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>
Related
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");
Data is not fetched through json parsing. I want to fetch data from url and just set it to a textview. please help
private static final String URL_PRODUCTS = "http://ebeautyapp.com/experts/getContactUs.php";
//method for json parcing
private void loadData() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
new Response.Listener < String > () {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
String result = jObj.getString("result");
if (result.equals("success")) {
JSONArray jsonArray = jObj.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String contact_id = jsonObject.getString("contact_id");
String fullname = jsonObject.getString("fullname");
String moble1 = jsonObject.getString("moble1");
String mobileno2 = jsonObject.getString("mobileno2");
String profile_pic = jsonObject.getString("profile_pic");
String address = jsonObject.getString("address");
String about_us = jsonObject.getString("about_us");
fulllnames.setText(fullname);
mobilenos.setText(moble1);
}
} else {
String status = jObj.getString("status");
Toast.makeText(getApplicationContext(), "" + status, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
Using this I have got the response from the server. Hope this will solve your problem.
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
protected void onPreExecute() {
// responseView.setText("");
}
protected String doInBackground(Void... urls) {
String API_URL = "http://ebeautyapp.com/experts/getContactUs.php";
// Do some validation here
try {
URL url = new URL(API_URL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
// progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
// responseView.setText(response);
// parseJsonData(response);
}
JSON parsing
private void jsonParsing(String response){
try {
JSONObject jObj = new JSONObject(response);
String result = jObj.getString("result");
if (result.equals("success")) {
JSONArray jsonArray = jObj.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String contact_id = jsonObject.getString("contact_id");
String fullname = jsonObject.getString("fullname");
String moble1 = jsonObject.getString("moble1");
String mobileno2 = jsonObject.getString("mobileno2");
String profile_pic = jsonObject.getString("profile_pic");
String address = jsonObject.getString("address");
String about_us = jsonObject.getString("about_us");
fulllnames.setText(fullname);
mobilenos.setText(moble1);
}
} else {
String status = jObj.getString("status");
Toast.makeText(getApplicationContext(), "" + status, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
And use this task as simple by using this
new RetrieveFeedTask().execute();
I want develop android application for one website. I read website posts from json and show its in RecyclerView every 10 posts.
I can show title, description and thumbnail. but i want show medium from thumbnail_images instance of thumbnail. I don't know how to read images from medium ?!
My Json Link : Link
AsyncTaskCodes:
public class MainDataInfo {
private Context mContext;
private String ServerAddress = ServerIP.getIP();
public void getMainDataInfo(Context context) {
mContext = context;
new getInfo().execute(ServerAddress + "page=1");
}
private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<MainDataModel> infoModels;
#Override
protected void onPreExecute() {
CustomProcessDialog.createAndShow(mContext);
infoModels = new ArrayList<>();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(ServerAddress + "page=1")
.build();
Response response;
try {
response = client.newCall(request).execute();
ou_response = response.body().string();
response.body().close();
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.getJSONArray("posts");
infoModels = new ArrayList<>();
for (int i = 0; i <= infoModels.size(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
int id = postObject.getInt("id");
String title = postObject.getString("title");
Log.d("Data", "Post id: " + id);
Log.d("Data", "Post title: " + title);
//Use the title and id as per your requirement
infoModels.add(new MainDataModel(
postObject.getInt("id"),
postObject.getString("title"),
postObject.getString("content"),
postObject.getString("thumbnail")));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return ou_response;
}
#Override
protected void onPostExecute(String result) {
CustomProcessDialog.dissmis();
if (result != null) {
bus.post(infoModels);
}
}
}
}
How can set images from medium ? thanks all <3
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.getJSONArray("posts");
for (int i= 0; i < postsArray.length(); i++){
JSONObject postObject = postsArray.getJSONObject(i);
int id = postObject.getInt("id");
String title = postObject.getString("title");
//get other data
JSONObject imageObj = postObject.getJSONObject("thumbnail_images");
JSONObject mediumObj = imageObj.getJSONObject("medium");
String mediumImage = mediumObj.getString("url");
Log.d("Data", "id: " + id);
Log.d("Data", "title: " + title);
//log other data
Log.d("Data", "the mediumObj url: " + mediumImage);
}
} catch (JSONException e) {
e.printStackTrace();
}
I am new to Json. I want to retrieve the distance between two places using json. I want to get "text"(Distance b/w two places) from "distance" object which is in "legs" array which in turn is in "routes" array.
Link(http://maps.googleapis.com/maps/api/directions/json?origin=Adoor&destination=Thiruvananthapuram%20Zoo&sensor=false)
Java code:
String uri="http://maps.googleapis.com/maps/api/directions/json?origin="+destination+"&destination="+tour_place+"&sensor=false";
queue= Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest objectRequest=new JsonObjectRequest(Request.Method.GET, uri, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray array=response.getJSONArray("legs");
distances.add(array.getJSONObject(0).getJSONObject("distance").getDouble("text"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error){
}
});
queue.add(objectRequest);
Okay, will now post the code I did. Try this out.
try {
JSONObject json = new JSONObject(jStr);
JSONArray jaRoutes = json.getJSONArray("routes");
JSONArray jaLegs = jaRoutes.getJSONObject(0).getJSONArray("legs");
JSONObject joDistance = jaLegs.getJSONObject(0).getJSONObject("distance");
String text = joDistance.getString("text");
Toast.makeText(this, text, Toast.LENGTH_SHORT);
} catch (JSONException e) {
Log.d("SAMPLE", e.toString());
}
Let me know if it works.
Try this,
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
JSONObject jDistance = null;
JSONObject jDuration = null;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for(int i=0;i<jRoutes.length();i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
List<HashMap<String, String>> path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for(int j=0;j<jLegs.length();j++){
/** Getting distance from the json data */
jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
HashMap<String, String> hmDistance = new HashMap<String, String>();
hmDistance.put("distance", jDistance.getString("text"));
/** Getting duration from the json data */
jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
HashMap<String, String> hmDuration = new HashMap<String, String>();
hmDuration.put("duration", jDuration.getString("text"));
/** Adding distance object to the path */
path.add(hmDistance);
/** Adding duration object to the path */
path.add(hmDuration);
jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for(int k=0;k<jSteps.length();k++){
String polyline = "";
polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
List<LatLng> list = decodePoly(polyline);
/** Traversing all points */
for(int l=0;l<list.size();l++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
path.add(hm);
}
}
}
routes.add(path);
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e){
}
Try code below:
try {
StringRequest sr = new StringRequest(Request.Method.GET, uri, (String) null, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pDialog.dismiss();
;
Log.d("", ".......response====" + response.toString());
////////
try {
JSONObject object = new JSONObject(response);
if (serverCode.equalsIgnoreCase("0")) {
}
if (serverCode.equalsIgnoreCase("1")) {
try {
if ("1".equals(serverCode))
{
JSONArray jsonArray = object.getJSONArray("routes");
if(jsonArray.length()>0)
{
for(int i=0; i<jsonArray.length(); i++)
{
JSONArray legs =jsonArray.getJSONArray("legs");
if(legs.length()>0)
{
for(int i=0; i<legs.length(); i++)
{
JSONObject object1 = legs.getJSONObject("distance");
String distance = object1.getString("text");
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
;
// VolleyLog.d("", "Error: " + error.getMessage());
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
Toast.makeText(ForgotPasswordActivity.this, "Timeout Error",
Toast.LENGTH_LONG).show();
} else if (error instanceof AuthFailureError) {
VolleyLog.d("", "" + error.getMessage() + "," + error.toString());
} else if (error instanceof ServerError) {
VolleyLog.d("", "" + error.getMessage() + "," + error.toString());
} else if (error instanceof NetworkError) {
VolleyLog.d("", "" + error.getMessage() + "," + error.toString());
} else if (error instanceof ParseError) {
VolleyLog.d("", "" + error.getMessage() + "," + error.toString());
}
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_email", email);
return params;
}
};
sr.setShouldCache(true);
sr.setRetryPolicy(new DefaultRetryPolicy(50000 * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(sr);
} catch (Exception e) {
e.printStackTrace();
}
Try this
try{
JSONObject object = new JSONObject(thewholething.toString());
JSONArray routes =object.getJSONArray("routes");
JSONArray legs=routes.getJSONObject(0).getJSONArray("legs")
JSONObject distance =legs.getJSONObject(0).getJSONObject("distance");
String text=distance.getString("text");
}
catch (JSONException e) {
e.printStackTrace();
}
Now the String text contains your value.
From your response, you parse your routes array first.
JsonArray routes = response.getJsonArray("routes");
From here, you can get legs array like the following.
JsonArray legs = routes.getJsonArray("legs");
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