markers don't show on map and i don't understand error
My json file:[
{
"name": "aaaa",
"lat": 35.747394,
"lang": 51.267577
}
]
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
List<Position> positionsList = new ArrayList<>();
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//delete if static
PositionsTask positionsTask = new PositionsTask();
positionsTask.execute();
// end delete
// positionsList.add(new Position("beb souika",1,1));
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng TUNIS = new LatLng(36.818248, 10.182416);
for(Position pos: positionsList){
LatLng latLng = new LatLng(pos.getLatitude(),pos.getLongitude());
if(mMap!=null){
mMap.addMarker(new MarkerOptions().position(latLng).title(pos.getName()));
}
}
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(TUNIS,11));
}
private class PositionsTask extends AsyncTask<Void, Void, Void> {
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_LATITUDE = "latitude";
private static final String TAG_lONGITUDE = "longitude";
#Override
protected void onPreExecute(){
progressDialog = new ProgressDialog(MapsActivity.this);
progressDialog.setMessage("Chargement en cours ...");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String link;
BufferedReader bufferedReader;
String result="[]";
try {
link = "http://192.168.8.105/map1.php";
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
StringBuilder sb = new StringBuilder() ;
while ((line = bufferedReader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.e("Exception: ",e.getMessage());
}
positionsList = getPositionList(result);
return null;
}
#Override
protected void onPostExecute(Void params) {
progressDialog.dismiss();
}
#Override
protected void onCancelled() {
progressDialog.dismiss();
}
protected List getPositionList(String myJSON){
List<Position> positions = new ArrayList<>();
try {
JSONArray data = new JSONArray(myJSON);
for(int i=0;i<data.length();i++){
Position position = new Position();
JSONObject json = data.getJSONObject(i);
position.setId(json.getInt(TAG_ID));
position.setName(json.getString(TAG_NAME));
position.setLatitude(json.getDouble(TAG_LATITUDE));
position.setLongitude(json.getDouble(TAG_lONGITUDE));
positions.add(position);
}
} catch (JSONException e) {
e.printStackTrace();
}
return positions;
}
}
}
04-23 21:33:16.491 2567-3598/? E/Parcel: Class not found when unmarshalling: com.facebook.search.api.GraphSearchQuery
java.lang.ClassNotFoundException: com.facebook.search.api.GraphSearchQuery
at java.lang.Class.classForName(Native Method)
at java.lang.Class.forName(Class.java:324)
at android.os.Parcel.readParcelableCreator(Parcel.java:2404)
at android.os.Parcel.readParcelable(Parcel.java:2358)
at android.os.Parcel.readValue(Parcel.java:2264)
at android.os.Parcel.readArrayMapInternal(Parcel.java:2614)
at android.os.BaseBundle.unparcel(BaseBundle.java:221)
at android.os.BaseBundle.getString(BaseBundle.java:920)
at android.content.Intent.getStringExtra(Intent.java:6221)
at com.android.server.am.ActivityStackSupervisor.startActivityLocked(ActivityStackSupervisor.java:2751)
at com.android.server.am.ActivityStackSupervisor.startActivityMayWait(ActivityStackSupervisor.java:2209)
at com.android.server.am.ActivityManagerService.startActivityAsUser(ActivityManagerService.java:6591)
at com.android.server.am.ActivityManagerService.startActivity(ActivityManagerService.java:6346)
at android.app.ActivityManagerNative.onTransact(ActivityManagerNative.java:170)
at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:4166)
at android.os.Binder.execTransact(Binder.java:453)
Caused by: java.lang.ClassNotFoundException: com.facebook.search.api.GraphSearchQuery
at java.lang.Class.classForName(Native Method)
at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
at java.lang.Class.classForName(Native Method)
at java.lang.Class.forName(Class.java:324)
at android.os.Parcel.readParcelableCreator(Parcel.java:2404)
at android.os.Parcel.readParcelable(Parcel.java:2358)
at android.os.Parcel.readValue(Parcel.java:2264)
at android.os.Parcel.readArrayMapInternal(Parcel.java:2614)
at android.os.BaseBundle.unparcel(BaseBundle.java:221)
at android.os.BaseBundle.getString(BaseBundle.java:920)
at android.content.Intent.getStringExtra(Intent.java:6221)
at com.android.server.am.ActivityStackSupervisor.startActivityLocked(ActivityStackSupervisor.java:2751)
at com.android.server.am.ActivityStackSupervisor.startActivityMayWait(ActivityStackSupervisor.java:2209)
at com.android.server.am.ActivityManagerService.startActivityAsUser(ActivityManagerService.java:6591)
at com.android.server.am.ActivityManagerService.startActivity(ActivityManagerService.java:6346)
at android.app.ActivityManagerNative.onTransact(ActivityManagerNative.java:170)
at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:4166)
at android.os.Binder.execTransact(Binder.java:453)
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
when i tried to put direction from source to destination on map
this null pointer exception heppen
when i tried to put direction from source to destination on map
this null pointer exception heppen
l
ocat:
07-05 02:19:21.569 23133-23133/com.example.saad.testapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.saad.testapp, PID: 23133
java.lang.NullPointerException
at com.example.saad.testapp.map$TaskParser.onPostExecute(map.java:248)
at com.example.saad.testapp.map$TaskParser.onPostExecute(map.java:205)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5511)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
map.class is as follows :
public class map extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
loc ambLoc;
loc patLoc;
String tempE;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
ambLoc=new loc();
patLoc=new loc();
tempE=new String();
}
#Override
public void onMapReady(GoogleMap googleMap) {
getPoints();
}
void getPoints()
{
//some code here
String url=getRequestUrl(ambLoc,patLoc);
TaskRequestDirections taskRequestDirections = new TaskRequestDirections();
taskRequestDirections.execute(url);
}
private String getRequestUrl(loc origin, loc dest) {
//Value of origin
String str_org = "origin=" + origin.getLatitude() +","+origin.getLongitude();
//Value of destination
String str_dest = "destination=" + dest.getLatitude()+","+dest.getLongitude();
//Set value enable the sensor
String sensor = "sensor=false";
//Mode for find direction
String mode = "mode=driving";
//Build the full param
String param = str_org +"&" + str_dest + "&" +sensor+"&" +mode;
//Output format
String output = "json";
//Create url to request
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + param;
return url;
}
private String requestDirection(String reqUrl) throws IOException {
String responseString = "";
InputStream inputStream = null;
HttpURLConnection httpURLConnection = null;
try{
URL url = new URL(reqUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
//Get the response result
inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
responseString = stringBuffer.toString();
bufferedReader.close();
inputStreamReader.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
inputStream.close();
}
httpURLConnection.disconnect();
}
return responseString;
}
public class TaskRequestDirections extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
String responseString = "";
try {
responseString = requestDirection(strings[0]);
} catch (IOException e) {
e.printStackTrace();
}
return responseString;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//Parse json here
TaskParser taskParser = new TaskParser();
taskParser.execute(s);
}
}
having exception on the below line
public class TaskParser extends AsyncTask<String, Void, List<List<HashMap<String, String>>> > {
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... strings) {
JSONObject jsonObject = null;
List<List<HashMap<String, String>>> routes = null;
try {
jsonObject = new JSONObject(strings[0]);
DirectionParser directionsParser = new DirectionParser();
routes = directionsParser.parse(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> lists) {
//Get list route and display it into the map
ArrayList points = null;
PolylineOptions polylineOptions = null;
for (List<HashMap<String, String>> path : lists) {
points = new ArrayList();
polylineOptions = new PolylineOptions();
for (HashMap<String, String> point : path) {
double lat = Double.parseDouble(point.get("lat"));
double lon = Double.parseDouble(point.get("lon"));
points.add(new LatLng(lat,lon));
}
polylineOptions.addAll(points);
polylineOptions.width(15);
polylineOptions.color(Color.BLUE);
polylineOptions.geodesic(true);
}
if (polylineOptions!=null) {
Toast.makeText(getApplicationContext(), "adding polyline!", Toast.LENGTH_SHORT).show();
having exception on the
mMap.addPolyline(polylineOptions);
} else {
Toast.makeText(getApplicationContext(), "Direction not found!", Toast.LENGTH_SHORT).show();
}
}
}
}
suggest any solution if you have
thank you
thank you
thank you
thank you
You never set mMap variable try like this
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
getPoints();
}
the error is "Error connecting to service"
public class MarkerTask extends AsyncTask<Void, Void, String>
{
private static final String LOG_TAG = "ExampleApp";
private static final String SERVICE_URL = "https://192.168.8.103/map1.php";
private GoogleMap mMap;
// Invoked by execute() method of this object
#Override
protected String doInBackground(Void... args) {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
// Connect to the web service
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Read the JSON data into the StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to service", e);
//throw new IOException("Error connecting to service", e); //uncaught
} finally {
if (conn != null) {
conn.disconnect();
}
}
return json.toString();
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String json) {
try {
// De-serialize the JSON string into an array of city objects
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
LatLng latLng = new LatLng(jsonObj.getJSONArray("marker").getDouble(0),
jsonObj.getJSONArray("marker").getDouble(1));
//move CameraPosition on first result
if (i == 0) {
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng).zoom(13).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
// Create a marker for each city in the JSON data.
mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
.title(jsonObj.getString("name"))
.snippet(Integer.toString(jsonObj.getInt("population")))
.position(latLng));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON", e);
}
}
}
My map Activity
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
if (mapFragment != null) {
//setUpMap();
new MarkerTask().execute();
}
}}
I developed an app in which i am receiving latitude and longitude through API REST from my server, so what i want is that the api call will be solved before the display of such coordinates on map. Please guide me how to do this.
I've already implemented a solution but it seems to not work.
From the stack trace I've got this message:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: pro.rane.myapplication, PID: 1590
java.lang.NullPointerException: Attempt to get length of null array
at pro.rane.myapplication.MapsActivity.onMapReady(MapsActivity.java:160)
at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzt$zza.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:392)
at com.google.android.gms.maps.internal.bw.a(:com.google.android.gms.DynamiteModulesB:82)
at com.google.maps.api.android.lib6.impl.bf.run(:com.google.android.gms.DynamiteModulesB:1805)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
I am conscious that this error is caused by the fact that function getCoordinates() doesn't work properly. I've also tried in past to use Volley library but it didn't work in same way. How can I make my API request works ?
Please note that the url is working, if you do your own get request on my server you can see the correct result in your browser.
Here's my code:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final String LATITUDE = "latitude";
private static final String LONGITUDE = "longitude";
private GoogleMap mMap;
private String info;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Bundle b = getIntent().getExtras();
if (b != null)
info = b.getString("qrCodeInformation");
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
/*connection to obtain the array of positions*/
private static String[][] getCoordinates(String tran_id) throws JSONException {
String dummy_tran_id = "1";
String richiesta = "http://myurl/getArticleTravel?tran_id=" + dummy_tran_id;
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpGet request = new HttpGet(richiesta);
request.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = "";
try {
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("Errore http request",""+e.getMessage());
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {
Log.i(squish.getMessage(), squish.getMessage());
}
}
JSONArray jObject;
String[][] coordinates;
jObject = new JSONArray(result);
String[] latitude = new String[jObject.length()];
String[] longitude = new String[jObject.length()];
for (int i = 0; i < jObject.length(); i++) {
latitude[i] = jObject.getJSONObject(i).getString(LATITUDE);
longitude[i] = jObject.getJSONObject(i).getString(LONGITUDE);
}
coordinates = new String[latitude.length][longitude.length];
for(int i =0; i < latitude.length;i++){
coordinates[i][0] = latitude[i];
coordinates[i][1] = longitude[i];
}
//String[][] dummy_coordinates = {{"45.465454", "9.186515999999983"}, {"41.9027835", "12.496365500000024"}};
return coordinates;
//return dummy_coordinates;
}
#Override
public void onMapReady(GoogleMap googleMap) {
String[][] coordinates = {{"45.465454", "9.186515999999983"}, {"41.9027835", "12.496365500000024"},{"40.9027835", "15.496365500000024"}}; //= null;
try {
coordinates = getCoordinates(info);
} catch (JSONException e) {
e.printStackTrace();
}
Integer a;
mMap = googleMap;
View marker = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker_layout, null);
TextView numTxt = (TextView) marker.findViewById(R.id.num_txt);
for (a = 0; a < coordinates.length; a++) {
if(a==0){
numTxt.setText("Go");
mMap.addMarker(new MarkerOptions()
.position(new LatLng(Double.parseDouble(coordinates[a][0]), Double.parseDouble(coordinates[a][1])))
.title("GO")
.snippet("Start point "+ a.toString())
.icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(this, marker)))
);
}else {
numTxt.setText(a.toString());
mMap.addMarker(new MarkerOptions()
.position(new LatLng(Double.parseDouble(coordinates[a][0]), Double.parseDouble(coordinates[a][1])))
.title(a.toString())
.snippet("Arrival point " + a.toString())
.icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(this, marker)))
);
}
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(Double.parseDouble(coordinates[a][0]), Double.parseDouble(coordinates[a][1])),5));
}
}
// Convert a view to bitmap
public static Bitmap createDrawableFromView(Context context, View view) {
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
view.setLayoutParams(new DrawerLayout.LayoutParams(DrawerLayout.LayoutParams.WRAP_CONTENT, ViewPager.LayoutParams.WRAP_CONTENT));
view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
view.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.disconnect();
}
}
Extend the AsyncTask class and use doInBackground to handle the work from getCoordinates in a background thread.
public class YourAsyncTask extends AsyncTask<Void, Void, YourReturnType> {
public interface OnFinishListener{
void onFinish(YourReturnType result);
}
private OnFinishListener mListener;
public OnFinishListener setOnFinishListener(#Nullable OnFinishListener l){
mListener = l;
}
#Override
protected YourReturnType doInBackground(Void... params) {
// Replace all "YourReturnType" with the actual type/object you want to return
YourReturnType returnValue;
// Do your work here and build/create your returnValue
return returnValue;
}
// This will get called automatically after doInBackground finishes
#Override
protected void onPostExecute(YourReturnType result) {
// If listener is set
if(mListener != null){
mListener.onFinish(result); // Return the returnValue
}
}
}
In your Activity when you want to get the coordinate values, execute your AsyncTask and set the listener interface;
YourAsyncTask yourTask = new YourAsyncTask();
yourTask.execute();
yourTask.setOnFinishListener(new YourAsyncTask.OnFinishListener(){
#Override
public void onFinish(YourReturnType result){
// Retrieve your returned value from result
// And if mMap is ready, perform map actions
}
});
AsyncTask documentation
So Im trying to display markers on my map from a Jsonfile and they are not appearing Ive narrowed it down to the line
map = mapFragment.getMapAsync(this);
it gives me the error
Incompatible types:
Required: com.google.android.gms.maps.GoogleMap Found: Void
Here is the rest of the code:
public class MainActivity extends FragmentActivity implements OnMapReadyCallback {
private static final String LOG_TAG = "ExampleApp";
private static final String SERVICE_URL = "https://api.myjson.com/bins/4jb09";
protected GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (map == null) {
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
map = mapFragment.getMapAsync(this);
if (map != null) {
//setUpMap();
new MarkerTask().execute();
}
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
setUpMap();
}
private void setUpMap() {
// Retrieve the city data from the web service
// In a worker thread since it's a network operation.
new Thread(new Runnable() {
public void run() {
try {
retrieveAndAddCities();
} catch (IOException e) {
Log.e(LOG_TAG, "Cannot retrive cities", e);
return;
}
}
}).start();
}
protected void retrieveAndAddCities() throws IOException {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
// Connect to the web service
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Read the JSON data into the StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to service", e);
throw new IOException("Error connecting to service", e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
// Create markers for the city data.
// Must run this on the UI thread since it's a UI operation.
runOnUiThread(new Runnable() {
public void run() {
try {
createMarkersFromJson(json.toString());
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON", e);
}
}
});
}
void createMarkersFromJson(String json) throws JSONException {
// De-serialize the JSON string into an array of city objects
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
// Create a marker for each city in the JSON data.
JSONObject jsonObj = jsonArray.getJSONObject(i);
map.addMarker(new MarkerOptions()
.title(jsonObj.getString("name"))
.snippet(Integer.toString(jsonObj.getInt("population")))
.position(new LatLng(
jsonObj.getJSONArray("latlng").getDouble(0),
jsonObj.getJSONArray("latlng").getDouble(1)
))
);
}
}
private class MarkerTask extends AsyncTask<Void, Void, String> {
private static final String LOG_TAG = "ExampleApp";
private static final String SERVICE_URL = "https://api.myjson.com/bins/4jb09";
// Invoked by execute() method of this object
#Override
protected String doInBackground(Void... args) {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
// Connect to the web service
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Read the JSON data into the StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to service", e);
//throw new IOException("Error connecting to service", e); //uncaught
} finally {
if (conn != null) {
conn.disconnect();
}
}
return json.toString();
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String json) {
try {
// De-serialize the JSON string into an array of city objects
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
LatLng latLng = new LatLng(jsonObj.getJSONArray("latlng").getDouble(0),
jsonObj.getJSONArray("latlng").getDouble(1));
//move CameraPosition on first result
if (i == 0) {
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng).zoom(13).build();
map.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
// Create a marker for each city in the JSON data.
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
.title(jsonObj.getString("name"))
.snippet(Integer.toString(jsonObj.getInt("population")))
.position(latLng));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON", e);
}
}
}
}
Change it to
map.getMapAsync(this);
instead of
map = mapFragment.getMapAsync(this);
because
#Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap = googleMap;
}
return type of this method is void, so it will not return anything.
You have to do this:
map.getMapAsync(this)
mapFragment.getMapAsync(this); has return type Void
Change your setUpMapIfNeeded() to following one
private void setUpMapIfNeeded() {
if (map == null) {
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
}
Do the marker setting work in onMapReady().
Use SupportMapFragment instead of MapFragment.You can take help from following code sample.
Define MapFragment as :
private SupportMapFragment supportMapFragment;
GoogleMap mGoogleMap; //for google map
And in your activity creation, you can do like this:
if(supportMapFragment==null){
supportMapFragment = (SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
//do load your map and other map stuffs here...
}
});
hope this will help you ...
Your code is returning this error Incompatible types: Required: com.google.android.gms.maps.GoogleMap Found: Void
because getMapAsync() does not return anything. If you look at the documentation for this function:
public void getMapAsync (OnMapReadyCallback callback)
Sets a callback object which will be triggered when the GoogleMap instance is ready to be used.
Note:
This method must be called from the main thread. The callback will be executed in the main thread. In the case where Google Play services is not installed on the user's device, the callback will not be triggered until the user installs it. In the rare case where the GoogleMap is destroyed immediately after creation, the callback is not triggered. The GoogleMap object provided by the callback is non-null.
OnMapReadyCallback is an interface that needs implemented and passed to through this function. Nothing is currently assigned to your googleMap variable you should instead set its value in this block of code which implements OnMapReadyCallback
#Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap = googleMap;
}
I want to show item of list view in autocomplete text view when click on that item in the list view using the following code.
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, AdapterView.OnItemClickListener {
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
GoogleMap mMap;
SupportMapFragment mFragment;
Marker CurrentMarker,FindMarker;
Location mLastLocation;
CustomAutoCompleteTextView atvPlaces = null;
DownloadTask placesDownloadTask;
DownloadTask placeDetailsDownloadTask;
ParserTask placesParserTask;
ParserTask placeDetailsParserTask;
final int PLACES=0;
final int PLACES_DETAILS=1;
LatLng latLng;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
mFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mFragment.getMapAsync(this);
// Getting a reference to the AutoCompleteTextView
atvPlaces = (CustomAutoCompleteTextView) findViewById(R.id.atv_places);
atvPlaces.setThreshold(1);
// Adding textchange listener
atvPlaces.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Creating a DownloadTask to download Google Places matching "s"
placesDownloadTask = new DownloadTask(PLACES);
// Getting url to the Google Places Autocomplete api
String url = getAutoCompleteUrl(s.toString());
// Start downloading Google Places
// This causes to execute doInBackground() of DownloadTask class
placesDownloadTask.execute(url);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
lv = (ListView) findViewById(R.id.list);
lv.setOnItemClickListener(this);
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if(ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
if(ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)){
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
}else{
return true;
}
}
private String getAutoCompleteUrl(String place){
// Obtain browser key from https://code.google.com/apis/console
String key = "key=AIzaSyC_7RaIknbxXauB6n2xHNTZgRjg0eo5xog";
// place to be be searched
String input = "input="+place;
// place type to be searched
String types = "types=geocode";
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = input+"&"+types+"&"+sensor+"&"+key;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/autocomplete/"+output+"?"+parameters;
return url;
}
private String getPlaceDetailsUrl(String ref){
// Obtain browser key from https://code.google.com/apis/console
String key = "key=AIzaSyC_7RaIknbxXauB6n2xHNTZgRjg0eo5xog";
// reference of place
String reference = "reference="+ref;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = reference+"&"+sensor+"&"+key;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/details/"+output+"?"+parameters;
return url;
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
//Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
// mLocationRequest.setInterval(1000);
// mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED){
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest,this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if(CurrentMarker != null){
CurrentMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
MarkerOptions markerOption = new MarkerOptions();
markerOption.position(latLng);
markerOption.title("Current Position");
markerOption.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
CurrentMarker = mMap.addMarker(markerOption);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(13));
if(mGoogleApiClient != null){
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
==PackageManager.PERMISSION_GRANTED){
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResult){
switch (requestCode){
case MY_PERMISSIONS_REQUEST_LOCATION: {
if(grantResult.length > 0
&& grantResult[0] == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if(mGoogleApiClient == null){
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
}else {
Toast.makeText(this, "permisison denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
#Override
public void onItemClick(AdapterView adapterView, View view, int position, long id) {
String str = ((TextView) view.findViewById(R.id.place_name)).getText().toString();
Toast.makeText(this,str, Toast.LENGTH_SHORT).show();
}
private class DownloadTask extends AsyncTask<String, Void, String> {
private int downloadType = 0;
// Constructor
public DownloadTask(int type) {
this.downloadType = type;
}
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try {
// Fetching the data from web service
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
switch (downloadType) {
case PLACES:
// Creating ParserTask for parsing Google Places
placesParserTask = new ParserTask(PLACES);
// Start parsing google places json data
// This causes to execute doInBackground() of ParserTask class
placesParserTask.execute(result);
break;
case PLACES_DETAILS:
// Creating ParserTask for parsing Google Places
placeDetailsParserTask = new ParserTask(PLACES_DETAILS);
// Starting Parsing the JSON string
// This causes to execute doInBackground() of ParserTask class
placeDetailsParserTask.execute(result);
}
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
int parserType = 0;
public ParserTask(int type) {
this.parserType = type;
}
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
JSONObject jObject;
List<HashMap<String, String>> list = null;
try {
jObject = new JSONObject(jsonData[0]);
switch (parserType) {
case PLACES:
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
// Getting the parsed data as a List construct
list = placeJsonParser.parse(jObject);
break;
case PLACES_DETAILS:
PlaceDetailsJSONParser placeDetailsJsonParser = new PlaceDetailsJSONParser();
// Getting the parsed data as a List construct
list = placeDetailsJsonParser.parse(jObject);
}
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return list;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
switch (parserType) {
case PLACES:
String[] from = new String[]{"description"};
int[] to = new int[]{R.id.place_name};
// Creating a SimpleAdapter for the AutoCompleteTextView
//SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), result, android.R.layout.simple_list_item_1, from, to);
// Setting the adapter
// atvPlaces.setAdapter(lv);
// list adapter
ListAdapter adapter = new SimpleAdapter(MainActivity.this, result,R.layout.list_item,from,to);
// Adding data into listview
lv.setAdapter(adapter);
break;
case PLACES_DETAILS:
String location = atvPlaces.getText().toString();
if (location != null && !location.equals("")) {
new GeocoderTask().execute(location);
}
break;
}
}
}
private class GeocoderTask extends AsyncTask<String, Void, List<Address>> {
#Override
protected List<Address> doInBackground(String... locationName) {
// TODO Auto-generated method stub
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
protected void onPostExecute(List<Address> addresses) {
if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
}
for(int i=0;i<addresses.size();i++){
Address address = (Address)addresses.get(i);
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Find Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
FindMarker = mMap.addMarker(markerOptions);
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(13).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
}
}
I want to show selected item in autocompleteTextview from listView when click on that item. Please tell me using my source code.
#Override
public void onItemClick(AdapterView adapterView, View view, int position, long id) {
String str = ((TextView) view.findViewById(R.id.place_name)).getText().toString();
Toast.makeText(this,str, Toast.LENGTH_SHORT).show();
atvPlaces.setText(str);
atvPlaces.dismissDropDown();
}
Pls check this code, I modified.
String mSelectedItem;
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int ClikedPosition, long id) {
//Getting clicked item from list view
mSelectedItem=adapter.getItem(ClikedPosition);
//Setting to auto complete text view
mAutoCompleteTextView.setText(mSelectedItem);
}
});