0

Iam making an app with connecting to server and reading the json,but am getting java.lang.String org.json.JSONObject.toString()' on a null object reference error.please help me.thanks in advance Here is my activity

    public class NewProductActivity extends Activity {

private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();
EditText inputName;
Button createBtn;

private static String url_create_product = "http://10.0.2.2/create_product.php";

private static final String TAG_SUCCESS = "success";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_product);

    inputName = (EditText)findViewById(R.id.nameEt);
    createBtn = (Button)findViewById(R.id.createBt);

    createBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new CreateNewProduct().execute();
        }
    });

}
class CreateNewProduct extends AsyncTask<String,String,String>{
    String name = inputName.getText().toString();
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(NewProductActivity.this);
        pDialog.setMessage("Creating Product..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }
    protected String doInBackground(String... args){

        inputName = (EditText)findViewById(R.id.nameEt);

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("name",name ));

        JSONObject json = jsonParser.makeHttprequest(url_create_product,
                "POST", params);

        // check log cat fro response
        Log.d("Create Response", json.toString());

        // check for success tag
        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // successfully created product
                Intent i = new Intent(getApplicationContext(), AllProductsActivty.class);
                startActivity(i);

                // closing this screen
                finish();
            } else {
                // failed to create product
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once done
        pDialog.dismiss();
    }
}
}

here is my Json parser public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

public JSONParser(){}

public JSONObject makeHttprequest(String url, String method, List<NameValuePair> params){

    try {
        if (method.equals( "POST")){

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }else if (method .equals( "GET")){
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params,"url");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);


            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }
    }catch (UnsupportedEncodingException e ){
        e.printStackTrace();
    }catch (ClientProtocolException e){
        e.printStackTrace();
    }catch (IOException e){
        e.printStackTrace();
    }
    try{
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null){
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    }catch (Exception e){
        Log.e("Buffer error","Error Converting");
    }
    try {
        jObj = new JSONObject(json);
    }catch (JSONException e){
        Log.e("JSON Parser","Error parsing");
    }

    return jObj;
}
}

here is my php file

      <?php
 $response = array();
  if(isset($_POST['name'])){
   $name =  $_POST['name'];

 $con = mysql_connect("localhost","root","root");
$db = mysql_select_db("db");  
$result = mysql_query("INSERT INTO product(name) VALUES ('$name')");

if($result){
    $response["success"] = 1;
    $response["message"] = "successfully inserted";
    echo json_encode($respone);
}
else {
    $response["success"] = 0;
    $response["message"] ="error occured";
    echo json_encode($response);
}
} else{
 $response["success"] = 0;
   $response["message"] = "required feild missing";
  echo json_encode($response);
}

 ?>

here is my error log

            06-27 18:35:55.097 3462-4317/com.example.joel339.sample           E/JSON Parser: Error parsing

                                                                   --------- beginning of crash
           06-27 18:35:55.097 3462-4317/com.example.joel339.sample E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1


                                                                      Process: com.example.joel339.sample, PID: 3462
                                                                      java.lang.RuntimeException: An error occurred while executing doInBackground()
                                                                          at android.os.AsyncTask$3.done(AsyncTask.java:309)
                                                                          at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                                                                          at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                                                                          at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                                          at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
                                                                          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                          at java.lang.Thread.run(Thread.java:818)
             Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
                                                                          at com.example.joel339.sample.NewProductActivity$CreateNewProduct$override.doInBackground(NewProductActivity.java:70)
                                                                          at com.example.joel339.sample.NewProductActivity$CreateNewProduct$override.access$dispatch(NewProductActivity.java)
                                                                          at com.example.joel339.sample.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:0)
                                                                          at com.example.joel339.sample.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:50)
                                                                          at android.os.AsyncTask$2.call(AsyncTask.java:295)
                                                                          at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                          at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
                                                                          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
                                                                          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
                                                                          at java.lang.Thread.run(Thread.java:818) 

i am able to create a new product,my product list json is being updated,but i cant see the products list

here is the products list activity

   public class AllProductsActivty extends ListActivity {

private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String,String>> productsList;

private static String url_all_products = "http://10.0.2.2/get_all_products_details.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "product";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";

JSONArray products = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_products);

    productsList = new ArrayList<HashMap<String, String>>();

    ListView lv = getListView();

    new LoadAllProducts().execute(url_all_products);
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            String pid = ((TextView)view.findViewById(R.id.pid)).getText().toString();

            Intent in = new Intent(getApplicationContext(),EditProductActivity.class);
            in.putExtra(TAG_PID,pid);

            startActivityForResult(in,100);
        }
    });
}
@Override
protected void onActivityResult(int requestCode,int resultCode , Intent data){
    super.onActivityResult(requestCode,resultCode,data);

    if(resultCode == 100){
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }
}

class LoadAllProducts extends AsyncTask< String,String,String>{
    @Override
    protected void onPreExecute(){
        super.onPreExecute();
        pDialog = new ProgressDialog(AllProductsActivty.this);
        pDialog.setMessage("LoadingProducts.Please Wait");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }
    protected String doInBackground(String... args){
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        JSONObject json = jParser.makeHttprequest(url_all_products,"GET",params);
        Log.d("Allproducts:",json.toString());

        try{
            int success = json.getInt(TAG_SUCCESS);
            if (success == 1){

                products = json.getJSONArray(TAG_PRODUCTS);

                for (int i = 0;i < products.length();i++){
                    JSONObject c =products.getJSONObject(i);

                    String id = c.getString(TAG_PID);
                    String name = c.getString(TAG_NAME);

                    HashMap<String,String> map = new HashMap<String, String>();

                    map.put(TAG_PID,id);
                    map.put(TAG_NAME,name);
                    productsList.add(map);
                }
            }else{
                Intent i = new Intent(getApplicationContext(),NewProductActivity.class);
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        }
        catch (JSONException e){
            e.printStackTrace();
        }
        return null;
    }

    protected void onPostExecute(String file_url){
        pDialog.dismiss();

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ListAdapter adapter = new SimpleAdapter(
                        AllProductsActivty.this,productsList,R.layout.list_view,new String[]{TAG_PID,TAG_NAME},
                        new int[]{R.id.pid,R.id.name});
                setListAdapter(adapter);
            }
        });
    }

}

}

5
  • 1
    you should not initialize view in background thread remove inputName = (EditText)findViewById(R.id.nameEt); inside doInBackground and your jsonObject is null that is why you are getting null pointer expection here // check log cat fro response Log.d("Create Response", json.toString()); Commented Jun 27, 2016 at 11:49
  • Which is '295' line no in your code? Commented Jun 27, 2016 at 11:52
  • then where should i initialise view? Commented Jun 27, 2016 at 12:00
  • @SaravInfern You're right. It could be a problem. But it won't lead to crash. Right? Commented Jun 27, 2016 at 12:01
  • i have edited the logcat Commented Jun 27, 2016 at 13:12

1 Answer 1

1

The error is in this line.

Log.d("Create Response", json.toString());

Because of null object, it gives you null pointer exception. Double check with this line, Just add the safety check as below

if (json == null || json == JSONObject.NULL){
     // error handling.. 
}
else
{
     // Your code
}

Suggestion:(not related to crash)

Just remove this line inputName = (EditText)findViewById(R.id.nameEt); in doInBackground(). You already initilised this variable in onCreate(), so just remove it.

Sign up to request clarification or add additional context in comments.

5 Comments

@sunnyjoel show me your updated code.. Otherwise remove this line Log.d("Create Response", json.toString()); and check it..
yeah it worked.the app doesnt crash now.but its not proceeding the intent to AllProductsActivity.
i added to the code if (if json == null || json.object == null){Log.d("null","null")}; the app doesnt crash now,and logcat shows 06-27 20:00:19.059 5082-5229/com.example.joel339.sample E/JSON Parser: Error parsing 06-27 20:00:19.059 5082-5229/com.example.joel339.sample D/null: null..json is returning empty.
Your json is empty. You have to fix it.. It may be issue related to server side.
how can i do that?please do help me.

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.