0

I have android class to parse a JSON array like this, Now the problem is it is only parsing 'image_first' index i want to parse 'image_second' too. But when i try to parse image_second it will throw some exceptions

code

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;



public class MainActivity extends Activity {

    EditText etResponse;
    TextView tvIsConnected;
    JSONObject jObject;
    JSONArray jCountries = null;
    String image_first;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // get reference to the views
        etResponse = (EditText) findViewById(R.id.etResponse);
        tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);

        // check if you are connected or not
        if(isConnected()){
            tvIsConnected.setBackgroundColor(0xFF00CC00);
            tvIsConnected.setText("You are conncted");
        }
        else{
            tvIsConnected.setText("You are NOT conncted");
        }


        // call AsynTask to perform network operation on separate thread
        new HttpAsyncTask().execute("http://kodspider.com/Android_Test/index.php"/*"http://hmkcode.appspot.com/rest/controller/get.json"*/);
    }

    public static String GET(String url){
        InputStream inputStream = null;
        String result = "";
        try {

            // create HttpClient
            HttpClient httpclient = new DefaultHttpClient();

            // make GET request to the given URL
            HttpResponse httpResponse = httpclient.execute(new HttpGet(url));

            // receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();

            // convert inputstream to string
            if(inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "Did not work!";

        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }

        return result;
    }

    private static String convertInputStreamToString(InputStream inputStream) throws IOException{
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null)
            result += line;

        inputStream.close();
        return result;

    }

    public boolean isConnected(){
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isConnected()) 
                return true;
            else
                return false;   
    }
    private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {

            return GET(urls[0]);
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
            try {
                JSONObject json = new JSONObject(result);

                String str = "";

                JSONArray articles = json.getJSONArray("images");
                str += "articles length = "+json.getJSONArray("images").length();
                str += "\n--------\n";
                str += "names: "+articles.getJSONObject(0).names();
                str += "\n--------\n";
                str += "url: "+articles.getJSONObject(0).getString("image_second");

                etResponse.setText(str);
                etResponse.setText(json.toString(1));

                for(int i=0;i<json.getJSONArray("images").length();i++){

                System.out.println(articles.getJSONObject(i).getString("image_second"));

                }


//              try {
//                  jObject = new JSONObject(result);
//                  // Retrieves all the elements in the 'countries' array 
//                  jCountries = jObject.getJSONArray("images");
//                  for(int i=0;i<jCountries.length();i++){
//                   image_first = jCountries.getJSONObject(i).getString("image_first");
//                  }
//                  System.out.println(image_first);
//              } catch (JSONException e) {
//                  e.printStackTrace();
//              }



            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

                }
       }
    }
}

logcat

05-14 12:19:15.700: W/System.err(581): org.json.JSONException: No value for image_second
05-14 12:19:15.700: W/System.err(581):  at org.json.JSONObject.get(JSONObject.java:354)
05-14 12:19:15.700: W/System.err(581):  at org.json.JSONObject.getString(JSONObject.java:510)
05-14 12:19:15.700: W/System.err(581):  at com.hmkcode.android.MainActivity$HttpAsyncTask.onPostExecute(MainActivity.java:125)
05-14 12:19:15.710: W/System.err(581):  at com.hmkcode.android.MainActivity$HttpAsyncTask.onPostExecute(MainActivity.java:1)
05-14 12:19:15.710: W/System.err(581):  at android.os.AsyncTask.finish(AsyncTask.java:417)
05-14 12:19:15.710: W/System.err(581):  at android.os.AsyncTask.access$300(AsyncTask.java:127)
05-14 12:19:15.710: W/System.err(581):  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
05-14 12:19:15.720: W/System.err(581):  at android.os.Handler.dispatchMessage(Handler.java:99)
05-14 12:19:15.720: W/System.err(581):  at android.os.Looper.loop(Looper.java:123)
05-14 12:19:15.720: W/System.err(581):  at android.app.ActivityThread.main(ActivityThread.java:4627)
05-14 12:19:15.720: W/System.err(581):  at java.lang.reflect.Method.invokeNative(Native Method)
05-14 12:19:15.730: W/System.err(581):  at java.lang.reflect.Method.invoke(Method.java:521)
05-14 12:19:15.730: W/System.err(581):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-14 12:19:15.730: W/System.err(581):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-14 12:19:15.730: W/System.err(581):  at dalvik.system.NativeStart.main(Native Method)
3
  • There is not String for "image_second",So try optString("image_second") insted of getString("image_second") Commented May 14, 2014 at 7:02
  • throwing another exception like 05-14 12:36:49.180: W/System.err(609): org.json.JSONException: End of input at character 0 of Commented May 14, 2014 at 7:06
  • Before getting value try to check if its found or not if(articles.has("image_second")){ str += "url: "+articles.getJSONObject(0).getString("image_second"); } Commented May 14, 2014 at 7:10

2 Answers 2

2

Try to replace this line :

str += "url: "+articles.getJSONObject(0).getString("image_second");

With this :

str += "url: "+articles.getJSONObject(2).getString("image_second");

OR

str += "url: "+articles.getJSONObject(3).getString("image_second");
Sign up to request clarification or add additional context in comments.

2 Comments

@ДмитрийИвановичМенделеев your keys are not the same for all. You have image_first for the first 2 an image_second for the next 2
@ДмитрийИвановичМенделеев i suggest you keep the keys the same so that you can loop through the array.
1
{
    "images": [
        {
            "image_first": "http://kodspider.com/Android_Test/images/bg.jpg"
        },
        {
            "image_first": "http://kodspider.com/Android_Test/images/gmail_bg.jpg"
        },
        {
            "image_second": "http://kodspider.com/Android_Test/images/bbg.jpg"
        },
        {
            "image_second": "http://kodspider.com/Android_Test/images/1425328_405486846250283_806381377_o.jpg"
        }
    ]
}

Change this

for(int i=0;i<json.getJSONArray("images").length();i++){

            System.out.println(articles.getJSONObject(i).getString("image_second"));

}

To

JSONArray articles = json.getJSONArray("images");
JSONObject jb = articles.getJSONObject(0);
String imageurl1 = jb.getString("image_first");
JSONObject jb1 = articles.getJSONObject(1);
String imageurl2 = jb1.getString("image_first");
JSONObject jb2 = articles.getJSONObject(2);
String imageurl3 = jb2.getString("image_second");
JSONObject jb3 = articles.getJSONObject(3);
String imageurl4 = jb3.getString("image_second");

4 Comments

But why i think both would give same result
@ДмитрийИвановичМенделеев it will not. But if you change the key instead of JSONObject jb = articles.getJSONObject(0); you can loop through and use the index. Also you can add more json object and it will still work. edited to change the names
I think i can use like for(inti=0;i<json.getJSONArray("images").length();i++){ System.out.println(articles.getJSONObject(i).optString("image_first")); System.out.println(articles.getJSONObject(i).optString("image_second")); } it gave output as my expectation...
@ДмитрийИвановичМенделеев yes you could do that also. Actually that is the right way or the better way

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.