java - 进度对话框使异步任务中的 Activity 崩溃

标签 java android android-asynctask progressdialog

我有一个正在工作的异步任务,我在其中放置了一个进度对话框。问题是当我将进度对话框放入其中时会崩溃:

public class CheckBeerJSON extends AsyncTask
<String, Void, String> {

    Context c;
    String b;
    private ProgressDialog Dialog = new ProgressDialog(c);

    public CheckBeerJSON(Context context, String beer)
    {
         c = context;
         b = beer;
    }

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        return readJSONFeed(arg0[0]);
    }

    protected void onPreExecute() {
        Dialog.setMessage("Checking your portfolio");

        Dialog.setTitle("Searching");
        Dialog.show();
    }

    protected void onPostExecute(String result){

        //decode json here
        try{

            JSONObject json = new JSONObject(result);
            String status = json.getString("status");

            if(status.equals("no")){


                String message = "Beer not logged";
                Toast.makeText(c,  message, Toast.LENGTH_SHORT).show();

                //clear loader image
                LinearLayout ll = (LinearLayout) (LinearLayout)((Activity) c).findViewById(R.id.addBeerLayout);
                ll.removeAllViews();

                //Add beer add button
                LayoutInflater mInflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                LinearLayout addButton = (LinearLayout)((Activity) c).findViewById(R.id.addBeerLayout);
                addButton.addView(mInflater.inflate(R.layout.addbeerbutton_layout, null)); 


            }

            else{
                String message = "You have the beer!!";
                Toast.makeText(c,  message, Toast.LENGTH_SHORT).show();

                //clear loader image
                LinearLayout ll = (LinearLayout) (LinearLayout)((Activity) c).findViewById(R.id.addBeerLayout);
                ll.removeAllViews();

                //inflate star rater
                LayoutInflater mInflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                LinearLayout addButton = (LinearLayout)((Activity) c).findViewById(R.id.addBeerLayout);
                addButton.addView(mInflater.inflate(R.layout.addrate_layout, null));

                RatingBar r = (RatingBar) ((Activity) c).findViewById(R.id.beerRatingBar);

                //get user data
                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
                String userID = prefs.getString("userID", null);

                //get beer rating with async task and update rate bar
                String url = "my_other_url";
                String userURLComp = "u=" + userID;
                String beerID = "&b=" + b;

                url = url + userURLComp + beerID;



                new GetUserRating(c,r).execute(url);

                //add listener to bar
                addListenerOnRatingBar(c);









            }


        }
        catch(Exception e){

        }

        Dialog.dismiss();

    }





    private void addListenerOnRatingBar(Context view) {
        RatingBar ratingBar = (RatingBar) ((Activity) view).findViewById(R.id.beerRatingBar);

        ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
            public void onRatingChanged(RatingBar ratingBar, float rating,
                boolean fromUser) {

                //next async task to update online database
                float stars = ratingBar.getRating();

                //get user details
                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
                String userID = prefs.getString("userID", null);

                //get beer id
                String beerID = b;

                //get rating
                String urlRate = "r=" + String.valueOf(ratingBar.getRating());
                String urlUserID = "&u=" + userID;
                String urlBeerID = "&b=" + beerID;

                //construct url
                String url2 = "my_url";

                url2 = url2 + urlRate + urlUserID + urlBeerID;

                Log.d("addRateing", url2);

                //async task to update rating in database
                new UpdateRating(c).execute(url2);





            }
        });
    }

    public String readJSONFeed(String URL) {
        StringBuilder stringBuilder = new StringBuilder();
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(URL);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                inputStream.close();
            } else {
                Log.d("JSON", "Failed to download file");
            }
        } catch (Exception e) {
            Log.d("readJSONFeed", e.getLocalizedMessage());
        }        
        return stringBuilder.toString();
    }




}

我得到的错误是:

08-16 21:22:34.054  10772-10772/com.beerportfolio.beerportfoliopro E/AndroidRuntime: FATAL EXCEPTION: main
        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.beerportfolio.beerportfoliopro/com.example.beerportfoliopro.BeerPage}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2332)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2368)
        at android.app.ActivityThread.access$600(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1330)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:155)
        at android.app.ActivityThread.main(ActivityThread.java:5536)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1074)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:841)
        at dalvik.system.NativeStart.main(Native Method)
        Caused by: java.lang.NullPointerException
        at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:142)
        at android.app.AlertDialog.<init>(AlertDialog.java:98)
        at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
        at com.example.beerportfoliopro.CheckBeerJSON.<init>(CheckBeerJSON.java:37)
        at com.example.beerportfoliopro.BeerPage.onCreate(BeerPage.java:83)
        at android.app.Activity.performCreate(Activity.java:5066)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1102)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2288)
        ... 11 more

最佳答案

私有(private) ProgressDialog 对话框 = new ProgressDialog(c);

c 为空,请尝试以下代码。

private ProgressDialog Dialog;

public CheckBeerJSON(Context context, String beer)
{
     c = context;
     Dialog = new ProgressDialog(c);
     b = beer;
}

关于java - 进度对话框使异步任务中的 Activity 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18284225/

相关文章:

android - 如何设计具有圆角和阴影的弹出窗口

java - CraftingManager 错误

java - NoClassDefFoundError : Problems with linking my own jar to Android project

java - Java 或 PHP 中缺少方法

安卓网络实时时钟

Android 在 Asynctask 中使用多种方法

android - 在 AsyncTask 中获取 TextView - Android

android - AsyncTaskLoader 基本示例。 (安卓)

java - DecimalFormat 类不必要地给出四舍五入的数字

java - 使用jsoup从html获取属性