android JSONArray length - android

i have an array from a json feed i know that in the jArray there is one league but i need to work out the count of that array incase a second is added to the feed at a later date. at the moment log cat isn't logging out "teamFeedStructure" does anyone know what I'm doing wrong or know how to correctly turn the length of an array into a string that i can use in an intent?
heres the code
JSONObject obj = new JSONObject(json);
JSONObject objData = obj.getJSONObject("data");
JSONArray jArray = objData.getJSONArray("structure");
//String leagues = jArray.toString();
//Log.v("myapp", "structure" + leagues);
for (int i=0; i < jArray.length(); i++) {
JSONObject oneObject = jArray.getJSONObject(i);
leaguecountArray = oneObject.getJSONArray("league_id");
for (int l=0; l < leaguecountArray.length(); l++) {
if (leaguecountArray.length() == 1) {
teamFeedStructure = "One";
}
if (leaguecountArray.length() == 2) {
teamFeedStructure = "Two";
}
Log.v("myapp", teamFeedStructure);
}
}

Why do you need to iterate here:
for (int l=0; l < leaguecountArray.length(); l++)
{
if (leaguecountArray.length() == 1){
teamFeedStructure = "One";
}
if (leaguecountArray.length() == 2){
teamFeedStructure = "Two";
}
Log.v("myapp", teamFeedStructure);
}
Nevermind how many passes you do the result will still be the same.
Also you can use not English words, but String holding the number you need. Do like that:
teamFeedStructure = String.valueOf(leaguecountArray.length());
Then the value will become "2" for example. In your other activity you can parse it again to integer like that: int number = Integer.parseInt(teamFeedStructure);

Add the following line
teamFeedStructure = "greater two";
before
if (leaguecountArray.length() == 1){
If you get greater two message, means your array length more than two.

Thanks for your help everyone i discovered that i had gone a step too far into the feed which is why i was not getting anything in Logcat. now it's counting fine.

Related

Combining nested json for loop

I have two forloop in which the data is added to different ArrayList. Now my question is how do we combine these two arraylist?
Below is the code which i tried, but not working. Please give me solution for the same. TIA
try {
JSONObject object = new JSONObject(response);
status = object.getString("status");
if (status.equals("200")) {
rest.dismissProgressdialog();
JSONArray jsonArray = object.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
New_Service_Model_1 new_service_model = new New_Service_Model_1();
new_service_model.setMain_name(jsonObject.getString("main_name"));
new_service_model.setSmid(jsonObject.optInt("smid"));
JSONArray jsonArray1 = jsonObject.getJSONArray("sub_service");
//sub_services_list.clear();
sub_services_list = new ArrayList<>();
for (int j = 0; j < jsonArray1.length(); j++) {
JSONObject jsonObject1 = jsonArray1.getJSONObject(j);
New_Sub_Service_Model_1 sub_service_model = new New_Sub_Service_Model_1();
sub_service_model.setSmid(jsonObject1.optString("smid"));
sub_service_model.setSbid(jsonObject1.optInt("sbid"));
sub_service_model.setSub_name(jsonObject1.optString("sub_name"));
sub_service_model.setDesc(jsonObject1.optInt("desc"));
sub_service_model.setSt_cust(jsonObject1.optInt("st_cust"));
sub_service_model.setSt_pro(jsonObject1.optInt("st_pro"));
sub_service_model.setExist_cust(jsonObject1.optInt("exist_cust"));
sub_service_model.setExist_prov(jsonObject1.optInt("exist_prov"));
sub_services_list.add(sub_service_model);
}
new_service_model.setSub_service_list(sub_services_list);
services_list.add(new_service_model);
service_list_adapter = new Service_List_Adapter_1(this, services_list, service_costMain_interface);
rclyrview_services.setAdapter(service_list_adapter);
service_list_adapter.notifyDataSetChanged();
}
} else {
rest.dismissProgressdialog();
Toast.makeText(Service_Manage.this, "No Data found", Toast.LENGTH_SHORT).show();
}
Instead of parsing the json response manually.
Paste you json here http://www.jsonschema2pojo.org/ and use GSON or Jackson whichever is convenient for parsing the response.
There are many tutorials available which can give you a quick overview of how things can be done. Worth a try if your app has many places where you want to have Json parsing.

How to get the first value of a JSONArray?

My JSON code is as follows:
returnString = "";
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
JSONObject c = json_data.getJSONObject("data");
Log.i("log_tag","statues: "+c.getString("statues"));
returnString = c.getString("statues"); }
Now I want to see the values within my JSONArray. The value for statues is either 0 or 1. Further, I will use them in an if else phrase.
What I mean is something like this:
if(value of statues = 0){
do something}
else{
do something else}
How would I do that?
If you want only first status value in the JSONArray
to get the first value from JSONArray simply do outside of the loop and before the if statement:
JSONObject FirstArray = jArray.getJSONObject(0); // first Array in JSONArray
JSONObject data = FirstData.getString("data");
String FirstStatusValue = data.getString("Status");
then parse FirstStatusValue to int and use it in if.
I hope I understood your question well, if I didnt please correct me
if you want all status value within the JSONArray
before the for loop declare an array of string to and add all the status value in it then loop:
String[] StatusArray = new String[jArray.length()]; // will make the status array has the same length as the JSONArray
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
JSONObject c = json_data.getJSONObject("data");
Log.i("log_tag","statues: "+c.getString("statues"));
StatusArray[i] = c.getString("status");
}
then for if statement add for loop then check the statement like:
for (int i = 0; i < StatusArray.length(); i++)
{
if (StatusArray[i] == 0)
// do something
else
// do something
}

Comparing two strings in android [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Comparing two identical strings with == returns false
I am having real hard time with solving this code. This might look silly but I am not able to figure out what is happening. I am parsing a JSONArray(No big deal!) I am traversing the array with a for loop. I want to break the loop when the user input and the value matches. Here is my code
String regi = null;
JSONObject studentObject = null;
try {
JSONArray returned = test.getInternetData();
int i;
for (i = 0; i < returned.length(); i++) {
studentObject = returned.getJSONObject(i);
regi = studentObject.getString("REGISTRATION_NO");
if (regi == reg) {
name = studentObject.getString("STUDENT_NAME");
break;
}
}
course = studentObject.getString("COURSE_CODE");
Log.d("Details", name + course + regi + i);//Out put: nullGraduate081018394:name - null
//course: Graduate (same for all), regi: last registration number,
//i: giving totalnumber of objects
As per my knowledge the loop should stop when it finds a match. The COURSE_CODE will be corresponding to the student. Am I missing something?
Please note: The function getInternetData() is returning the whole JSON Array. The loop is completely traversing every object.
Strings cannot be compared with == in Java. You have to use string1.equals(string2).
Use regi.equals(reg) or regi.contentEquals(reg) instead of == and you will be fine :-)
use regi.contentEquals(reg) or !regi.contentEquals(reg) for comparison
you should use regi.contentEquals(reg)
try using this
JSONArray returned = test.getInternetData();
int i;
for (i = 0; i < returned.length(); i++) {
// added the below line
studentObject = new JsonObject();
studentObject = returned.getJSONObject(i);
regi = studentObject.getString("REGISTRATION_NO");
if (regi.equals(reg)) {
name = studentObject.getString("STUDENT_NAME");
break;
}
}
instead of just
JSONArray returned = test.getInternetData();
int i;
for (i = 0; i < returned.length(); i++) {
studentObject = returned.getJSONObject(i);
regi = studentObject.getString("REGISTRATION_NO");
if (regi == reg) {
name = studentObject.getString("STUDENT_NAME");
break;
}
}

complex Json Parsing in Android

In my app, i want to parse json response which is in the format
{"quote":[{"orderId":"3209926"},{"totalpages":1}]}
below is the code which i had done,But the problem is how to get the "totalpages" value?
try {
JSONObject jObject = new JSONObject(result);
JSONArray jArray = jObject.getJSONArray("quote");
for (int i = 0; i < jArray.length(); i++)
{
JSONObject offerObject = jArray.getJSONObject(i);
current.orderId = offerObject.getInt("orderId");
It shows error when i use
current.totalpage= offerObject.getInt("totalpages");
Anybody knows how to parse this?THanks in advance
Note that getInt(), like other get-functions of JSONObject throw JSONException if the object does not contain the key requested. Thus, before you request the key you should use hasKey() to determine whether the object contains the key.
For example, inside the for loop you can do the following:
JSONObject offerObject = jArray.getJSONObject(i);
if(offerObject.has("orderId") {
current.orderId = offerObject.getInt("orderId");
}
if(offerObject.has("totalpages") {
current.totalpage= offerObject.getInt("totalpages");
}
You can also add a flag and a check after the loop to ensure that both orderId and totalpages were present in the JSON data.
I dont know why your json is having that structure. But if you want to parse it then you will have to do something like the following with the has function.
for (int i = 0; i < jArray.length(); i++) {
JSONObject offerObject = jArray.getJSONObject(i);
if(offerObject.has("orderId")) {
current.orderId = offerObject.getInt("orderId");
} else if(offerObject.has("totalpages")) {
current.totalpage= offerObject.getInt("totalpages");
}
}

Android: Decoding JSON

[{"placeID":"p0001","placeName":"INTI International University","placeType":"Education","placeLat":"2.813997","placeLng":"101.758229","placePict":""},{"placeID":"p0002","placeName":"Nilai International College","placeType":"Education","placeLat":"2.814179","placeLng":"101.7700107","placePict":""}]
How do I decode the JSON sent from my PHP script on Android?
please try this
String s = "[{\"placeID\":\"p0001\",\"placeName\":\"INTI International University\",\"placeType\":\"Education\","
+ "\"placeLat\":\"2.813997\",\"placeLng\":\"101.758229\",\"placePict\":\"\"},"
+ "{\"placeID\":\"p0002\",\"placeName\":\"Nilai International College\",\"placeType\":\"Education\",\"placeLat\":\"2.814179\",\"placeLng\":\"101.7700107\",\"placePict\":\"\"}]";
ArrayList<String> arrplaceID = new ArrayList<String>();
ArrayList<String> arrplaceName = new ArrayList<String>();
try {
JSONArray arr = new JSONArray(s);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonObject = arr.getJSONObject(i);
arrplaceID.add(jsonObject.optString("placeID"));
arrplaceName.add(jsonObject.optString("placeName"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < arrplaceID.size(); i++) {
Log.e("arr[" + i + "] place Name", arrplaceName.get(i));
}
What is the problem in this Please Read this tutorial for parsing JSON it might be helpful in future also.json parsing link
Follow below points.
1) it seems the response you are getting is Json Array. so create one json array by response string.
JSonArray jArray = new JsonArray(responseString);
2) now you have your response in jArray. now iterate a loop and take json object from JsonArray, in your case you have two json objects.
for(i,i<jArray.size,i++)
{
JsonObject obj=jArray.get(i);
// here you got your first entry in jsonObject.
// nor use this obj according to ur need. you can say obj.getString("placeID");
// and so on.
}
refer this to understand more on json link
use JSONArray class:
JSONArray jsonplaces = new JSONObject(stringPlaces);
then your able to iterate throught array by using for-loop:
for (int i = 0; i < jsonplaces.length(); i++) {
JSONObject jsonplace = (JSONObject) jsonplaces.get(i);
//read items, for example:
String placeName = jsonplace.getString("placeName");
}

Categories

Resources