ds19891231 2016-05-29 15:54
浏览 72

将数据从android添加到mysql数据库时出现NullPointer异常[重复]

This question already has an answer here:

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) 
</div>
  • 写回答

1条回答 默认 最新

  • douzhaolu4839 2016-05-29 16:15
    关注

    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.
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog