使用JSON更新数据库不执行更新或删除

时间:2013-07-17 22:20:01

标签: android json

现在解决了崩溃问题后,应用程序没有执行更新或删除 当我更新它立即崩溃,但当我删除它显示我吐司,然后没有任何反应

这是班级

public class EditCard extends Activity {

    EditText txtName;
    EditText txtPosition;
    EditText txtCollege;
    EditText txtPhone;
    Button btnSave;
    Button btnDelete;

    String cid;

    // Progress Dialog
    private ProgressDialog pDialog;

    // JSON parser class
    JSONParser jsonParser = new JSONParser();

    // single product url
    private static final String url_card_details = "http://XXX";

    // url to update product
    private static final String url_update_card = "http://XXX";

    // url to delete product
    private static final String url_delete_card = "http://XXX";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_CARDS = "cards";
    private static final String TAG_CID = "cid";
    private static final String TAG_CNAME = "name";
    private static final String TAG_POSITION = "position";
    private static final String TAG_COLLEGE = "college";
    private static final String TAG_PHONE = "phone";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_card);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
        .permitAll().build();
        StrictMode.setThreadPolicy(policy);
        // save button
        btnSave = (Button) findViewById(R.id.SaveCard);
        btnDelete = (Button) findViewById(R.id.DeleteCard);

        // getting product details from intent
        Intent i = getIntent();

        // getting product id (pid) from intent
        cid = i.getStringExtra(TAG_CID);

        // Getting complete product details in background thread
        new GetCardDetails().execute();

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

            @Override
            public void onClick(View arg0) {
                // starting background task to update product
                new SaveCardDetails().execute();
            }
        });

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

            @Override
            public void onClick(View arg0) {
                // deleting product in background thread
                new DeleteCard().execute();
            }
        });

    }

    /**
     * Background Async Task to Get complete product details
     * */
    class GetCardDetails extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(EditCard.this);
            pDialog.setMessage("Loading card details. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Getting product details in background thread
         * */
        protected String doInBackground(String... params) {

            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    // Check for success tag
                    int success;
                    try {
                        // Building Parameters
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair("cid", cid));

                        // getting product details by making HTTP request
                        // Note that product details url will use GET request
                        JSONObject json = jsonParser.makeHttpRequest(
                                url_card_details, "GET", params);

                        // check your log for json response
                        Log.d("Single Product Details", json.toString());

                        // json success tag
                        success = json.getInt(TAG_SUCCESS);
                        if (success == 1) {
                            // successfully received product details
                            JSONArray cardObj = json
                                    .getJSONArray(TAG_CARDS); // JSON Array

                            // get first product object from JSON Array
                            JSONObject card = cardObj.getJSONObject(0);

                            // product with this pid found
                            // Edit Text
                            txtName = (EditText) findViewById(R.id.editCard1);
                            txtPosition = (EditText) findViewById(R.id.editCard2);
                            txtCollege= (EditText) findViewById(R.id.editCard3);
                            txtPhone= (EditText) findViewById(R.id.editCard4);

                            // display product data in EditText
                            txtName.setText(card.getString(TAG_CNAME));
                            txtPosition.setText(card.getString(TAG_POSITION));
                            txtCollege.setText(card.getString(TAG_COLLEGE));
                            txtPhone.setText(card.getString(TAG_PHONE));

                        }else{
                            // product with pid not found
                        }
                    } 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 got all details
            pDialog.dismiss();
        }
    }

    /**
     * Background Async Task to  Save product Details
     * */
    class SaveCardDetails extends AsyncTask<String, String, String> {

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

        /**
         * Saving product
         * */
        protected String doInBackground(String... args) {

            // getting updated data from EditTexts
            String name = txtName.getText().toString();
            String position = txtPosition.getText().toString();
            String college = txtCollege.getText().toString();
            String phone = txtPhone.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", name));
            params.add(new BasicNameValuePair("position", position));
            params.add(new BasicNameValuePair("college", college));
            params.add(new BasicNameValuePair("phone", phone));

            // sending modified data through http request
            // Notice that update product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_update_card,
                    "POST", params);

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

                if (success == 1) {
                    // successfully updated
                    Intent i = getIntent();
                    // send result code 100 to notify about product update
                    setResult(100, i);
                    finish();
                } else {
                    // failed to update 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 product uupdated
            Toast.makeText(getApplicationContext(), "The Student Card Updated sucessfully", Toast.LENGTH_LONG).show();
            pDialog.dismiss();
        }
    }

    /*****************************************************************
     * Background Async Task to Delete Product
     * */
    class DeleteCard extends AsyncTask<String, String, String> {

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

        /**
         * Deleting product
         * */
        protected String doInBackground(String... args) {

            // Check for success tag
            int success;
            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("cid", cid));

                // getting product details by making HTTP request
                JSONObject json = jsonParser.makeHttpRequest(
                        url_delete_card, "POST", params);

                // check your log for json response
                Log.d("Delete Card", json.toString());

                // json success tag
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    // product successfully deleted
                    // notify previous activity by sending code 100
                    Intent i = getIntent();
                    // send result code 100 to notify about product deletion
                    setResult(100, i);
                    finish();
                }
            } 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 product deleted
            Toast.makeText(getApplicationContext(), "The Student Card deleted sucessfully", Toast.LENGTH_LONG).show();
            pDialog.dismiss();

        }

    }
}

这是我更新时的LogCat

07-18 01:15:53.053: W/dalvikvm(8740): threadid=11: thread exiting with uncaught exception (group=0x40a71930)
07-18 01:15:53.383: E/AndroidRuntime(8740): FATAL EXCEPTION: AsyncTask #1
07-18 01:15:53.383: E/AndroidRuntime(8740): java.lang.RuntimeException: An error occured while executing doInBackground()
07-18 01:15:53.383: E/AndroidRuntime(8740):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
07-18 01:15:53.383: E/AndroidRuntime(8740):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
07-18 01:15:53.383: E/AndroidRuntime(8740):     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
07-18 01:15:53.383: E/AndroidRuntime(8740):     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
07-18 01:15:53.383: E/AndroidRuntime(8740):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
07-18 01:15:53.383: E/AndroidRuntime(8740):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
07-18 01:15:53.383: E/AndroidRuntime(8740):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
07-18 01:15:53.383: E/AndroidRuntime(8740):     at java.lang.Thread.run(Thread.java:856)
07-18 01:15:53.383: E/AndroidRuntime(8740): Caused by: java.lang.NullPointerException
07-18 01:15:53.383: E/AndroidRuntime(8740):     at com.example.ahliaevents.EditCard$SaveCardDetails.doInBackground(EditCard.java:210)
07-18 01:15:53.383: E/AndroidRuntime(8740):     at com.example.ahliaevents.EditCard$SaveCardDetails.doInBackground(EditCard.java:1)
07-18 01:15:53.383: E/AndroidRuntime(8740):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
07-18 01:15:53.383: E/AndroidRuntime(8740):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
07-18 01:15:53.383: E/AndroidRuntime(8740):     ... 4 more

这是我删除时的LogCat

07-18 01:18:01.584: E/JSON Parser(8850): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject

1 个答案:

答案 0 :(得分:0)

对于您的删除崩溃,您没有从服务器返回JSON,您可能会收到错误页面。解析器期望看到JSON,它看到的似乎是XML / XHTML文档的开头。

对于你的其他崩溃,只需在第210行查看你的来源。你得到一个NullPointerException,这意味着你期望某个东西成为一个对象,但它是一个空引用。

最令人担忧的是你在runOnUiThread()内使用doInBackground() doInBackground的全部意义是避免UI线程。