Naaz
Naaz

Reputation: 273

Most probably error with JSON parsing

Here is my Activity code(which I took from >> http://itweb-projects.com/wordpress/android-connecting-to-mysql-using-php) the problem that I'm facing is that its throwing a JSON error handling its parsing? >>

 package com.database_demo;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.net.ParseException;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Toast;

public class Database_demo extends ListActivity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        String result = null;
        InputStream is = null;
        StringBuilder sb = null;
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        List<String> r = new ArrayList<String>();

        try{

        //http post
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://winacro.com/nishant/andRHOME.php");
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        }
        catch(Exception e){
            Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
       }

        //Convert response to string  
        try
        {
          BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));

          sb = new StringBuilder();

          String line = null;

          while ((line = reader.readLine()) != null) 
          {
             sb.append(line + "\n");
          }

          is.close();

          result = sb.toString();
        }
        catch(Exception e)
        {
            Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
        }
        //END Convert response to string   
        try{
                JSONArray jArray = new JSONArray(result);
                JSONObject json_data=null;
                for(int i=0;i<jArray.length();i++)
                {
                   json_data = jArray.getJSONObject(i);
                   r.add(json_data.getString("category"));
               }
               setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, r));
            }
            catch(JSONException e1){
                Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
            } catch (ParseException e1) {
                Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
        }

    }
}

Here's my Manifest.xml>>

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.database_demo"
      android:versionCode="1"
      android:versionName="1.0">
      <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.INTERNET" />      
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Database_demo"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>


</manifest> 

Here's the LOGCAT reply>>

07-28 09:02:17.435: I/Process(27270): Sending signal. PID: 27270 SIG: 9
07-28 09:02:37.985: D/AndroidRuntime(27812): Shutting down VM
07-28 09:02:37.985: W/dalvikvm(27812): threadid=1: thread exiting with uncaught exception (group=0x420442a0)
07-28 09:02:37.985: E/AndroidRuntime(27812): FATAL EXCEPTION: main
07-28 09:02:37.985: E/AndroidRuntime(27812): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.database_demo/com.database_demo.Database_demo}: java.lang.NullPointerException
07-28 09:02:37.985: E/AndroidRuntime(27812):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at android.app.ActivityThread.access$600(ActivityThread.java:140)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at android.os.Handler.dispatchMessage(Handler.java:99)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at android.os.Looper.loop(Looper.java:137)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at android.app.ActivityThread.main(ActivityThread.java:4898)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at java.lang.reflect.Method.invokeNative(Native Method)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at java.lang.reflect.Method.invoke(Method.java:511)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1008)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:775)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at dalvik.system.NativeStart.main(Native Method)
07-28 09:02:37.985: E/AndroidRuntime(27812): Caused by: java.lang.NullPointerException
07-28 09:02:37.985: E/AndroidRuntime(27812):    at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at org.json.JSONTokener.nextValue(JSONTokener.java:94)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at org.json.JSONArray.<init>(JSONArray.java:87)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at org.json.JSONArray.<init>(JSONArray.java:103)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at com.database_demo.Database_demo.onCreate(Database_demo.java:78)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at android.app.Activity.performCreate(Activity.java:5206)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
07-28 09:02:37.985: E/AndroidRuntime(27812):    ... 11 more

What could be the main reason of thecrash and how can I solve it? I have checked the php file its returning the JSON successfully!

UPDATED CODE WITH ASYNC TASK running to relieve the UI thread:

package com.database_demo;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Toast;

public class Database_demo extends ListActivity {

    String result = null;
    InputStream is = null;
    StringBuilder sb = null;
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    List<String> r = new ArrayList<String>();

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        AsyncTaskRunner runner = new AsyncTaskRunner();
        runner.execute("sleepTime");
     }
    private class AsyncTaskRunner extends AsyncTask<String, String, String> {
        // Do the long-running work in here

        // This is called each time you call publishProgress()

        // This is called when doInBackground() is finished
        @Override
        protected void onPostExecute(String result) {

        }

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            try{

                //http post
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://winacro.com/nishant/andRHOME.php");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
                }
                catch(Exception e){
                    Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
               }

                //Convert response to string  
                try
                {
                  BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));

                  sb = new StringBuilder();

                  String line = null;

                  while ((line = reader.readLine()) != null) 
                  {
                     sb.append(line + "\n");
                  }

                  is.close();

                  result = sb.toString();
                }
                catch(Exception e)
                {
                    Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
                }
                //END Convert response to string   
                try{
                        JSONArray jArray = new JSONArray(result);
                        JSONObject json_data=null;
                        for(int i=0;i<jArray.length();i++)
                        {
                           json_data = jArray.getJSONObject(i);
                           r.add(json_data.getString("category"));
                       }
                       setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, r));
                    }
                    catch(JSONException e1){
                        Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
                    } catch (ParseException e1) {
                        Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
                }


            return null;
        }


    }
}

LATEST LOGCAT>>

Upvotes: 1

Views: 356

Answers (3)

setListAdapter(new ArrayAdapter(this, android.R.layout.simple_expandable_list_item_1, r));

instead of this use filename.this

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234847

First, you are doing network access on the UI thread. This is a big no-no and, if you are running with API 11 or later, it will throw a NetworkOnMainThreadxception. However, if you do get an exception, you are continuing to try to parse the (null) response stream.

You need to move the network processing to a separate thread and you need to improve your error handling. Displaying a Toast and continuing as if nothing went wrong is a recipe for disaster. You need to stop processing and alert the user if there is a problem receiving the response. See the Keeping Your App Responsive article.

Upvotes: 2

Related Questions