NullPointer从android到mysql数据库添加数据时出现异常

时间:2016-05-29 15:54:46

标签: java php android mysql nullpointerexception

我在从Android应用程序向MySQL数据库添加数据时获得NullPointerException,因此当我点击创建新产品时会发生此异常。这是我在我的数据库中添加新产品的代码:

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();
        }

    }
}

我检查了我的PHP代码,它工作正常:

<?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) 

1 个答案:

答案 0 :(得分:0)

我没有您的问题的答案,因为您的商家信息中没有包含行号,我也不打算对它们进行手工编号。但是,找到并修复这种类型的错误死简单。以下是步骤:

  1. 启用IDE中的行号
  2. 在代码中找到与stacktrace中引用代码中一行的最顶行相对应的行。在这种情况下,它是文件NewProductActivity.java
  3. 中的第102行
  4. 在该行上,将有一个类似variable.something的表达式。
  5. 执行该行时variable为空。找出原因。