How to access volley response {"data":"success"} like this.
i am already try this
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getJSONArray("data");
} catch (JSONException e) {
e.printStackTrace();
}
You're trying to access a JSONArray from a JSONObject while it's just a string. So just replace getJSONArray with getString and try this
String data = new JSONObject(response).getString("data");
Or in your code
try {
JSONObject j = new JSONObject(response);
result = j.getString("data");
}
catch (JSONException e) {
e.printStackTrace();
}
Access Like This
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getString("data");
} catch (JSONException e) {
e.printStackTrace();
}
You can check this, before retrieving check if that tag (i.e. "data" for your case) is exists on that json object.
JSONObject j = null;
try {
j = new JSONObject(response);
if(j.has("data") {
result = j.getString("data");
}
} catch (JSONException e) {
e.printStackTrace();
}
As the value of data is string and to get string value you have to use JSONObject.getString("data")
Use:
result = j.getString("data");
Instead of:
result = j.getJSONArray("data");
Related
I have such a JSON: https://paste.ubuntu.com/p/HkTK9xTzNx/
How do I get a "imdb_id" String (line 14). There is no array which contains that value,it's not in square branches,so I don't know how to get it.
Solution as per your need:
try {
imdbLink = response.getString("imdb_id");
} catch (JSONException e) {
e.printStackTrace();
}
A standard solution:
String json = "{\"imdb_id\":\"str12345\"}"; // your json response from network call/local file
JSONObject jsonObject;
try {
jsonObject = new JSONObject(json);
String id = jsonObject.getString("imdb_id");
} catch (Exception e) {
e.printStackTrace();
}
I am new to Stackoverflow and this is my first question.
I am developing an application where I am reading data from a json file from assets folder and storing the values in array list.
here is my code
try {
JSONObject object=new JSONObject(loadJSONFromAsset());
String objec=object.getString("root");
JSONObject object1=new JSONObject(objec);
JSONArray array=object1.getJSONArray("child");
for (int i=0;i<array.length();i++)
{
JSONObject jsonObject=array.getJSONObject(i);
list.add(String.valueOf(jsonObject));
}
} catch (JSONException e) {
e.printStackTrace();
}
// Inflate the layout for this fragment
return rootview;
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getActivity().getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
And this is my json data structure
"root" : {
"child" : [ "data1","data2","data3",.......]},
I want the data1,data2 values inside a list
Try this
try {
JSONObject object=new JSONObject(loadJSONFromAsset());
String objec=object.getString("root");
JSONObject object1=new JSONObject(objec);
JSONArray array=object1.getJSONArray("child");
for (int i=0;i<array.length();i++)
{
list.add(array.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
JSONObject object=new JSONObject(loadJSONFromAsset());
String objec=object.getString("root");
JSONObject object1=new JSONObject(objec);
JSONArray array=object1.getJSONArray("child");
for (int i=0;i<array.length();i++)
{
JSONObject jsonObject=array.getJSONObject(i);
list.add(jsonObject.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
Here is the code i had tried with multiple times to get multiple rows values in a single text view with json.
protected Void doInBackground(Void... arg0)
{
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://192.168.1.5/send-data.php");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jArray = new JSONArray(str);
for( int i=0; i <jArray.length(); i++) {
json = jArray.getJSONObject(i);
}
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
try {
textview.setText(json.getString("survey_textresponse"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Hiding progress bar after done loading TextView.
progressbar.setVisibility(View.GONE);
}
}
}
when i run php file in chrome directly it shows all values from database while in android app it shows only the first row value.
Because you are only storing the last value of JSONobject in json reference
// assume JArray length = 5
for( int i=0; i <jArray.length(); i++) {
json = jArray.getJSONObject(i);
// only have last object value , in last iteration jArray.getJSONObject(4)
}
There can be many solutions to this
Collect data as list of Values
Collect in a String or StringBuilder Object
StringBuilder sb = new StringBuilder();
// or List<String> list = new ArrayList<>();
for( int i=0; i <jArray.length(); i++) {
json = jArray.getJSONObject(i);
sb.append(json.optString("survey_textresponse")+"\n");
// or list.add(json.optString("survey_textresponse"));
}
and later
textview.setText(sb.toString());
// or can collect list as string using loop and display it
The loop that you've written for retrieving the values from the JSONArray is not proper. Its only storing the last object while iterating through the loop. You could store the retrieved values in a collection of string.
Here's an example code you could follow:
private class RetrieveTask extends AsyncTask<Void,Void,Void>{
List<String> jsonResults;
String str;
JSONObject json;
#Override
protected void onPreExecute() {
super.onPreExecute();
jsonResults=new ArrayList<>();
}
#Override
protected void onPostExecute(Void aVoid) {
for(String data:jsonResults)
textview.append(data);
}
#Override
protected Void doInBackground(Void... voids) {
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://192.168.1.5/send-data.php");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jArray = new JSONArray(str);
for( int i=0; i <jArray.length(); i++) {
json = jArray.getJSONObject(i);
if(json.optString("survey_textresponse")!=null){
jsonResults.add(json.getString("survey_textresponse"));
}
}
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Your json variable contains only last element of JsonArray when it is finished. You can display on TextView while retrieving your values from JsonArray.
for( int i=0; i <jArray.length(); i++) {
json = jArray.getJSONObject(i);
textview.setText(textview.getText() + json.getString("survey_textresponse") + "\n");
}
I kept some JSON data in a txt file inside assests folder. Then i am reading the txt file and kept the result in a string. Now i am trying to convert the string to JSONObject and get some data from each key. Below is the code.
========method for reading from a file:
private String readMyJsonFile()
{
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("myFile.txt"), "UTF-8"));
mLine = reader.readLine();
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
return mLine;
}
======= And inside onCreate():
String JsonStr = readMyJsonFile();
try {
JSONObject jsonObj = new JSONObject(JsonStr);
JSONObject questionMark = JsonObj.getJSONObject("structure_details");
Iterator keys = questionMark.keys();
while(keys.hasNext())
{
String currentDynamicKey = (String)keys.next();
JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey);
}
}
catch (JSONException e) {e.printStackTrace(); }
================================================
and the JSON data is:
{"structure_details":{"x1":{"id":"54","name":"sh"},
"x2":{"id":"69","name":"dd"},
"x3":{"id":"80","name":"kk"}
}
}
==========================================================
I am getting result but the problem is that i am not getting the JSONObject serially in JSONObject jsonObj = new JSONObject(JsonStr); . The sequence is not the same as the JsonStr.
How to solve it?
Take the iterator keys in a ArrayList of string. Then loop through each arraylist object and get the JsonObjects. Following is the code that might help:
String JsonStr = readMyJsonFile(); //readMyJsonFile() is the same method you created
ArrayList<String> sortedKey = new ArrayList<String>();
try {
JSONObject jsonObj = new JSONObject(JsonStr);
JSONObject questionMark = jsonObj.getJSONObject("structure_details");
Iterator keys = questionMark.keys();
while(keys.hasNext()) {
String currentDynamicKey = (String)keys.next();
sortedKey.add(currentDynamicKey);
}
Collections.sort(sortedKey);
for(String str:sortedKey )
{ JSONObject currentDynamicValue = questionMark.getJSONObject(str);
}
}
catch (Exception e) {
e.printStackTrace();
}
It is not JSON:
"structure_details":{"x1":{"id":"54","name":"sh"},
"x2":{"id":"69","name":"dd"},
"x3":{"id":"80","name":"kk"}
}
It is JSON:
{"structure_details":{"x1":{"id":"54","name":"sh"},
"x2":{"id":"69","name":"dd"},
"x3":{"id":"80","name":"kk"}
}}
and it JSON:
{"x1":{"id":"54","name":"sh"},
"x2":{"id":"69","name":"dd"},
"x3":{"id":"80","name":"kk"}
}
I want to send 15 images to a server and I use json objects to convert these images in a String, but when i want to send it, is some devices there are Out of memory exception because there is a big string.
My images has 320x400 more and less and i do this:
First I create a jsonarray with one object to each image:
for (int i = 0; i < images.size(); i++) {
Mat aux = images.get(i);
int cols = aux.cols();
int rows = aux.rows();
int elemSize = (int) aux.elemSize();
byte[] data = new byte[cols * rows * elemSize];
aux.get(0, 0, data);
String dataString = new String(Base64.encode(data, Base64.DEFAULT));
JSONObject obj = new JSONObject();
try {
obj.put("ROWS", aux.rows());
obj.put("COLS", aux.cols());
obj.put("TYPE", aux.type());
obj.put("DATA", dataString);
} catch (JSONException e) {
e.printStackTrace();
}
arrayjson.put(obj);
}
And the i create a json object with contains this array and another params:
final JSONObject jsontoSend = new JSONObject();
try {
jsontoSend.put("USERNAME", user.username);
jsontoSend.put("DATE", getCurrentDateandTime());
jsontoSend.put("IMAGES", arrayjson);
jsontoSend.put("TOTALIMAGES", images.size());
} catch (JSONException e) {
e.printStackTrace();
}
Finally, i try to send this object:
StringEntity send = null;
try {
send = new StringEntity(jsontoSend.toString());
httpPost.setEntity(send);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (OutOfMemoryError e) {
e.printStackTrace();
return -2;
}
How can i do to send this big string??
Thanks
SOLUTION:
I solved this adding in my Manifest file android:largeHeap="true"with this, android increase my app memory and runs fine