0

I'm getting NullPointerException while adding data from android app to MySQL database, so when I click to create a new product this exception occurs. This is my code to add new product in my database:

public class NewProductActivity extends Activity {

    // Progress Dialog
    private ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();
    EditText inputName;
    EditText inputPrice;
    EditText inputDesc;

    // url to create new product
    private static String url_create_product = "http://192.168.56.1/products/create_product.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";

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

        // Edit Text
        inputName = (EditText) findViewById(R.id.inputName);
        inputPrice = (EditText) findViewById(R.id.inputPrice);
        inputDesc = (EditText) findViewById(R.id.inputDesc);

        // Create button
        Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);

        // button click event
        btnCreateProduct.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                String name = inputName.getText().toString();
                String price = inputPrice.getText().toString();
                String description = inputDesc.getText().toString();
                // creating new product in background thread
                new CreateNewProduct().execute(name,price,description);
            }
        });
    }

    /**
     * Background Async Task to Create new product
     * */
    class CreateNewProduct extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(NewProductActivity.this);
            pDialog.setMessage("Creating Product..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Creating product
         * */
        protected String doInBackground(String... args) {
            String name = args[0],
                    price = args[1],
                    description = args[2];
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", name));
            params.add(new BasicNameValuePair("price", price));
            params.add(new BasicNameValuePair("description", description));

            // getting JSON Object
            // Note that create product url accepts POST method
     **line 102**       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(), AllProductsActivity.class);
                    startActivity(i);

                    // closing this screen
                    finish();
                } else {
                    // failed to create product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
        }

    }
}

I checked out my PHP code and it works fine:

<?php  
    $con = mysql_connect('localhost', 'root','');
    mysql_select_db('database',$con);

    $name = $_POST['name'];
    $price = $_POST['price'];
    $description = $_POST['description']; 
    $sql = "insert into products(name, price, description)                   
            values('$name','$price','$description')"; 
    mysql_query($sql); 
?>

Logcat:

FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
  at android.os.AsyncTask$3.done(AsyncTask.java:299)
  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
  at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
  at java.util.concurrent.FutureTask.run(FutureTask.java:239)
  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
  at java.lang.Thread.run(Thread.java:856)
aused by: java.lang.NullPointerException
  at com.example.hanen.test1.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:102)
  at com.example.hanen.test1.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:68)
  at android.os.AsyncTask$2.call(AsyncTask.java:287)
  at java.util.concurrent.FutureTask.run(FutureTask.java:234)
  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
  at java.lang.Thread.run(Thread.java:856) 
HanenO
  • 144
  • 2
  • 10
  • do you know which line of your code caused exception? – pouyan May 29 '16 at 16:00
  • NewProductActivity:102 – G. Blake Meike May 29 '16 at 16:04
  • can you give everything in that class including the import statements? the exception is pointing to line 102, can you check what do you have on line 102 that can possibly cause NullPointerException ? – LeTex May 29 '16 at 16:05
  • @G.BlakeMeike i know that wich class has problem but i dont know that which line of code is line 102. – pouyan May 29 '16 at 16:07
  • Count! ... Or turn on line numbers in your IDE. Sheesh. SO is not an appropriate place to get others to put line numbers on your source file. ;-P – G. Blake Meike May 29 '16 at 16:15
  • @pooyan line is JSONObject json = jsonParser.makeHttpRequest(url_create_product, "POST", params); – HanenO May 29 '16 at 17:07
  • @LeTex line 102 is JSONObject json = jsonParser.makeHttpRequest(url_create_product, "POST", params); – HanenO May 29 '16 at 17:08
  • @honeyyy so it seems that your 'jsonParser' is null. can you debug it and check if it is null ? – pouyan May 29 '16 at 17:12
  • @pooyan debug gives me Client not ready yet. Connected to the target VM, address: 'localhost:8626', transport: 'socket' – HanenO May 29 '16 at 17:42
  • @honeyyy if line 102 is JSONObject json = jsonParser.makeHttpRequest , then you need to understand why your jsonParser is null. – LeTex May 30 '16 at 07:00

1 Answers1

0

I don't have the answer to your question, because you haven't included line numbers on your listing, and I'm not going to hand-number them. Finding and fixing this type of error, though, is dead simple. Here are the steps:

  1. Turn on line numbers in your IDE
  2. Find the line in your code that corresponds to the topmost line in the stacktrace that refers to a line in your code. In this case that is line 102 in the file NewProductActivity.java
  3. On that line, there will be an expression that looks like variable.something.
  4. When that line is executed variable is null. Find out why.
G. Blake Meike
  • 6,615
  • 3
  • 24
  • 40
  • thank you for responding the line is JSONObject json = jsonParser.makeHttpRequest(url_create_product, "POST", params); and i think the problem is related to this line private static String url_create_product = "http://192.168.56.1/products/create_product.php"; but i checked out iPt is v4 is 192.168.56.1,i don't know how to resolve this problem – HanenO May 29 '16 at 17:14
  • bet you are wrong. bet your problem is that is that jsonParser is null. – G. Blake Meike May 29 '16 at 17:35
  • it is null because while debugging it sais Client not ready yet. Connected to the target VM, address: 'localhost:8626', transport: 'socket' – HanenO May 29 '16 at 17:42