Android JSON request populating array - android

I have followed this tutorial.
The author directly uses the data in the callback by setting the textview within the callback. What I would like to do is populate an array with the response I'm getting from my request, and then be able to use that array elsewhere (as the response listener is an anonymous inner class, I can't figure out how to get data from it; any attempt to assign to an array inside the listener has proved fruitless.
Thanks, please bear with me as I'm still a beginner.
The listener:
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);
String name = person.getString("name");
String email = person.getString("email");
JSONObject phone = person
.getJSONObject("phone");
String home = phone.getString("home");
String mobile = phone.getString("mobile");
jsonResponse += "Name: " + name + "\n\n";
jsonResponse += "Email: " + email + "\n\n";
jsonResponse += "Home: " + home + "\n\n";
jsonResponse += "Mobile: " + mobile + "\n\n\n";
}
txtResponse.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();
hidepDialog();
}
});
EDIT: The code below outlines the problem I'm having. I'm aware this is probably due to misunderstanding or misapplication on my part but still.
private void makeJsonArrayRequest(String url){
//ONLY WAY TO ACCESS INSIDE LISTENER IS TO MAKE FINAL
final ArrayList<String> string = new ArrayList<>();
showpDialog();
JsonArrayRequest req = new JsonArrayRequest(
url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject field = (JSONObject) response.get(i);
string.add(i, field.getString("title"));
//THIS PRINTS OUT ALL MY TITLES CORRECTLY, SHOWING THAT
//THE STRINGS ARRAY IS POPULATED IN THIS SCOPE
Log.d(AppController.TAG, string.get(i));
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context,
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(AppController.TAG, "Error: " + error.getMessage());
Toast.makeText(context,
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
}
);
AppController.getInstance().addToRequestQueue(req);
//THIS CAUSES AN OUT OF BOUNDS EXCEPTION, AS IT THINKS THE ARRAY HAS NOT BEEN POPULATED
Log.d(AppController.TAG, string.get(3));
}

I think the problem is using variable string as a copy of actual string inside OnResponse(..).
Try adding static to this variable :
final static ArrayList<String> string = new ArrayList<>();

Related

How to implement Nested JsonObject /JsonArrey in One Json Value?

I have a Json Format
Json Url
http://inter.youdao.com/intersearch?tag=simple-eh&from=en&to=hi&q=spin
I need only first i
first i - n. घुमाव; चक्रण; झुकाव
second i. v. घूमना; कातना
Is it possible that first i + second i word only first word = n. घुमाव, v. घूमना
The problem was showing result in android no eh velue.
How to get hindi word.
Json Result
{
"data": {
"eh": {
"": "spɪn",
"ukphone": "spɪn",
"ukspeech": "spin&type=1",
"trs": [
{
"i": "n. घुमाव; चक्रण; झुकाव"
},
{
"i": "v. घूमना; कातना"
}
],
Android Implement :
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
urlJsonObj, null, new Response.Listener<JSONObject>() { #Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
// Parsing json object response
// response will be a json object
JSONObject result = response.getJSONObject("data");
String eh= result.getString("eh");
JSONObject result1 = response.getJSONObject("eh");
String hindi= result1.getString("trs");
jsonResponse = "";
jsonResponse += "Hindi: " + hindi ;
txtResponse.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();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
finally fix the Problem
Thanks
here is code :
try {
// Parsing json object response
// response will be a json object
String syncresponse = response.getString("data");
JSONObject object2 = new JSONObject(syncresponse);
String synckey = object2.getString("eh");
JSONObject object3 = new JSONObject(synckey);
JSONArray jArray1 = object3.getJSONArray("trs");
for(int i = 0; i < jArray1 .length(); i++)
{
JSONObject object4 = jArray1.getJSONObject(i);
String comp_id = object4.getString("i");
String replace = object4.getString( "i" ).replace( ";", "," );
translate.setText(mWord + "=" + comp_id);
}

How can I get a JSON value from Volley response?

The response format is {"status":"201","message":"OTP is created and sent."}, I need to get the status & message values, but String name = response.getString("name"); is showing red line error.
Here is my code:
public void sendData() {
final JSONObject json = new JSONObject();
final TextView serverResp = findViewById(R.id.connectionStatus);
try {
json.put("mobile", "12312312");
} catch (JSONException e) {
e.printStackTrace();
}
String url = getResources().getString(R.string.url_login);
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, json,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(REQ_TAG, response.toString());
String name = response.getString("name");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
serverResp.setText("Error getting response\n" + error.toString());
Log.d(REQ_TAG, "Error: " + error.toString()
+ "\nStatus Code " + error.networkResponse.statusCode
+ "\nResponse Data " + error.networkResponse.data
+ "\nCause " + error.getCause()
+ "\nmessage" + error.getMessage());
}
});
jsonObjectRequest.setTag(REQ_TAG);
requestQueue.add(jsonObjectRequest);
// do i need the following line?
//RequestQueueSingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
}
Becuase there is no key name in JSON response
try this
String status= response.getString("status");
String message= response.getString("message");

i want to connect my android app to a web service using JSON

i want to connect my android app to a web service when i press the button nothing happens ,the web service is working and its return JSON... and her is my cod .
public class MainActivity extends AppCompatActivity {
RequestQueue requestQueue ;
TextView textView;
Button start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textView3);
requestQueue = Volley.newRequestQueue(this);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://192.168.5.160:8080/H2O.asmx/Menu_Get_Categories",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("Categories");
for (int i = 0 ; i < jsonArray.length() ; i++){
JSONObject Categories = jsonArray.getJSONObject(i);
String Cat_AR_Name = Categories.getString("Cat_AR_Name");
String Cat_EN_Name = Categories.getString("Cat_EN_Name");
String CatID = Categories.getString("CatID");
textView.append(Cat_AR_Name+" "+Cat_EN_Name+" "+CatID+" \n ");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY","ERROR");
}
}
);
requestQueue.add(jsonObjectRequest);
}
});
}
}
I always use this example to parse JSON data using Volley, but I can't tell you if this gonna help you.
Let's say that we have the Json data below:
[
{
"name" : "Alex Watson",
"email" : "alex.watson#company.com",
"phone" : {
"home" : "0912345678",
"mobile" : "0612345678"
}
},
{
"name" : "John Deep",
"email" : "john.deep#company.com",
"phone" : {
"home" : "0912345678",
"mobile" : "0612345678"
}
}
]
The following code does the job :
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);
String name = person.getString("name");
String email = person.getString("email");
JSONObject phone = person
.getJSONObject("phone");
String home = phone.getString("home");
String mobile = phone.getString("mobile");
jsonResponse += "Name: " + name + "\n\n";
jsonResponse += "Email: " + email + "\n\n";
jsonResponse += "Home: " + home + "\n\n";
jsonResponse += "Mobile: " + mobile + "\n\n\n";
}
txtResponse.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();
hidepDialog();
}
});
// Adding request to request queue, please substitute here with your own queue
VolleyQueue.add(req);
You can follow this tutorial.

I am trying to get the value using JSON in android, Below is my code, It shows null pointer exception and error during request queue

/**
* Method to make json array request where response starts with [
* Requesting data from url
* */
private String urlJsonArry_local = "http://www.endorecord.in/endorecord/hospitaladmin/Api/device_hospitals.php?deviceid=";
private void makeJsonArrayRequest() {
showpDialog();
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry_local +androidID,
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);
String name = person.getString("hospitalid");
String email = person.getString("hospital_name");
/*JSONObject phone = person
.getJSONObject("phone");
String home = phone.getString("home");
String mobile = phone.getString("mobile");
*/
jsonResponse += "Name: " + name + "\n\n";
jsonResponse += "Email: " + email + "\n\n";
//jsonResponse += "Home: " + home + "\n\n";
//jsonResponse += "Mobile: " + mobile + "\n\n\n";
}
Toast.makeText(getApplicationContext(), jsonResponse, Toast.LENGTH_LONG).show();
//txtResponse.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();
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
you should be passing your url in the request "http://www.google.com"+androidID not this. And the Url urlJsonArry_local that you have mentioned above returns json object response not jsonArray, Your code and Json reponse are completely irrelavant
for the Json respone in above url
private String urlJsonArry_local = "http://www.endorecord.in/endorecord/hospitaladmin/Api/device_hospitals.php?deviceid=";
RequestQueue queue = MyVolley.getRequestQueue();
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,urlJsonArry_local,null/* paramateres passed here*/,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject jObject = response;
String status = jObject.getString("status");
JSONArray hospitalArray = jObject.getJSONArray("hospital");
//your for loop to parse hospital array here
hideProgressDialog();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideProgressDialog();
}
});
queue.add(jsObjRequest);

volley library displaying the data not stored in the json data

I am having problem with volley library. I dont understand where i am getting all the values from in the application even the internet is not accessible and the data is not available in the api itself. I tried to clear the cache but nothing is working. Any suggestion would be appreciated. Thanks
private void makeJsonObjReq() {
//Log.e("makeJsonobjReq method", "inside");
pinfo = new PostsInfo();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
Const.URL_JSON_ARRAY, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray jArray;
Log.e(TAG +"", " rrr "+ response.toString());
try {
Log.e(TAG, "" + response.getInt("count") + " " + response.getInt("pages") + " " + response.getInt("page"));
for (int i = response.getInt("page"); i <= response.getInt("pages"); i++) {
jArray = response.getJSONArray("results");
for (int j = 0; j < response.getInt("count"); j++) {
try {
a_fetch_data.open();
JSONObject json = jArray.getJSONObject(i);
Log.e(TAG +" no of count in array", "i = "+ json.getString("id"));
//jsonObjectValue(json);
}
catch (JSONException e) {
e.printStackTrace();
}
}
Log.e(TAG, "Array "+ " Completed ");
}
}
catch (JSONException e1) {
e1.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
/*Adding request to request queue*/
ApplicationController.getInstance().addToRequestQueue(jsonObjReq,
"jobj_req");
ApplicationController.getInstance().getRequestQueue().getCache().remove("jobj_req");
}
api :http://bumpintomums.com.au/wp-content/themes/bumpii/API/get_data.php
The problem is, this method returns a response even though i am not connected to internet and i have not instantiated any cache work here.

Categories

Resources