【问题标题】:NullPointerException for ProgressDialog in AsyncTask [duplicate]AsyncTask 中 ProgressDialog 的 NullPointerException [重复]
【发布时间】:2017-01-01 10:49:56
【问题描述】:

我在 MainActivity 的单独文件中的另一个类中有一个 AsyncTask 类

GetWarehouseSales.java

public class GetWarehouseSales extends Activity {

    private String TAG = MainActivity.class.getSimpleName();
    private ListView lv;
    private ProgressDialog pDialog;
    //URL to get JSON details
    private static String url = "http://192.168.0.1/mycc/retrieve_ws.php";
    ArrayList<HashMap<String,String>> sales_details;

    public GetWarehouseSales(){
    }

    public void executeGWS(){
        new RetrieveWarehouseSalesTask().execute();
    }


    public class RetrieveWarehouseSalesTask extends AsyncTask<Void,Void,Void>{

        public RetrieveWarehouseSalesTask(){

        }

        @Override
        protected void onPreExecute(){
            super.onPreExecute();
            pDialog = new ProgressDialog(GetWarehouseSales.this);
            pDialog.setMessage("Getting you the best warehouse sales...");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected Void doInBackground(Void... arg0){
            HttpHandler sh = new HttpHandler();
            //making a request to URL and getting response
            String jsonStr = sh.makeServiceCall(url);
            Log.e(TAG, "Response from url: " + jsonStr);

            if(jsonStr != null){
                try{
                    JSONObject jsonObj = new JSONObject(jsonStr);
                    //Getting JSON Array Node
                    JSONArray sales = jsonObj.getJSONArray("Result");
                    //looping through all results
                    for(int i = 0; i<sales.length();i++){
                        JSONObject s = sales.getJSONObject(i);
                        String title = s.getString("title");
                        String description = s.getString("description");

                        HashMap<String,String> salesDetails = new HashMap<>();

                        //adding each child node to HashMap key =>value
                        salesDetails.put("title",title);
                        salesDetails.put("description",description);

                        //adding to array list
                        sales_details.add(salesDetails);
                    }
                    Log.d("TAG",sales_details.toString());
                }catch(final JSONException e){
                    Log.e(TAG, "JSON parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),"JSON parsing error: " + e.getMessage(),Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }else{
                Log.e(TAG,"Couldn't get json from server");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), "Check logcat", Toast.LENGTH_LONG ).show();
                    }
                });
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result){
            super.onPostExecute(result);
            if(pDialog.isShowing()){
                pDialog.dismiss();
            }

            //update parsed JSON data into ListView
            ListAdapter adapter = new SimpleAdapter(GetWarehouseSales.this, sales_details,R.layout.item_listview, new String[]{
                    "title","description"}, new int[]{R.id.text,R.id.description});

            lv.setAdapter(adapter);
        }
    }


}

MainActivity.java

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        GetWarehouseSales gws = new GetWarehouseSales();
        gws.executeGWS();

    }

错误:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference

错误指向这一行:

pDialog = new ProgressDialog(GetWarehouseSales.this);

我想执行 AsyncTask RetrieveWarehouseSalesTask,它可以在 GetWarehouseSales.java 中找到 MainActivity.java,但出现 NPE 错误。

【问题讨论】:

  • 我无法确定该代码有什么问题,但我认为您必须真正开始活动。否则它不会有上下文。堆栈跟踪或功能示例代码会很有帮助。

标签: java android android-asynctask


【解决方案1】:

尝试传递 MainActivity 上下文..

 @Override
protected void onCreate(Bundle savedInstanceState) {
    GetWarehouseSales gws = new GetWarehouseSales(MainActivity.this);
    gws.executeGWS();

}

检索上下文:

private Activity activityContext;


 public GetWarehouseSales(Activity context){
     this.activityContext=context;
}

现在使用该上下文初始化您的 ProgressDialog

 @Override
    protected void onPreExecute(){
        super.onPreExecute();
        pDialog = new ProgressDialog(activityContext);
        pDialog.setMessage("Getting you the best warehouse sales...");
        pDialog.setCancelable(false);
        pDialog.show();
    }

或..尝试使用

 pDialog = new ProgressDialog(getApplicationContext());

【讨论】:

  • 现在错误指向 pDialog.show()。报错信息是“MainActivity has leaked window DecorView@17887f5[] that original added here”
  • @kylas 尝试编辑....
  • 窗口泄漏异常是由于您的 mainactivity 在显示进度对话框时被破坏
【解决方案2】:

这是错误的原因:

    GetWarehouseSales gws = new GetWarehouseSales();
    gws.executeGWS();

您创建了一个活动实例,当AsyncTask 正在执行时,尝试访问Context

看起来最简单的解决方法是将RetrieveWarehouseSalesTask 放入MainActivity,类似于:

class MainActivity ... {
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...

        new RetrieveWarehouseSalesTask().execute();
    }

    public class RetrieveWarehouseSalesTask extends AsyncTask<Void,Void,Void>{
    ...
}

【讨论】:

    【解决方案3】:

    希望这会对你有所帮助..

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        GetWarehouseSales gws = new GetWarehouseSales(this);
        gws.executeGWS();
    
    }
    

    检索上下文:

    private Context activityContext;
    
     public GetWarehouseSales(Context context){
         this.activityContext=context;
    }
    

    现在使用该上下文初始化您的 ProgressDialog

    @Override
        protected void onPreExecute(){
            super.onPreExecute();
            pDialog = new ProgressDialog(activityContext);
            pDialog.setMessage("Getting you the best warehouse sales...");
            pDialog.setCancelable(false);
            pDialog.show();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-15
      • 2014-12-18
      • 2018-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多