I think it's very odd that the TextViews are not showing me any data that it has retrieved from the mySQL database. Here is my code:
This is the key parsing bit, I have two columns that need parsing and putting into separate TextView, something that I think I have done:
//PARSING JSON DATA
try {
jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_name", "Driver_full_name:" + json_data.getString("Driver_full_name"));
Log.i("log_for", "Drives for:" + json_data.getString("Drives_for"));
returnString += "\n\t" + jArray.getJSONObject(i);
somethingelse += "\n\t" + jArray.getJSONObject(i);
}
} catch (JSONException e1) {
Log.d("DB", "Error somewhere");
CurrentSeasonDrivers_DriverName.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(CurrentSeasonDrivers_DriversName, "Could not parse data so shut up",
Toast.LENGTH_LONG).show();
}
});
}
return returnString += somethingelse;
}
protected void onPostExecute(String returnString, String somethingelse) {
TextView drivername = (TextView) findViewById(R.id.DriverName);
drivername.setText(drivername.getText() + "\n" + returnString);
TextView drivesfor = (TextView) findViewById(R.id.DrivesFor);
drivesfor.setText(drivesfor.getText() + "\n" + somethingelse);
}
}
}
Hoping someone can help. Considering there are no errors. The logs in the parsing bit show the data fully parsed, however the logs in the onPostExecute show it unparsed again, or at least with curly brackets and speech marks around each row.
Thanks for any help. Really appreciate it.
Looks like you're parsing the JSON using the getString method for your logs, but stuffing the entire JSON in the Strings that you use to set the text. Unless there's something in between these steps that's not here, I think what you need to do is use the getString method when appending to returnString and somethingElse.
Is your onPostExecute method even called? The signature is wrong, it cannot take two parameters.
You should pass a String array instead (and of course change your AsyncTask class declaration to use a String array in onPostExecute) :
...
return new String[] {returnString, somethingelse};
}
protected void onPostExecute(String[] strings) {
String returnString = strings[0];
String somethingelse = strings[1];
}
Related
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 6 years ago.
I have a Json script which get data from a Mysql database and print it in different TextViews. The thing I want to know is how can I take for example only the "idE" value and print it in the "TextViewTitulo" TextView
try {
String response = "[{"0":"1","id":"1","1":"f3n","idE":"f3n","2":"bar","tipo":"bar"},{"0":"1","id":"1","1":"f3n","idE":"f3n","2":"bar2","tipo":"bar2"}]"
JSONArray array;
array = new JSONArray(response);
StringBuilder sb = new StringBuilder();
for (i=0; i<array.length(); i++) {
// chain each string, separated with a new line
sb.append(array.getString(i) + "\n");
}
// display the content on textview
textViewTitulo.setText(sb.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
My code works fine, but is displays the whole string of values
You have 2 objects in your JSONArray, and 1 textview to show the data in, so I'm adding append " " to separate them.
for (i=0; i<array.length(); i++) {
sb.append(array.getJSONObject(i).getString("idE"));
sb.append(" ");
//do whatever with it
}
textViewTitulo.setText(sb.toString());
Of course you can get it, you just have to iterate through the whole JSONArray. If you know the value you are looking for, you have to search for it, if you know the index - it is easier, you just have to get it. So for the first case, you could do something like:
for (int i = 0; i < array.length(); i++) {
JSONObject current = array.getJSONObject(i);
// In your case the JSONObject is more complicated
// so you need to iterate over it too
Iterator<?> keys = current.keys();
while(keys.hasNext()) {
String key = (String)keys.next();
String value = current.get(key);
// Do something with the value
}
// Or If you know what key you are looking for, you may do
String value = current.get("idE");
// Do something with value
}
I have JSON Response like this.I have tried a lot but unable to parse the Values.
This one is my Actual Response...
{"ResponseCode":"000","ResponseDescription":"Successful","SystemServiceID":["0000"],"SystemServiceName":["Test"],"ProductID":["000"],"ProductName":["Test"],"ProductDescription":["Test product"],"MinimumValue":[10000],"MaximumValue":[500000],"ImageURL":[null],"Country":["AAAA"],"CompanyID":["1"],"CompanyName":["Test"],"FieldLevel":["2"],"FieldInfo":["{\"Field1\":{\"Field Name\":\"Phone Number\",\"Field Type\":\"Number\",\"Validation\":{\"Min\":\"4\",\"Max\":\"8\"}},\"Field2\":{\"Field Name\":\"Email\",\"Field Type\":\"String\",\"Validation\":{\"Regular Expression\":\"abcd\",\"Min Length\":\"10\",\"Max Length\":\"20\"}}}"]}
Out of this i am able to parse all the field expect the below one...
{
"Field1":
{
"Field Name":"Phone Number",
"Field Type":"Number",
"Validation":{"Min":"4","Max":"8"}
},
"Field2":
{
"Field Name":"Email",
"Field Type":"String",
"Validation":{"Regular Expression":"abcd","Min Length":"10","Max Length":"20"}
}
}
I also want to fetch the value of Validation":{"Min":"4","Max":"8"} this field.Like it has max value 4 and min value is 8.
Any Help will be appreciated.
Thanks in Advance ... :)
Here is the code to read Min And Max values
JSONObject parentObject = new JSONObject(Json_String);
JSONObject field1 = parentObject.getJSONObject("Field1");
JSONObject validation = field1.getJSONObject("Validation");
String min = validation.getString("Min");
String max = validation.getString("Max");
Assuming your JSON string is well formed.
Since in your response you are not getting the "\" into JSON so you need to some modifications into that like (update : It seems that replacement not required here)
String json = "{\"Field1\":{\"Field Name\":\"Phone Number\",\"Field Type\":\"Number\",\"Validation\":{\"Min\":\"4\",\"Max\":\"8\"}},\"Field2\":{\"Field Name\":\"Email\",\"Field Type\":\"String\",\"Validation\":{\"Regular Expression\":\"abcd\",\"Min Length\":\"10\",\"Max Length\":\"20\"}}}";
// json.replace("\\", ""); // I verified that parsing works well without replacement too
try {
JSONObject parentObject = new JSONObject(json);
JSONObject field1 = parentObject.getJSONObject("Field1");
JSONObject validation = field1.getJSONObject("Validation");
String min = validation.getString("Min");
String max = validation.getString("Max");
System.out.println("Min ::::::: " + min);
System.out.println("MAx ::::::: " + max);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am trying to parse the response i get from the network database. I am getting only one value i.e. seller id in response. When i try to pass it in JSON Object, somehow the toast after it doesn't execute and the toast after it is not executed.
I know there are many related questions but i can't find whats wrong... please help. Thanks.
try {
JSONArray jArray = new JSONArray(stuff.toString());
Toast.makeText(this, "len: " + jArray.length(), 1000).show(); // length is 1
for (int i = 0; i < jArray.length(); i++) {
Toast.makeText(this, "Arr: " + stuff, 1000).show();
// Arr: [{"seller_id":"5"}]
JSONObject jObject = jArray.getJSONObject(i);
j_id = jObject.getString(stuff);
// not getting executed
Toast.makeText(this, "JSON: " + j_id, 1000).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(this, "View: " + j_id, 1000).show(); // j_id is giving null value
This is my json data [{"seller_id":"5"}] i am trying to get the value of seller id (ie 5 here) out of it.
There is a problem in jObject.getString() method args
JSONObject jObject = jArray.getJSONObject(i);
j_id = jObject.getString(stuff);
Your giving the array. It should the name of the object i.e seller_id
so after the modification your code would be j_id = jObject.getString("seller_id");
After the following code:
j_id = jObject.getString(stuff);
add textview.settext(j_id);
and change this textview with your textview name
and if its not working than show your complete json data.
I have this below Json which I'm getting from a .Net Web service:
[["Developer","test","developer#test.com"]]
I checked with jsonlint validator and It shows above json fine.
Because it is not having any key I don't know how to parse it in Android.
Can someone please help me how to parse this json without key.
If it had keys, I would have tried this:
{"first":"somevalue","last":"someothervalue"} // Json response
JSONObject json_obj = new JSONObject(resp); //response is the json array
String first = json_obj.getString("first");
String last = json_obj.getString("last");
String test = "Hello! " + first + " " + last;
Hope someone helps :)
Regards,
Praveen
MY SOLUTION
JSONArray respo = new JSONArray(resp); //resp is Json Array
respo = respo.getJSONArray(0);
String test = respo.getString(2);
test = "Your Email Address is " + test;
in Android (Java) parsing this line looks like:
String jsonString="[[\"Developer\",\"test\",\"developer#test.com\"]]";
try {
JSONArray jsonArray=new JSONArray(jsonString);
JSONArray jsonArray2=jsonArray.getJSONArray(0);
for (int i = 0; i < jsonArray2.length(); i++) {
String valueString=jsonArray2.getString(i);
Log.e("json", i+"="+valueString);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Use JSONArray instead of JSONObject. Then use the getJSONArray() function to get the array inside the array. After that you can access all values with their index and getString().
As the title says really. I have two columns. I want to put them into textviews so I did it. However only the bottom two results, one from each column gets shown. Very odd. Here is my code: http://pastebin.com/qNgfHfT3
The parsing/onPostExecute is towards the bottom where the issue is.
One thing to note: The logs labeled "work" & "dontwork" show all my results, however the logs in the onPostExecute (Google & Google1) only show the last result so I presume the error is in the transfer from parsing to displaying.
Would really appreciate any help here. Thanks.
If you are receiving a JSON response I'd suggest you to parse it by using Gson. It's strongly recommendable as long as you can parse the whole thing in a pair of lines.
Note that creating a proper object it is as easy as doing the following:
YourObject object = gson.fromJson(responseReader, YourObject.class);
or even if you are retrieving a list of items:
Type listType = new TypeToken<List<YourObject>>() {}.getType();
List<YourObject> objects = gson.fromJson(responseReader, listType);
Here's an example that fits exactly your needs
After the process is done you'll have your object (or list of objects) available in an accesible variable.
EDIT:
First your Asynctask should have the following params:
public class HttpTask extends AsyncTask<Void, Void, ArrayList<Driver>> {
and your doInBackground method will need to pass that array to your onPostExecute:
#Override
protected ArrayList<Driver> doInBackground(Void... params) {
For the rest, I take it when the JSon parsing starts.
//PARSING JSON DATA
try {
JSONObject json_data;
Driver d;
jArray = new JSONArray(result);
int l = jArray.length();
if(l>0){
ArrayList<Driver> drivers = newArrayListList<Driver>();
for (int i = 0; i < l; i++) {
json_data = jArray.getJSONObject(i);
d = new Driver(json_data.optString("Driver_full_name"), json_data.optString("Drives_for"));
drivers.add(d);
Log.i("work", returnString);
Log.i("dontwork", somethingelse);
}
} catch (JSONException e1) {
Log.d("DB", "Error somewhere");
CurrentSeasonDrivers_DriverName.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(CurrentSeasonDrivers_DriversName, "Could not parse data so shut up", Toast.LENGTH_LONG).show();
}
});
}
return drivers;
}
protected void onPostExecute(ArrayList<Drivers>... drivers) {
Log.i("Google", returnString);
Log.i("Google1", somethingelse);
String firstDriverName = drivers.get(0).name;
String firstDriverDrivesFor = drivers.get(0).drivesfor;
String secondDriverName = drivers.get(1).name;
TextView drivername = (TextView) findViewById(R.id.DriverName);
drivername.setText(firstDriverName);
TextView drivesfor = (TextView) findViewById(R.id.DrivesFor);
drivesfor.setText(firstDriverDrivesFor);
}
With this and an object for your driver will complete the circle.
public class Driver{
public String name;
public String drivesfor;
public Driver(String _name, String _drivesfor){
name = _name;
drivesfor = _drivesfor;
}
}
I guess you can take over from here.
Let me know about your progress.