English 中文(简体)
AsyncTask的ProgressDialog 扔出一个无线点的例外吗?
原标题:ProgressDialog in AsyncTask throwing a NullPointerException?

I m trying to display a ProgressDialog while loading a json feed from a http server. I get a NullPointerException in doInBackground and onPostExecute. If I have not misunderstood AsyncTask, in onPostExecute the final code will run! Where is my fault? Here s my activity code:

public class ResultInput extends Activity {

    int count = 0;
    String mainUrl;
    String[] product_pict_part;
    InputStream is = null;
    private ProgressDialog pd;
    String TAG = "meinDebug";
    ParseEan parse_code;
    String readProductNameEan;
    ImageView productPic;
    String productName;
    Drawable drawable;
    TextView product_name;
    TextView text_level;
    int productLevel;

    private Context context;

    // private MyProgressDialog dialog;
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        new ProgressTask(ResultInput.this).execute();
    }

    private InputStream fetch(String urlString) throws MalformedURLException,
            IOException {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet request = new HttpGet(urlString);
        HttpResponse response = httpClient.execute(request);
        return response.getEntity().getContent();
    }

    private class ProgressTask extends AsyncTask<String, Void, Boolean> {
        private ProgressDialog dialog;
        private Activity activity;

        // private List<Message> messages;
        public ProgressTask(Activity activity) {
            this.activity = activity;
            context = activity;
            dialog = new ProgressDialog(context);
        }

        /** progress dialog to show user that the backup is processing. */

        /** application context. */

        protected void onPreExecute() {
            this.dialog.setMessage("Progress start");
            this.dialog.show();
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            pd.dismiss();
            productPic.setImageDrawable(drawable);

            Log.i(TAG, "Picture URL " + mainUrl);
            product_name.setText(productName);

            if (productLevel == 1) {
                text_level.setText("helal");
            } else if (productLevel == 2) {
                text_level.setText("mittel");
            } else if (productLevel == 3) {
                text_level.setText("haram");
            } else if (productLevel == 4) {
                text_level.setText("in analyse");
            }

            if (dialog.isShowing()) {
                dialog.dismiss();
            }

            if (success) {
                Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
            }
        }

        protected Boolean doInBackground(final String... args) {
            try {
                mainUrl = "http://nur-efsan.de/websHalalCheck/public/image/index/dir/";
                product_name = (TextView) findViewById(R.id.produkt_name);
                text_level = (TextView) findViewById(R.id.text_level);
                productPic = (ImageView) findViewById(R.id.productpic);
                productName = parse_code.parseJSONPost("data", "name",
                        readProductNameEan);
                String productPicture = parse_code.parseJSONPost("data",
                        "image", readProductNameEan);
                productLevel = Integer.parseInt(parse_code.parseJSONPost(
                        "data", "levelId", readProductNameEan));

                product_pict_part = productPicture.split("/");
                mainUrl = mainUrl + product_pict_part[0] + "/name/"
                        + product_pict_part[1];

                try {
                    is = fetch(mainUrl);
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                drawable = Drawable.createFromStream(is, "src");

                return true;
            } catch (Exception e) {
                Log.e("tag", "error", e);
                return false;
            }
        }

    }

}
问题回答

在 OnPostExecut 方法中

 dialog.dismiss();

< 强 > 而不是

 pd.dismiss();

<强 > 第二

您不应该在 doInBackgroud (...) 方法中重现 TextView 或图像view( 产品名称、 testview... ), 因为 Ginbackgroud (...) 方法不是 UI 线索 。

因此在 Create 方法上重现, 然后调用 AyncTask 和设置 Value, 在 on PostExecut 方法中...

many thanks for the reply! i change my code as you have described it to me! and i have forget to set my content view :) my final code:

package com.halal.helalcheck;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

public class ResultInput extends Activity {

    int count = 0;
    String mainUrl;
    String[] product_pict_part;
    InputStream is = null;
    String TAG = "meinDebug";
    ParseEan parse_code = new com.halal.helalcheck.ParseEan();
    String readProductNameEan;
    ImageView productPic;
    String productName;
    Drawable drawable;
    TextView product_name;
    TextView text_level;
    int productLevel;


    private Context context;

    // private MyProgressDialog dialog;
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.resultwindow);

        mainUrl = "http://nur-efsan.de/websHalalCheck/public/image/index/dir/";
        product_name = (TextView) findViewById(R.id.produkt_name);
        text_level = (TextView) findViewById(R.id.text_level);
        productPic = (ImageView) findViewById(R.id.productpic);


        new ProgressTask(ResultInput.this).execute();


    }

    private InputStream fetch(String urlString) throws MalformedURLException,
            IOException {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet request = new HttpGet(urlString);
        HttpResponse response = httpClient.execute(request);
        return response.getEntity().getContent();
    }

    private class ProgressTask extends AsyncTask<String, Void, Boolean> {
        private ProgressDialog dialog;
        private Activity activity;

        public ProgressTask(Activity activity) {
            this.activity = activity;
            context = activity;
            dialog = new ProgressDialog(context);
        }

        /** progress dialog to show user that the backup is processing. */

        /** application context. */

        @Override
        protected void onPreExecute() {
            this.dialog.setMessage("Checking Product");
            this.dialog.show();
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            drawable = Drawable.createFromStream(is, "src");
            productPic.setImageDrawable(drawable);
            Log.i(TAG, "Picture URL " + mainUrl);
            product_name.setText(productName);

            if (productLevel == 1) {
                text_level.setText("helal");
            } else if (productLevel == 2) {
                text_level.setText("mittel");
            } else if (productLevel == 3) {
                text_level.setText("haram");
            } else if (productLevel == 4) {
                text_level.setText("in analyse");
            }

            if (dialog.isShowing()) {
                dialog.dismiss();
            }

        }

        @Override
        protected Boolean doInBackground(final String... args) {
            try {
                Bundle b = getIntent().getExtras();
                String ean_code = b.getString("barcodestring");


                String readProductNameEan = parse_code.readProductEan(ean_code);
                Log.i(TAG, readProductNameEan);
                productName = parse_code.parseJSONPost("data", "name", readProductNameEan);
                Log.i(TAG, productName);

                productLevel = Integer.parseInt(parse_code.parseJSONPost( "data", "levelId", readProductNameEan));

                String productPicture = parse_code.parseJSONPost("data", "image", readProductNameEan);
                product_pict_part = productPicture.split("/");
                mainUrl = mainUrl + product_pict_part[0] + "/name/" + product_pict_part[1];

                try {
                    is = fetch(mainUrl);
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


                return true;
            } catch (Exception e) {
                Log.e("tag", "error", e);
                return false;
            }
        }

    }

}




相关问题
Android - ListView fling gesture triggers context menu

I m relatively new to Android development. I m developing an app with a ListView. I ve followed the info in #1338475 and have my app recognizing the fling gesture, but after the gesture is complete, ...

AsyncTask and error handling on Android

I m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What s unclear to me is how to handle ...

Android intent filter for a particular file extension?

I want to be able to download a file with a particular extension from the net, and have it passed to my application to deal with it, but I haven t been able to figure out the intent filter. The ...

Android & Web: What is the equivalent style for the web?

I am quite impressed by the workflow I follow when developing Android applications: Define a layout in an xml file and then write all the code in a code-behind style. Is there an equivalent style for ...

TiledLayer equivalent in Android [duplicate]

To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?

Using Repo with Msysgit

When following the Android Open Source Project instructions on installing repo for use with Git, after running the repo init command, I run into this error: /c/Users/Andrew Rabon/bin/repo: line ...

Android "single top" launch mode and onNewIntent method

I read in the Android documentation that by setting my Activity s launchMode property to singleTop OR by adding the FLAG_ACTIVITY_SINGLE_TOP flag to my Intent, that calling startActivity(intent) would ...

From Web Development to Android Development

I have pretty good skills in PHP , Mysql and Javascript for a junior developer. If I wanted to try my hand as Android Development do you think I might find it tough ? Also what new languages would I ...

热门标签