I need to plot map marker using the values which I get from the JSONArray. I have used the following code.It is working fine when I pass the latitude and longitude values directly but when I pass the values fetched from JSONArray the map isnt getting plotted.
StringRequest stringRequest = new StringRequest(Request.Method.POST,url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONObject object = new JSONObject(response);
if (object.getInt("status") == 200) {
JSONArray jsonArray = object.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject pobj = jsonArray.getJSONObject(i);
lat = Double.parseDouble(pobj.getString("latitude"));
lon = Double.parseDouble(pobj.getString("longitude")); pobj.getDouble("latitude")+","+pobj.getDouble("longitude");
Log.i("MAP",""+response);
Log.i("lat-",""+lat);
Log.i("lon-",""+lon);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void DisplayTrack() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("geo:" + lat + "," + lon + "?q=" + lat + "," + lon + ")")); //NOT WORKING
intent.setData(Uri.parse("geo:" + 15.824730932928347 + "," + 74.50431285009074 + "?q=" + 15.824730932928347 + "," + 74.50431285009074 + ")")); //WORKING
startActivity(intent);
}
Below is my data:
"data": [
{
"id": "43",
"site_no": "361",
"p_id_no": "68-1-361",
"sas_application_no": "95534",
"latitude": "15.824730932928347",
"longitude": "74.50431285009074",
From the comments: With this logic you're assigning the lat& lon of the last object in your jsonArray. It's most likely that by the time you reach your last object, one of your object has caused some JSONException or your last element has empty or null value. In any case it's being assigned null value. Do check your JSON response fully.
So I created a little demo how you can do it. Read the inline comments to understand:
public class MainActivity extends AppCompatActivity {
//declare the global variable, initially they are null
private Double lat, lon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// prepare request
StringRequest stringRequest = new StringRequest(Request.Method.POST, "url",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONObject object = new JSONObject(response);
//check
if (object.getInt("status") == 200) {
JSONArray jsonArray = object.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
//keep getting the new objects
JSONObject pobj = jsonArray.getJSONObject(i);
//assign the last object lat/lon
lat = Double.parseDouble(pobj.getString("latitude"));
lon = Double.parseDouble(pobj.getString("longitude"));
}
//if they are not null then call the activity
if (lat != null && lon != null) {
DisplayTrack(lat, lon);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// call your request like you do
}
//declared the function out of the Network call scope
private void DisplayTrack(Double lat, Double lon) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("geo:" + lat + "," + lon + "?q=" + lat + "," + lon + ")")); //NOT WORKING
startActivity(intent);
}
}
Related
I need to show my 'Npc' markers on the map , but the npcList in onMapReady() is empty. How can i put the right way my Npcs from getNPC() npcList in onMapReady() npcList and then display the markers on map
my onMapReady():
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//zoom map camera
// Get LocationManager object
LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = (locationManager).getBestProvider(criteria, true);
Location myLocation = (locationManager).getLastKnownLocation(provider);
// myLastLoc = myLocation;
if (myLocation != null) {
//latitude of location
double myLatitude = myLocation.getLatitude();
//longitude og location
double myLongitude = myLocation.getLongitude();
LatLng latLon = new LatLng(myLatitude, myLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLon, 17));
}
mGoogleMap.setMyLocationEnabled(true);//koumpi gia location
buildGoogleApiClient(); // mallon mpilia
// locationManager.requestLocationUpdates(provider,1000,1f,com.google.android.gms.location.LocationListener);
npcList = new ArrayList<Npc>();
getNPC();
for(Npc mynpc:npcList) {
if (!npcList.isEmpty()) {
LatLng loc = new LatLng(mynpc.getNpclat(), mynpc.getNpclng());
String name = mynpc.getNpcname();
mGoogleMap.addMarker(new MarkerOptions()
.position(loc)
.title(name));
} else {
Toast.makeText(getActivity().getApplicationContext(), "npcList is empty", Toast.LENGTH_LONG).show();
}
}
}
my getNPC():
private void getNPC() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.URL_NPC_GET,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
Log.i("GAME_TAG", "response caught");
boolean error = obj.getBoolean("error");
if (!error) {
Log.i("GAME_TAG", "response showing return no error");
//converting the string to json array object
JSONArray array = obj.getJSONArray("results");
Log.i("GAME_TAG", "response has " + array.length() + " npcs");
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting npc object from json array
JSONObject npc = array.getJSONObject(i);
//adding the npc to npc list
npcList.add(new Npc(
npc.getInt("npcid"),
npc.getInt("userid"),
npc.getString("npcname"),
npc.getString("npcwelcome"),
(float) npc.getLong("npclat"),
(float) npc.getLong("npclng")
));
Log.i("GAME_TAG", "now arraylist has " + npcList.size() + " npcs");
Npc mynpc = npcList.get(i);
LatLng loc = new LatLng(mynpc.getNpclat(), mynpc.getNpclng());
String name = mynpc.getNpcname();
mGoogleMap.addMarker(new MarkerOptions()
.position(loc)
.title(name));
Log.i("GAME_TAG", "npc name "+ name+" " +loc);
}
Log.i("GAME_TAG", "if this sentence showing and still no marker, lets try adding only one marker");
LatLng loc = new LatLng(npcList.get(0).getNpclat(), npcList.get(0).getNpclng());
String name = npcList.get(0).getNpcname();
mGoogleMap.addMarker(new MarkerOptions()
.position(loc)
.title(name));
Log.i("GAME_TAG", "if this sentence showing and with one marker, something wrong with the loop");
} else {
Log.i("GAME_TAG", "response showing return with error");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestHandler.getInstance(getActivity()).addToRequestQueue(stringRequest);
}
my Npc class:
package com.example.game1;
public class Npc {
private int npcid;
private int userid;
private String npcname;
private String npcwelcome;
private float npclat;
private float npclng;
public Npc(int npcid,int userid,String npcname,String npcwelcome,float npclat,float npclng){
this.npcid = npcid;
this.userid = userid;
this.npcname = npcname;
this.npcwelcome = npcwelcome;
this.npclat = npclat;
this.npclng = npclng;
}
public int getNpcid() {
return npcid;
}
public int getUserid() {
return userid;
}
public String getNpcname() {
return npcname;
}
public String getNpcwelcome() {
return npcwelcome;
}
public float getNpclat() {
return npclat;
}
public float getNpclng() {
return npclng;
}
}
im retrieving the right values from db as you can see in image bellow
image
please help me im stuck
try this, move your looping for adding marker in response after adding to your arraylist
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//zoom map camera
// Get LocationManager object
LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = (locationManager).getBestProvider(criteria, true);
Location myLocation = (locationManager).getLastKnownLocation(provider);
// myLastLoc = myLocation;
if (myLocation != null) {
//latitude of location
double myLatitude = myLocation.getLatitude();
//longitude og location
double myLongitude = myLocation.getLongitude();
LatLng latLon = new LatLng(myLatitude, myLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLon, 17));
}
mGoogleMap.setMyLocationEnabled(true);//koumpi gia location
buildGoogleApiClient(); // mallon mpilia
// locationManager.requestLocationUpdates(provider,1000,1f,com.google.android.gms.location.LocationListener);
npcList = new ArrayList<Npc>();
getNPC();
}
your getnpc()
private void getNPC() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.URL_NPC_GET,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
Log.i("GAME_TAG", "response caught");
boolean error = obj.getBoolean("error");
if (!error) {
Log.i("GAME_TAG", "response showing return no error");
//converting the string to json array object
JSONArray array = obj.getJSONArray("results");
Log.i("GAME_TAG", "response has " + array.length() + " npcs");
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting npc object from json array
JSONObject npc = array.getJSONObject(i);
//adding the npc to npc list
npcList.add(new Npc(
npc.getInt("npcid"),
npc.getInt("userid"),
npc.getString("npcname"),
npc.getString("npcwelcome"),
npc.getLong("npclat"),
npc.getLong("npclng")
));
}
Log.i("GAME_TAG", "now arraylist has " + npcList.size() + " npcs");
for (Npc mynpc : npcList) {
LatLng loc = new LatLng(mynpc.getNpclat(), mynpc.getNpclng());
String name = mynpc.getNpcname();
mGoogleMap.addMarker(new MarkerOptions()
.position(loc)
.title(name));
}
Log.i("GAME_TAG", "if this sentence showing and still no marker, lets try adding only one marker");
LatLng loc = new LatLng(npcList.get(0).getNpclat(), npcList.get(0).getNpclng());
String name = npcList.get(0).getNpcname();
mGoogleMap.addMarker(new MarkerOptions()
.position(loc)
.title(name));
Log.i("GAME_TAG", "if this sentence showing and with one marker, something wrong with the loop");
} else {
Log.i("GAME_TAG", "response showing return with error");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestHandler.getInstance(getActivity()).addToRequestQueue(stringRequest);
}
Hope it helps.
i did a few changes to getNPC() and now it works here is the code:
private void getNPC() {
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Constants.URL_NPC_GET,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
Log.i("GAME_TAG", "response caught");
boolean error = obj.getBoolean("error");
if (!error) {
Log.i("GAME_TAG", "response showing return no error");
//converting the string to json array object
JSONArray array = obj.getJSONArray("results");
Log.i("GAME_TAG", "response has " + array.length() + " npcs");
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting npc object from json array
JSONObject npc = array.getJSONObject(i);
//adding the npc to npc list
npcList.add(new Npc(
npc.getInt("npcid"),
npc.getInt("userid"),
npc.getString("npcname"),
npc.getString("npcwelcome"),
(float) npc.getDouble("npclat"),
(float) npc.getDouble("npclng")
));
Log.i("GAME_TAG", "now arraylist has " + npcList.size() +
" npcs");
Npc mynpc = npcList.get(i);
LatLng loc = new LatLng(mynpc.getNpclat(),
mynpc.getNpclng());
String name = mynpc.getNpcname();
mGoogleMap.addMarker(new MarkerOptions()
.position(loc)
.title(name));
Log.i("GAME_TAG", "npc name "+ name+" " +loc);
}
Log.i("GAME_TAG", "if this sentence showing and still no
marker, lets try adding only one marker");
LatLng loc = new LatLng(npcList.get(0).getNpclat(),
npcList.get(0).getNpclng());
String name = npcList.get(0).getNpcname();
mGoogleMap.addMarker(new MarkerOptions()
.position(loc)
.title(name));
Log.i("GAME_TAG", "if this sentence showing and with one marker, something wrong with the loop");
} else {
Log.i("GAME_TAG", "response showing return with error");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestHandler.getInstance(getActivity()).addToRequestQueue(stringRequest);
}
I am writing an application for android and using the volley library. I need to write the received data into TextResult. How to do it?
private void jsonParse() {
String url = "https://api.apixu.com/v1/current.json?key=...&q=Paris";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("location");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject location = jsonArray.getJSONObject(i);
String name = location.getString("name");
String region = location.getString("region");
String country = location.getString("country");
TextResult.append(name + ", " + region + ", " + country + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
Json response example
{"location":{"name":"Paris","region":"Ile-de-France","country":"France"}}
Use this piece of code.
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject = response.getJSONObject("location");
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray location = jsonObject.getJSONArray(i);
String name = location.getString("name");
String region = location.getString("region");
String country = location.getString("country");
TextResult.append(name + ", " + region + ", " + country + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
{"location":{"name":"Paris","region":"Ile-de-France","country":"France"}}
Its not a JSONArray its a JSONObject.
First get the location from JSONObject.
String location_value=response.get("location");
JSONObject location=new JSONObject(location_value);
String name = location.getString("name");
String region = location.getString("region");
String country = location.getString("country");
TextResult.append(name + ", " + region + ", " + country + "\n\n");
local host giving me data in browser as shown in screenshot but Volly class giving me 'Request timed out.'
*it was working well in window 8 but recently i changed my window 8 to 10 so now i am facing this problem but i think it is not happen with this reason *
public DataPoint[] getTimeAndU() {
final DataPoint[] dataPoint = new DataPoint[2000];
final DataTransmit dataTransmit = new DataTransmit(mContext) {
#Override
protected void onCompleted(String json) {
Log.v("joson",json);
if (json != null) {
// Toast.makeText(this,"sucess"+json+"",Toast.LENGTH_LONG).show();
try {
Log.v("testt","dtsfasdf");
// JSONArray ja = new JSONArray(json);
JSONObject jo = new JSONObject(json);
for(int i = 0; i < jo.length(); i++){
if (i > 1) {
JSONObject obj2 = jo.getJSONObject("a"+i);
double x = toDouble(obj2.getString("time_s"));
double y = toDouble( obj2.getString("u_mv"));
dataPoint[i] = new DataPoint(x,y);
}else{
dataPoint[i] = new DataPoint(0,0);
}
}
} catch (Throwable t) {
Log.e("app", "Could not parse malformed JSON: \"" + String.valueOf(t) + "\"");
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}
}
}
};
//dataTransmit.requestJasonArray("http://192.168.1.12//Rehan/UrbanClout.php?FunctionKey=loginUser&login_name=aaa&login_pass=aaa", "Schedule");
// dataTransmit.requestJasonArray("http://192.168.1.8/ahsan_bhai_project/excel_reader/excel_reader/example.php", "Schedule");
dataTransmit.requestJasonObject("http://192.168.10.32/ahsan_bhai_project/excel_reader/excel_reader/example.php?FunctionKey=time_u","Schedule");
return dataPoint;
}
here my services in php
I was trying to add markers to a map automatically after getting the data from JSON, with the position that is in the api, this is what I have:
#Override
protected Void doInBackground(Void... params) {
HttpHandler sh2 = new HttpHandler();
final String jsonStrOportunidades = sh2.makeServiceCall(urlOportunidades);
Log.e(TAG, "Response from URL: " + jsonStrOportunidades);
if (jsonStrOportunidades != null) {
try {
JSONArray array = new JSONArray(jsonStrOportunidades);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String Designacao = jsonObject.getString("Designacao");
String Coord_LAT = jsonObject.getString("Coord_LAT");
String Coord_LONG = jsonObject.getString("Coord_LONG");
HashMap<String, String> oportunidades = new HashMap<>();
oportunidades.put("Designacao", Designacao);
oportunidades.put("Coord_LAT", Coord_LAT);
oportunidades.put("Coord_LONG", Coord_LONG);
double lat1 = Double.parseDouble(Coord_LAT);
double lng1 = Double.parseDouble(Coord_LONG);
mMap.addMarker(new MarkerOptions().position(new LatLng(lat1, lng1)));
listaOportunidades.add(oportunidades);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Json parsin error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
return null;
}
"mMap.addMarker" doesn't work, is it even possible creating markers from there?
Try setting the marker from onPostExecute. doInBackground isn't the place to update UI components.
#Override
protected String doInBackground(Void... params) {
HttpHandler sh2 = new HttpHandler();
final String jsonStrOportunidades = sh2.makeServiceCall(urlOportunidades);
Log.e(TAG, "Response from URL: " + jsonStrOportunidades);
return jsonStrOportunidades;
}
#Override
protected void onPostExecute(String jsonStrOportunidades){
if (jsonStrOportunidades != null) {
try {
JSONArray array = new JSONArray(jsonStrOportunidades);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String Designacao = jsonObject.getString("Designacao");
String Coord_LAT = jsonObject.getString("Coord_LAT");
String Coord_LONG = jsonObject.getString("Coord_LONG");
HashMap<String, String> oportunidades = new HashMap<>();
oportunidades.put("Designacao", Designacao);
oportunidades.put("Coord_LAT", Coord_LAT);
oportunidades.put("Coord_LONG", Coord_LONG);
double lat1 = Double.parseDouble(Coord_LAT);
double lng1 = Double.parseDouble(Coord_LONG);
mMap.addMarker(new MarkerOptions().position(new LatLng(lat1, lng1)));
listaOportunidades.add(oportunidades);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
Toast.makeText(getApplicationContext(), "Json parsin error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
Also, you need to change the AsyncTask class like this
YourAsyncTaskClass extends AsyncTask<String, Void, String>
I have been finding ways to resolve on how to pass multiple values from one class to the other.
I recently found a way which is to use putSerializable to do it but has not been successful. I only been able to return the last longitude and latitude to the other class.
This is my array json string:
{"longitude":"101.9366229","latitude":"1.236459"},
{"longitude":"101.930041","latitude":"1.224119"}]
Below are my code to pass the values:
class Findfriends extends AsyncTask<String, String, JSONObject> {
final String TAG = "Findfriends.java";
protected JSONObject doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
try {
HashMap<String, String> params = new HashMap<>();
params.put("username", args[0]);
JSONObject json = jsonParser.makeHttpRequest(
GET_FRIENDS, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
if (json != null) {
Toast.makeText(Borrower_AP.this, json.toString(),
Toast.LENGTH_LONG).show();
try {
dataJsonArr = json.getJSONArray("Posts");
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
Longitude = c.getDouble("longitude");
Latitude = c.getDouble("latitude");
Log.e(TAG, "Longitude: " + Longitude
+ ", Latitude: " + Latitude);
coordinates.setLongt(Longitude);
coordinates.setLat(Latitude);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public class Coordinates implements Serializable {
private Double lat;
private Double longt;
public Double getLat () {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
public Double getLongt() {
return longt;
}
public void setLongt(Double longt) {
this.longt = longt;
}
}
Get the values back:
Intent intent=this.getIntent();
Bundle bundle=intent.getExtras();
Coordinates coordinates=(Coordinates)bundle.getSerializable("coordinates");
System.out.println("Lat:" + coordinates.getLat());
System.out.println("Long:" + coordinates.getLongt());
for your requirement you need Arraylist of your class Coordinates just add objects to it in loop where you parsing json and just send it to another activity and in new activity get it by casting it to Coordinates arraylist
here is the sample
if i consider coordinates in onpost method is arraylist
ArrayList<Coordinates> coordinates=new ArrayList<Coordinates>();
in your onpost forloop
use following
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
Longitude = c.getDouble("longitude");
Latitude = c.getDouble("latitude");
Log.e(TAG, "Longitude: " + Longitude
+ ", Latitude: " + Latitude);
Coordinates coordinatesobj=new Coordinates();
coordinatesobj.setLongt(Longitude);
coordinatesobj.setLat(Latitude);
coordinates.add(coordinatesobj);
}
where you starting new activity there put below
Intent intent = new Intent(SourceActivity.this, TargetActivity.class);
intent.putExtra("key", coordinates);
at receiving side activity
Intent intent=this.getIntent();
Bundle bundle=intent.getExtras();
ArrayList<Coordinates> coordinates=( ArrayList<Coordinates>)bundle.getSerializable("key");
hope it helps