ANDROID : How to use org.json.JSONArray in for loop - android

I use library JsonHttpResponseHandler
and this my code
Data JSON is =
[{"id":"4","2":"123","phone":"123","1":"Shin","0":"4","name":"Shin"},{"id":"5","2":"555","phone":"555","1":"Wolf","0":"5","name":"Wolf"},{"id":"6","2":"666","phone":"666","1":"Lunar","0":"6","name":"Lunar"}]
And this my code =
#Override
public void onSuccess(int statusCode, org.apache.http.Header[] headers, org.json.JSONArray response)
Question is how can i use response data in for loop

Use below code ,
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jobj = response.getJSONObject(i);
String id = jobj.getString("id");
String two = jobj.getInt("2");
String phone = jobj.getInt("phone");
String one = jobj.getInt("1");
String zero = jobj.getInt("0");
String name = jobj.getString("name");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

it is the same as array.
for(int i =0 ; i < response.length() ; i++){
JSONObject object = response.getJSONObject(i);
}
inside json array > jsonobject it is like using a List
for your reference : JSON Array iteration in Android/Java

String dataStr="[{\"id\":\"4\",\"2\":\"123\",\"phone\":\"123\",\"1\":\"Shin\",\"0\":\"4\",\"name\":\"Shin\"},{\"id\":\"5\",\"2\":\"555\",\"phone\":\"555\",\"1\":\"Wolf\",\"0\":\"5\",\"name\":\"Wolf\"},{\"id\":\"6\",\"2\":\"666\",\"phone\":\"666\",\"1\":\"Lunar\",\"0\":\"6\",\"name\":\"Lunar\"}]";
try {
JSONArray jsonStrs =new JSONArray("1111");
for(int i=0;i<jsonStrs.length();i++)
{
JSONObject jobj=jsonStrs.getJSONObject(i);
int id=jobj.getInt("id");
String phone=jobj.getString("phone");
//get other values
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Related

How to parse a JSONArray and assign it to different TextViews?

I have a JSONArray and when I try to parse it, an NPE shows and the logcat shows W/System.err: org.json.JSONException: Value at 0 is null. Please help. I have provided my codes below.
JSON Array
[
{
"student_number":"201411870",
"full_name":"Miranda , Andrew Matthew Matera",
"year":"4",
"course":"BSIT"
}
]
Code Snippet
ArrayList<User> userArrayList = new JsonConverter<User>().toArrayList(response, User.class);
JSONArray jsonArray = new JSONArray(userArrayList);
try {
int regStudentNumber = jsonArray.getJSONObject(0).getInt("student_number");
String regFullName = jsonArray.getJSONObject(1).getString("full_name");
int regYear = jsonArray.getJSONObject(2).getInt("year");
String regCourse = jsonArray.getJSONObject(3).getString("course");
tvStudentNumber.setText(String.valueOf(regStudentNumber));
tvFullName.setText(regFullName);
tvYear.setText(String.valueOf(regYear));
tvCourse.setText(regCourse);
} catch (JSONException e) {
e.printStackTrace();
}
Solved it on my own. Sorry for the unclear question.
try {
JSONArray jsonArray = new JSONArray(response);
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int regStudentNumber = jsonObject.getInt("student_number");
String regFullName = jsonObject.getString("full_name");
int regYear = jsonObject.getInt("year");
String regCourse = jsonObject.getString("course");
tvStudentNumber.setText(String.valueOf(regStudentNumber));
tvFullName.setText(regFullName);
tvYear.setText(String.valueOf(regYear));
tvCourse.setText(regCourse);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
First of all parse JSON array to object to make clear it is for a particular value then fetch things from it based on need.
To parse json array to object use code
try {
JSONArray jsonArray = new JSONArray(response);
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
}
}
} catch (JSONException e) {
e.printStackTrace();
}

Android : How to access a JSONObject

I'm new to Android and I have tried so many options to access the JSONObject which returns from an API call but I couldn't succeed as any of the solutions i looked for didn't work for me.
What i want is to access the JSONObject and keep the Id & Name in a Array. And then populate the Names in a AutoCompleteTextView. How do i properly access the JSONObject. Please help me with this. I'm stuck on this for more than a day.
Following is my Code handling the JSONObject.
#Override
public void processFinish(JSONObject output) {
Toast.makeText(MainActivity.this,"ProcessFinish",Toast.LENGTH_SHORT).show();
allStations = output;
if(output != null){
Toast.makeText(MainActivity.this,output.toString(),Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this," Connection Failed!",Toast.LENGTH_SHORT).show();
}
}
Following is a sample output of my JSONObject
{
"SUCCESS": true,
"MESSAGE": "Found 398 Results!",
"NOFRESULTS": 3,
"RESULTS": {
"stationList": [
{
"stationCode": "ABN",
"stationID": 3,
"stationName": "ABLA"
},
{
"stationCode": "ADLA",
"stationID": 410,
"stationName": "ADLA"
},
{
"stationCode": "ANM",
"stationID": 11,
"stationName": "AHAMA"
}]
},
"STATUSCODE": "2000"
}
try this
try {
JSONObject obj= output.getJSONObject("RESULTS");
JSONArray dataArray= obj.getJSONArray(“stationList“);
for(int i=0;i<dataArray.length();i++)
{
JSONObject object1=dataArray.getJSONObject(i);
Strind id = object1.getString("stationID");
}
} catch (JSONException e) {
e.printStackTrace();
}
In This code output is your JSONObject result
try this
try {
JSONObject jsonObject = new JSONObject("response");
boolean status= jsonObject.getBoolean("SUCCESS");
String MESSAGE= jsonObject.getString("MESSAGE");
String NOFRESULTS= jsonObject.getString("NOFRESULTS");
String STATUSCODE= jsonObject.getString("STATUSCODE");
JSONObject obj=jsonObject.getJSONObject("RESULTS");
JSONArray jsonarray = obj.optJSONArray("stationList");
for (int i = 0; i < jsonarray.length(); i++){
JSONObject json_data = jsonarray.getJSONObject(i);
Log.e("stationCode",json_data.getString("stationCode"));
Log.e("stationID",json_data.getString("stationID"));
Log.e("stationName",json_data.getString("stationName"));
}
} catch (JSONException e) {
e.printStackTrace();
}
Have you tried using a JSON Array? For example you could use this method for storage:
JSONObject wgroup = new JSONObject(); //FINAL json object
try { //put initial data
wgroup.put("id", "2");
wgroup.put("user", "someone");
wgroup.put("stime", "2017-02-06 16:30:13");
wgroup.put("etime", "2017-02-06 19:30:13");
wgroup.put("real_dur", 3600);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray1 = new JSONArray(); //Create an array to store ALL Variables
for (int y=0; y< your_array.length ; y++ ){ //loop through your information array
JSONObject output = new JSONObject(); //CREATE a json object to put 1 workout
try {
wgroup.put("id", "2");
wgroup.put("name", "sam");
wgroup.put("age", "3");
wgroup.put("gender", "male");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray2 = new JSONArray(); //CREATE a json array to put 1 array
jsonArray1.put(output); //insert this OBJECT into the ARRAY
}
wgroup.put(jsonArray1);//insert the workouts ARRAY into the original object

Regd : getting value from json url

I want to get the id ^& content value in http://rest-service.guides.spring.io/greeting
What i tried is,
try {
JSONObject jsonObj = new JSONObject(parsingUrl);
// If you have array
JSONArray resultArray = jsonObj.getJSONArray("id"); // Here you will get the Array
// Iterate the loop
for (int i = 0; i < resultArray.length(); i++) {
// get value with the NODE key
JSONObject obj = resultArray.getJSONObject(i);
String name = obj.getString("content");
}
// If you have object
//String result1 = jsonObj.getString("result");
} catch (Exception e) {
e.printStackTrace();
}
Thanks
The url that your mentioned dont have json arrays, parsing will be like
try {
JSONObject jsonObj = new JSONObject(resultfromUrl);
int id = jsonObj.getInt("id");
String name = jsonObj.getString("content");
} catch (JSONException e) {
e.printStackTrace();
}

Loop through Json Object Android

Please can i really need you help with this code , Am using loopj.com/android-async-http To communicate with the server, everything works fine but have been trying to loop through the json object i get from the server.
{"rows":[{"Fname":"Eb\'rahim","Lname":"Durosimi","Predictions":"4","Cpredictions":"3","Points":"15"},{"Fname":"Otunba","Lname":"Alagbe","Predictions":"5","Cpredictions":"2","Points":"10"},{"Fname":"Olamide","Lname":"Jolaoso","Predictions":"4","Cpredictions":"2","Points":"10"},{"Fname":"g","Lname":"ade","Predictions":"1","Cpredictions":"1","Points":"5"},{"Fname":"Tiamiyu","Lname":"waliu","Predictions":"1","Cpredictions":"1","Points":"5"}]}
But have not bin able to get it right,Have tried different examples but to no avail.
public void onSuccess(String content) {
// TODO Auto-generated method stub
super.onSuccess(content);
try {
JSONObject json = new JSONObject(content);
JSONObject leaders= json.getJSONObject("rows");
Log.d("leaders",leaders.toString());
for(int i=0;i<leaders.length(); i++){
String fname = leaders.getString("Fname");
Log.d("First Names",fname);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Thanks for your help
Try this..
{ ==> JSONObject and [ ==> JSONArray
try {
JSONObject json = new JSONObject(content);
JSONArray leaders= json.getJSONArray("rows");
Log.d("leaders",leaders.toString());
for(int i=0;i<leaders.length(); i++){
JSONObject jsonas = leaders.JSONObject(i);
String fname = jsonas.getString("Fname");
Log.d("First Names",fname);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This way you can store all data received from the webservice to a arraylist of hashmaps.
ArrayList<HashMap<String,String>> alist=new ArrayList<HashMap<String,String>>();
try {
JSONObject json = new JSONObject(content);
JSONArray jArray = json.getJSONArray("rows");
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
String fname = json_data.getString("Fname");
String lname = json_data.getString("Lname");
HashMap<String, String>map=new HashMap<String, String>();
map.put("Fname",Fname);
map.put("LName", Lname);
alist.add(map);
}

storing json parsed values as string in array

I've got a json object, which is being collected into a function as string.
It contains array
{"officer_name":"V. M. ARORA"}{"officer_name":"Dr. C. P.
REDDY"}{"officer_name":"ARTI CHOWDHARY"}{"officer_name":"JAGDISH
SINGH"}
and here is the android code
public void func4(View view)throws Exception
{
AsyncHttpClient client = new AsyncHttpClient();
RequestParams rp = new RequestParams();
rp.put("pLat", "SELECT officer_name FROM iwmp_officer");
client.post("http://10.0.2.2/conc5.php", rp, new AsyncHttpResponseHandler() {
public final void onSuccess(String response) {
// handle your response here
ArrayList<String> User_List = new ArrayList<String>();
try {
/* here I need output in an array,
and only names not the "officer_name" */
} catch (Exception e) {
tx.setText((CharSequence) e);
}
//tx.setText(User_List.get(1));
}
#Override
public void onFailure(Throwable e, String response) {
// something went wrong
tx.setText(response);
}
});
}
The output I've shown above is in String, need to get it in array. Please help!
If the output you got is something like this.
String outputJson=[{"officer_name":"V. M. ARORA"}{"officer_name":"Dr. C. P. REDDY"}{"officer_name":"ARTI CHOWDHARY"}{"officer_name":"JAGDISH SINGH"}]
Then its a JSON Array.
You can parse it as
JsonArray array=new JsonArray(outputJson);
Then loop this json array using
for(JsonObject jsonObj in array){
String officerName=[jsonObj getString("officer_name");
}
You can use something like above The mentioned code is not correct syntactically but yes conceptually correct. You can go ahead with this.
List < String > ls = new ArrayList< String >();
JSONArray array = new JSONArray( response );
for (int i = 0; i < array.length() ; i++ ) {
JSONObject obj = array.getJSONObject(Integer.toString(i));
ls.add(obj.getString("officer_name"));
}
This would work
try {
JSONArray array= new JSONArray(response);
//array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
//JSONObject obj = response.getJSONArray(i);
JSONObject jsonLineItem = (JSONObject) array.getJSONObject(i);
String name_fd = jsonLineItem.getString("officer_name");
User_List.add(jsonLineItem.getString("officer_name"));
Log.d("JSONArray", name_fd+" " +name_fd);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
tx.setText( e.toString());
}

Categories

Resources