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);
}
Related
I'm getting the above-mentioned error while trying to extract data from JSONObject.My objective is to extract the "transactionId" data and store it in a variable for future use.
What I have so far:
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()) {
pd.dismiss();
}
/*txtJson.setText(result);*/
JSONObject jsonarray;
try {
jsonarray = new JSONObject(result);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject mJsonObject = jsonarray.getJSONObject(i);
Log.d("OutPut", mJsonObject.getString("transactionId"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
My JSON Object is shown below:
{
"merchantId":"X",
"transactionId":"Y"
}
I'm new to Programming so any help would be appreciated.
Try this code
JSONArray jsonarray;
try {
jsonarray = new JSONArray(result);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject mJsonObject = jsonarray.optJSONObject(i);
Log.d("OutPut", mJsonObject.optString("transactionId"));
}
} catch (JSONException e) {
e.printStackTrace();
}
Also, if there is single ITEM in your JSONArray, you can remove forLoop.
And, if the response received is JSONObject then,
JSONObject jsonObject;
try {
jsonObject = new JSONObject(result);
Log.d("OutPut", jsonObject.optString("transactionId"));
} catch (JSONException e) {
e.printStackTrace();
}
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
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();
}
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();
}
I am having the response of one of webservice to get the feeds list and in that response i am getting the two array with the same name.
The problem is that i am not able get the details of the inner array i.e. "ProfileName", "ImageUrl" etc..
I have tried the json parsing.
Below is the response of JSON:
{"Status":true,
"result":
[
{"result": [
{"ProfileName":"followers5","ImageUrl":"http:\/\/192.168.0.1\/webservice2\/uploads\/81.png","Likes":3,"Hearts":2},
{"ProfileName":"followers5","VideoUrl":"http:\/\/192.168.0.1\/webservice2\/uploads\/81.mp4","Likes":0,"Hearts":0}
]}
,{"result":[
{"ProfileName":"followers6","ImageUrl":"http:\/\/192.168.0.1\/webservice2\/uploads\/82.png","Likes":0,"Hearts":2},
{"ProfileName":"followers6","VideoUrl":"http:\/\/192.168.0.1\/webservice2\/uploads\/82.mp4","Likes":0,"Hearts":0}
]}
]
}
I have tried as below:
class feedtask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
Httputils getmethod = new Httputils();
try {
result = getmethod.Getrequest("feeds.php?uid=76");
System.out.println("Feeds Result--->" + result);
JSONObject jobj = new JSONObject(result);
JSONArray ja = jobj.getJSONArray("result");
for (int i = 0; i < ja.length(); i++) {
for (int j = 0; j <= i; j++) {
JSONObject jo = ja.getJSONObject(j);
abcd.add(jo.getString("ProfileName"));
System.out.println("Profile Name--->"
+ jo.getString("ProfileName"));
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
Please help me out to get the details of the second array.
Any help will be appreciated.
Thank you.
try
{
JSONObject _JSONResponse=new JSONObject(response);
String status=_JSONResponse.getString("Status");
JSONArray _ArrayResponse=_JSONResponse.getJSONArray("result");
for(int i=0;i<_ArrayResponse.length();i++)
{
JSONArray object=_ArrayResponse.getJSONObject(i).getJSONArray("result");
for(int j=0;j<object.length();j++)
{
JSONObject jObject=object.getJSONObject(j);
ProfileName=jObject.getString("ProfileName") ;
VideoUrl=jObject.optString("VideoUrl") ;
Likes=jObject.optString("Likes") ;
Hearts=jObject.optString("Hearts") ;
Log.i(TAG,ProfileName +" "+VideoUrl +" "+Likes+" " +Hearts);
}
}
}
catch(JSONException e){Log.e(TAG,e.toString());}
try{
JSONObject responseJson = new JSONObject(response);
if(responseJson.has("result")){
JSONArray resultJsonArr = responseJson.getJSONArray("result");
for(int i=0; i<resultJsonArr.length(); i++){
JSONObject resultInstanceJson = resultJsonArr.getJSONObject(i);
if(resultInstanceJson.has("result")){
JSONArray resultArr = resultInstanceJson.getJSONArray("result");
for(int j=0; j<resultArr.length(); j++){
JSONObject jsonResult = resultArr.getJSONObject(j);
String profileNAme = jsonResult.getString("ProfileName");
String imageUrl = "", videoUrl = "";
//image url
if(jsonResult.has("ImageUrl")){
imageUrl = jsonResult.getString("ImageUrl");
}
//video url
if(jsonResult.has("VideoUrl")){
videoUrl = jsonResult.getString("VideoUrl");
}
}
}
}
}
}catch(Exception e){
e.printStackTrace();
}
try this way
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = ja.getJSONObject(i);
JSONArray innerResult = jo.getJSONArray("result");
int size = innerResult.legth();
for (int j = 0; j < size; j++) {
JSONObject innerJo = innerResult.getJSONObject(j);
abcd.add(innerJo.getString("ProfileName"));
}
}
Edit:
public class InfoHolder {
public String profileName;
public String imageUrl;
public String videUrl;
}
for (int j = 0; j < size; j++) {
InfoHolder holder = new InfoHolder();
JSONObject innerJo = innerResult.getJSONObject(j);
// the same for imageUrl and videoUrl
holder.profileName = innerJo.getString("ProfileName");
abcd.add(holder);
}
of course you have to change from String to InfoHolder your abcd collectio
Try this:
try {
result = getmethod.Getrequest("feeds.php?uid=76");
System.out.println("Feeds Result--->" + result);
JSONObject jobj = new JSONObject(result);
JSONArray ja = jobj.getJSONArray("result");
for (int i = 0; i < ja.length(); i++) {
for (int j = 0; j < i; j++) {
JSONObject jo = ja.getJSONObject(j);
JSONArray resultJA = jo.getJSONArray("result");
for(int k=0;k< resultJA.length();k++){
JSONObject jo_inside = resultJA.getJSONObject(k);
String profileName = jo_inside.getString("ProfileName");
//use optString on JSONOBject. it will return empty String if that key does not exists or else the value u want. it won't give any exceptions.
String ImageURL = jo_inside.optString("ImageUrl");
String VideoURL = jo_inside.optString("VideoUrl");
}
}
}
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
You do
for (int i = 0; i < ja.length(); i++) {
ok for the first array now you need to get the array inside each cells of the first
For example :
JSONObject jo = ja.getJSONObject(i);
JSONArray ja2 = jo.getJSONArray("result");
then and only then you do the second loop
Maybe this answer isn't complete but the idea is here