0

尝试执行 JSON 查询时出现 AndroidBlockGuardPolicy 错误。看看其他例子,我想使用 AsyncTask,我以为我做到了,但我得到了一个错误......我只是没有看到什么吗?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.pm_article);
    context = this;

    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
    .detectAll()
    .penaltyLog()
    .penaltyDialog()
    .build());


    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
    // getting product details from intent
     Intent i = getIntent();

        // getting product id -section id (sid) from intent

        //Receive the section id (SID) from th intent
        String id = i.getStringExtra(PM_section.INTENT_ID);
        id_pub = id;
        new GetProductDetails().execute();

}

异步任务

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


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

        /**
         * Getting product details in background thread
         * */

        protected String doInBackground(String... args) {
            runOnUiThread(new Runnable() {
                public void run () {
                    SharedPreferences sharedPrefs = PreferenceManager
                            .getDefaultSharedPreferences(context);
                    int success;
                    try {
                        //sid2.setText("ID: " + id_pub); 
                        // Building Parameters
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair("id", id_pub));
                        System.out.println("Loading stories into the activity!");
                        // getting product details by making HTTP request
                        // Note that product details url will use GET request
                        JSONObject json = jParser.makeHttpRequest(url_load_article, "GET", params);
                        System.out.println("Loading stories into the actisadfsafdsafvity!");
                        // 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 contentObj = json
                                    .getJSONArray(TAG_PRODUCT); // JSON Array

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

                            // product with this pid found
                            // Edit Text
                            art_title = (TextView) findViewById(R.id.display_title);
                            art_author = (TextView) findViewById(R.id.display_author);
                            art_publishtime = (TextView) findViewById(R.id.display_date);
                            art_content = (TextView) findViewById(R.id.display_content);

                            // display product data in TextView
                            int text_size = Integer.parseInt(sharedPrefs.getString("prefFontSize", "1"));

                            art_title.setText(product.getString(TAG_TITLE));
                                art_title.setTextSize(TypedValue.COMPLEX_UNIT_SP, text_size+20);
                            art_author.setText(product.getString(TAG_AUTHOR));
                                art_author.setTextSize(TypedValue.COMPLEX_UNIT_SP, text_size+14);    
                                      art_publishtime.setText(product.getString(TAG_PUBLISHTIME));
                                art_publishtime.setTextSize(TypedValue.COMPLEX_UNIT_SP, text_size+14);
                            art_content.setText(product.getString(TAG_CONTENT));
                                art_content.setTextSize(TypedValue.COMPLEX_UNIT_SP, text_size+18);

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

    }   

错误日志

01-06 22:58:42.263: E/AndroidRuntime(23835): FATAL EXCEPTION: main
01-06 22:58:42.263: E/AndroidRuntime(23835): android.os.NetworkOnMainThreadException
01-06 22:58:42.263: E/AndroidRuntime(23835):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
01-06 22:58:42.263: E/AndroidRuntime(23835):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
01-06 22:58:42.263: E/AndroidRuntime(23835):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
01-06 22:58:42.263: E/AndroidRuntime(23835):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
01-06 22:58:42.263: E/AndroidRuntime(23835):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
01-06 22:58:42.263: E/AndroidRuntime(23835):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
01-06 22:58:42.263: E/AndroidRuntime(23835):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
01-06 22:58:42.263: E/AndroidRuntime(23835):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
01-06 22:58:42.263: E/AndroidRuntime(23835):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
01-06 22:58:42.263: E/AndroidRuntime(23835):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-06 22:58:42.263: E/AndroidRuntime(23835):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
01-06 22:58:42.263: E/AndroidRuntime(23835):    at com.example.pt_layout_test3.JSONParser.makeHttpRequest(JSONParser.java:62)
01-06 22:58:42.263: E/AndroidRuntime(23835):    at com.example.pt_layout_test3.PM_article$GetProductDetails$1.run(PM_article.java:180)
01-06 22:58:42.263: E/AndroidRuntime(23835):    at android.os.Handler.handleCallback(Handler.java:615)
01-06 22:58:42.263: E/AndroidRuntime(23835):    at android.os.Handler.dispatchMessage(Handler.java:92)
01-06 22:58:42.263: E/AndroidRuntime(23835):    at android.os.Looper.loop(Looper.java:137)
01-06 22:58:42.263: E/AndroidRuntime(23835):    at android.app.ActivityThread.main(ActivityThread.java:4745)
01-06 22:58:42.263: E/AndroidRuntime(23835):    at java.lang.reflect.Method.invokeNative(Native Method)
01-06 22:58:42.263: E/AndroidRuntime(23835):    at java.lang.reflect.Method.invoke(Method.java:511)
01-06 22:58:42.263: E/AndroidRuntime(23835):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-06 22:58:42.263: E/AndroidRuntime(23835):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-06 22:58:42.263: E/AndroidRuntime(23835):    at dalvik.system.NativeStart.main(Native Method)
4

1 回答 1

2

当前,您正在尝试访问 Ui 元素并runOnUiThreaddoInBackgroundAsyncTask 运行,这是不可能的。

当 doInBackground 执行完成时,您需要将所有 UI 元素初始化移入onPreExecuteonPostExecute用于更新 UI 元素。将您的课程创建AsyncTask为:

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

// Declare UI elemnts here

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
              // show ProgressDialog and initilize Ui elemnts
        }

        protected String doInBackground(String... args) {

             // add your code here from makeing JSON request 
             // 
            return null;
        }
        protected void onPostExecute(String file_url) {
            // Update UI when doInBackground exection completes
        }

    }   

有关我们如何在应用程序中使用 AsyncTask 的更多信息,请参见:

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

于 2013-01-07T07:03:14.347 回答