Does not display incoming data with response - android

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");

Related

How to parse JSON data in volley liabrary?

I want parse JSON response.I am unable to parse response.It shows org.json.JSONException: No value for String Response this error.
Here is my code ` public void onResponse(JSONObject response) {
Log.d("TAG", "Details:" + response);
responseTV.setText("String Response : " + response.toString());
try {
JSONObject jsonObject = response.getJSONObject("String Response"+response);
strcode = jsonObject.getString("responseCode");
strtext = jsonObject.getString("responseText");
strname = jsonObject.getString("personName");
Log.i("TAG","parseData:"+strname);
response_code.setText("" +strcode);
response_text.setText("" +strtext);
person_name.setText("" +strname);
} catch (JSONException e) {
Log.d("TAG", "profile: " + e);
}
}`
I guess you use Volley JsonObjectRequest, so you need to convert the response to a String and parse it to a JSONObject, like this:
jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
response -> {
try {
JSONObject jsonObject = new JSONObject(response.toString());
strcode = jsonObject.getString("responseCode");
strtext = jsonObject.getString("responseText");
strname = jsonObject.getString("personName");
Log.i("TAG","parseData:"+strname);
response_code.setText("" +strcode);
response_text.setText("" +strtext);
person_name.setText("" +strname);
} catch (JSONException e) {
Log.d("TAG", "profile: " + e);
}
}, error -> {}
);
try {
JSONObject jsonObject = response.getJSONObject(response);
strcode = jsonObject.getString("responseCode");
strtext = jsonObject.getString("responseText");
strname = jsonObject.getString("personName");
Log.i("TAG","parseData:"+strname);
response_code.setText("" +strcode);
response_text.setText("" +strtext);
person_name.setText("" +strname);
} catch (JSONException e) {
Log.d("TAG", "profile: " + e);
}
before you will do parsing , you will check all value receice by API exp :- responseCode, responseText, personName ( https://jsonlint.com/ ) , if all value you recived , check its in correct format , after that you will parse the data
you also use this , its will handle the JsonException
jsonObject.optString("responseText");
Solved this problem with this code
public void onResponse(JSONObject response) {
Log.d("TAG", "Details:" + response);
responseTV.setText("String Response : " + response.toString());
try {
// JSONObject jsonObject = response.getJSONObject(response.toString());
strcode = response.getString("responseCode");
strtext = response.getString("responseText");
strname = response.getString("personName");
Log.i("TAGParser","parseData:"+strname);
response_code.setText("" +strcode);
response_text.setText("" +strtext);
person_name.setText("" +strname);
} catch (JSONException e) {
Log.d("TAG", "profile: " + e);
}
}

Get JSONObject with ID in Android

I'm trying to read my data from my localhost to Android Studio. I have used volley to do this. I'm having issue getting the values from my json. Here's my json.
{"studentList":[{"username":"2011089882","password":"","section":"c4a","year":"4th"}]}
Here's my code in Android.
JsonObjectRequest jsonObjReq = new JsonObjectRequest(urlJsonObj, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
String username = response.getString("username");
String section = response.getString("section");
String year = response.getString("year");
jsonResponse = "";
jsonResponse += "Username: " + username + "\n\n";
jsonResponse += "Section: " + section + "\n\n";
jsonResponse += "Year: " + year + "\n\n\n";
txtView.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
Appreciate your help.
JSONArray parentArray = response.getJSONArray("studentList");
if (parentArray.length() == 0) {
//no students
} else {
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
String username = finalObject.getString("username");
String password = finalObject.getString("password");
String section = finalObject.getString("section");
String year = finalObject.getString("year");
}
}
this will loop through every student in "studentList"
make sure to import JSONArrayimport org.json.JSONArray;
{"studentList":[{"username":"2011089882","password":"","section":"c4a","year":"4th"}]}
Structure of your JSON response is an Object containing a list, which contains an object of type student
which contains username & password, where as you are directly trying to get username from outer object.
String username = response.getString("username");
Firstly You need to extract Object from List then access username.
JsonArray jsonArr = response.getJSONArray("studentList");
JsonObject studentObj = jsonArr.get(0);
try {
JSONObject jsonObject = new JSONObject(response.toString());
JSONArray jsonArray = jsonObject.getJSONArray("studentList");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String username = jsonObject1.getString("username");
String section = jsonObject1.getString("section");
String year = jsonObject1.getString("year");
Toast.makeText(MainActivity.this, username + " " + section + " " + year, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Hope this helps

Add marker to map from JSON, Android

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>

How to get complex JSON from URL?

My json is like this
{
"results": [{
"syllabus": "CBSE",
"grade": "5",
"subject": "Kannada",
"topic": "Grammar Level 1",
"id": 28
}]
}
Using Volley
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
System.out.println(person.toString());
String syllabus = person.getString("syllabus");
String grade= person.getString("grade");
jsonResponse += "Name: " + syllabus + "\n\n";
jsonResponse += "Email: " + grade + "\n\n";
}
Your Json have an object and then array.. try like this
JsonObjectRequest req = new JsonObjectRequest(urlJsonArry,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
JSONOArray array = response.getJSONArray("results")
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < array.length(); i++) {
JSONObject person = (JSONObject) array
.get(i);
System.out.println(person.toString());
String syllabus = person.getString("syllabus");
String grade= person.getString("grade");
jsonResponse += "Name: " + syllabus + "\n\n";
jsonResponse += "Email: " + grade + "\n\n";
}
if (!result.equalsIgnoreCase("")) {
try {
JSONObject jsonObject = new JSONObject(result); //result is what you get responce
JSONArray jsonArray = jsonObject.optJSONArray("results");
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjects = jsonArray.optJSONObject(i);
String syllabus = jsonObjects.optString("syllabus");
Int grade = jsonObjects.optInt("grade");
String subject = jsonObjects.optString("subject");
String topic = jsonObjects.optString("topic");
Int id = jsonObjects.optInt("id");
}
} else {
Log.e("", "error parse json", "--->" + e.getMessage());
}
} catch (Exception e) {
Log.e("", "error parse json", "--->" + e.getMessage());
}
} else {
Log.e("", "error parse json", "--->" + e.getMessage());
}

Android value of arraylist out of method

I have this code created with Volley and JSON:
public List<String> result = new ArrayList<String>();
public List<String> mostraDati(){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, DatiNet.MostraDati, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response.toString());
try {
System.out.println("fin qui ci siamo");
JSONArray utenti = response.getJSONArray("utenti");
List<String> resTemp = new ArrayList<String>();
for (int i = 0; i < utenti.length(); i++) {
JSONObject student = utenti.getJSONObject(i);
String nome = student.getString("nome");
String cognome = student.getString("cognome");
String numero = student.getString("numero");
String email = student.getString("email");
resTemp.add(nome + " " + cognome + " " + email);
}
result = resTemp;
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.append(error.getMessage());
}
});
requestQueue.add(jsonObjectRequest);
System.out.println(result.toString());
return result;
}
It works well but the return is always null "[]". How to solve the problem?
I think the problem is to port the value out of the method of jsonObjectRequest.
You have to change your code to add one arrayList value to another arrayList.
Change
result = resTemp;
to
result.addAll(resTemp);

Categories

Resources