0

更新类崩溃了,我无法打开它,而且我不了解 LogCat:

07-17 19:28:22.115: D/dalvikvm(3799): GC_FOR_ALLOC freed 133K, 23% free 12979K/16808K, paused 254ms, total 278ms
07-17 19:28:22.623: D/dalvikvm(3799): GC_FOR_ALLOC freed 15K, 15% free 14345K/16808K, paused 58ms, total 58ms
07-17 19:28:22.666: I/dalvikvm-heap(3799): Grow heap (frag case) to 16.517MB for 2514028-byte allocation
07-17 19:28:22.863: D/dalvikvm(3799): GC_FOR_ALLOC freed <1K, 13% free 16800K/19264K, paused 192ms, total 192ms
07-17 19:28:23.003: D/dalvikvm(3799): GC_CONCURRENT freed 0K, 13% free 16800K/19264K, paused 8ms+24ms, total 147ms
07-17 19:28:23.133: D/dalvikvm(3799): GC_FOR_ALLOC freed 1380K, 13% free 16801K/19264K, paused 57ms, total 58ms
07-17 19:28:23.173: I/dalvikvm-heap(3799): Grow heap (frag case) to 18.916MB for 2514028-byte allocation
07-17 19:28:23.443: D/dalvikvm(3799): GC_CONCURRENT freed <1K, 12% free 19256K/21720K, paused 109ms+10ms, total 269ms
07-17 19:28:28.693: D/AndroidRuntime(3799): Shutting down VM
07-17 19:28:28.703: W/dalvikvm(3799): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
07-17 19:28:28.786: E/AndroidRuntime(3799): FATAL EXCEPTION: main
07-17 19:28:28.786: E/AndroidRuntime(3799): android.os.NetworkOnMainThreadException
07-17 19:28:28.786: E/AndroidRuntime(3799):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
07-17 19:28:28.786: E/AndroidRuntime(3799):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
07-17 19:28:28.786: E/AndroidRuntime(3799):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
07-17 19:28:28.786: E/AndroidRuntime(3799):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
07-17 19:28:28.786: E/AndroidRuntime(3799):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
07-17 19:28:28.786: E/AndroidRuntime(3799):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
07-17 19:28:28.786: E/AndroidRuntime(3799):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
07-17 19:28:28.786: E/AndroidRuntime(3799):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
07-17 19:28:28.786: E/AndroidRuntime(3799):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
07-17 19:28:28.786: E/AndroidRuntime(3799):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
07-17 19:28:28.786: E/AndroidRuntime(3799):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
07-17 19:28:28.786: E/AndroidRuntime(3799):     at com.example.ahliaevents.JSONParser.makeHttpRequest(JSONParser.java:62)
07-17 19:28:28.786: E/AndroidRuntime(3799):     at com.example.ahliaevents.EditCard$GetCardDetails$1.run(EditCard.java:131)
07-17 19:28:28.786: E/AndroidRuntime(3799):     at android.os.Handler.handleCallback(Handler.java:725)
07-17 19:28:28.786: E/AndroidRuntime(3799):     at android.os.Handler.dispatchMessage(Handler.java:92)
07-17 19:28:28.786: E/AndroidRuntime(3799):     at android.os.Looper.loop(Looper.java:137)
07-17 19:28:28.786: E/AndroidRuntime(3799):     at android.app.ActivityThread.main(ActivityThread.java:5041)
07-17 19:28:28.786: E/AndroidRuntime(3799):     at java.lang.reflect.Method.invokeNative(Native Method)
07-17 19:28:28.786: E/AndroidRuntime(3799):     at java.lang.reflect.Method.invoke(Method.java:511)
07-17 19:28:28.786: E/AndroidRuntime(3799):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-17 19:28:28.786: E/AndroidRuntime(3799):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-17 19:28:28.786: E/AndroidRuntime(3799):     at dalvik.system.NativeStart.main(Native Method)
07-17 19:28:33.943: I/Process(3799): Sending signal. PID: 3799 SIG: 9

我不明白 LogCat 中写了什么。以前有人遇到过同样的问题吗?

这是我的代码

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

        // 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
            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 Product...");
            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
            pDialog.dismiss();

        }

    }
}

这是代码检查一下我不知道它有什么问题

4

2 回答 2

1

这可以帮助您:

当应用程序尝试在其主线程上执行网络操作时,会引发此类异常。在以下位置运行您的代码AsyncTask

class AsyncTaskClass extends AsyncTask<String, String, String> {



    protected String doInBackground(String... urls) {

            return null;

    }

    protected void onPostExecute(RSSFeed feed) {

    }
}

如何执行任务:

new AsyncTaskClass().execute(String);

不要忘记将其添加到AndroidManifest.xml文件中:

<uses-permission android:name="android.permission.INTERNET"/>
于 2013-07-17T16:42:18.813 回答
0

你得到NetWorkOnMainThreadException. 您正在 ui 线程上执行与网络相关的操作。

使用 athread或使用AsyncTask.

当应用程序尝试在其主线程上执行网络操作时引发的异常。这仅针对面向 Honeycomb SDK 或更高版本的应用程序抛出。

http://developer.android.com/reference/android/os/AsyncTask.html

您也可以查看本教程

http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html

于 2013-07-17T16:40:15.667 回答