【问题标题】:How to set List Adapter in onPostExecute Asynctask?如何在 onPostExecute Asynctask 中设置列​​表适配器?
【发布时间】:2017-03-06 04:52:19
【问题描述】:

大家好,

我这里有一些问题。我在 AsyncTask DoInBackground 中进行了 Web 服务调用。

我想设置列表适配器,但出现错误

java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference

现在如何在 post execute 中设置列​​表适配器?

我的代码

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);
    progressBar = (ProgressBar)findViewById(R.id.prgLoading);


     //Initialize the ListView
    final ListView lvProf = (ListView)findViewById(R.id.lvProfile);

    //call the asynctask cals and add item to the list.
    new LoadDataForActivity().execute();

   //Set adapter , but i got error here
    lvProf.setAdapter(new ListProfileAdapter(this,mItems));



}

private class LoadDataForActivity extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        progressBar.setVisibility(View.VISIBLE);
        progressBar.setIndeterminate(false);
        progressBar.setClickable(false);
    }
    @Override
    protected Void doInBackground(Void... params) {

        getAll();
        getTotalLeaveBalance();
        getMedicalBalance();
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
    //here is I add the item to my list (mitems)
        try{
            ResponseServiceMedicalBalance = ResponseServiceMedicalBalance.replace("\\\"", "\"");
            ResponseServiceMedicalBalance = ResponseServiceMedicalBalance.substring(1, ResponseServiceMedicalBalance.length() - 1);

            JSONParser jsonParser = new JSONParser();
            JSONObject jsonObject = (JSONObject) jsonParser.parse(ResponseServiceMedicalBalance);
            String Status = jsonObject.get("Status").toString();

            if (Status == "true") {
                // JSONArray structure = (JSONArray) jsonObject.get("DataList");
                String dataku = jsonObject.get("DataList").toString();
                mItems = new ArrayList<ListProfileItem>();
                try {
                    dataku = ANGGACRYYPT.decrypt(Enc_Pass, dataku);
                }catch (GeneralSecurityException e){
                    //handle error - could be due to incorrect password or tampered encryptedMsg
                }

                JSONParser parser = new JSONParser();
                JSONArray structure = (JSONArray) parser.parse(dataku);
                for (int i = 0; i < structure.size(); i++) {
                    JSONObject data = (JSONObject) structure.get(i);
                    item = new ListProfileItem();
                    item.claimpostname = data.get("claim_post_name").toString();
                    String claimamount = data.get("max_limit_per_year").toString();
                    if (claimamount!=("0.0"))
                    {
                        Double amount = Double.parseDouble(claimamount);
                        DecimalFormat formatter = new DecimalFormat("#,###.00");
                        String AmountFormatted = formatter.format(amount);
                        item.claimpostamount = AmountFormatted;
                    }
                    else
                    {
                        item.claimpostamount = data.get("max_limit_per_year").toString();
                    }
                    mItems.add(item);
                }
                // initialize and set the list adapter

            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

}

【问题讨论】:

  • 检查mItemsList解析后是否有值,否则初始化mItems = new ArrayList&lt;&gt;();

标签: android listview android-asynctask


【解决方案1】:

有几种方法可以解决这个问题,其中一种快速且最肮脏的方法是:

像这样改变你的 AsyncTaskActivity:

private class LoadDataForActivity extends AsyncTask<Void, Void, Void> {


  private ListView listView;

  private Context context;

  public LoadDataForActivity(ListView listView,Context context){
    this. listView = listView;
    this.context = context;
  }

    @Override
    protected void onPreExecute() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        progressBar.setVisibility(View.VISIBLE);
        progressBar.setIndeterminate(false);
        progressBar.setClickable(false);
    }
    @Override
    protected Void doInBackground(Void... params) {

        getAll();
        getTotalLeaveBalance();
        getMedicalBalance();
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
    //here is I add the item to my list (mitems)
        try{
            ResponseServiceMedicalBalance = ResponseServiceMedicalBalance.replace("\\\"", "\"");
            ResponseServiceMedicalBalance = ResponseServiceMedicalBalance.substring(1, ResponseServiceMedicalBalance.length() - 1);

            JSONParser jsonParser = new JSONParser();
            JSONObject jsonObject = (JSONObject) jsonParser.parse(ResponseServiceMedicalBalance);
            String Status = jsonObject.get("Status").toString();

            if (Status == "true") {
                // JSONArray structure = (JSONArray) jsonObject.get("DataList");
                String dataku = jsonObject.get("DataList").toString();
                mItems = new ArrayList<ListProfileItem>();
                try {
                    dataku = ANGGACRYYPT.decrypt(Enc_Pass, dataku);
                }catch (GeneralSecurityException e){
                    //handle error - could be due to incorrect password or tampered encryptedMsg
                }

                JSONParser parser = new JSONParser();
                JSONArray structure = (JSONArray) parser.parse(dataku);
                for (int i = 0; i < structure.size(); i++) {
                    JSONObject data = (JSONObject) structure.get(i);
                    item = new ListProfileItem();
                    item.claimpostname = data.get("claim_post_name").toString();
                    String claimamount = data.get("max_limit_per_year").toString();
                    if (claimamount!=("0.0"))
                    {
                        Double amount = Double.parseDouble(claimamount);
                        DecimalFormat formatter = new DecimalFormat("#,###.00");
                        String AmountFormatted = formatter.format(amount);
                        item.claimpostamount = AmountFormatted;
                    }
                    else
                    {
                        item.claimpostamount = data.get("max_limit_per_year").toString();
                    }
                    mItems.add(item);
                }

    listView.setAdapter(new ListProfileAdapter(context,mItems));


            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
  }

你可以像这样调用 asyncTask:

new LoadDataForActivity(listView,this).execute();

【讨论】:

    【解决方案2】:

    将 mItems 初始化为

    mItems = new ArrayList<>();
    

    为 ListProfileAdapter 创建对象

    ListProfileAdapter adapter =  new ListProfileAdapter(this,mItems);
    lvProf.setAdapter(adapter);
    

    在 mItems 中添加项目

    mItems.add(item);
    

    在所有添加到列表的项目后通知适配器

    adapter.notifyDataSetChanged(); 
    

    【讨论】:

    • mItems = new ArrayList&lt;&gt;();这行是错误的原因..他需要在onCreate方法中添加这行
    【解决方案3】:

    将它从 onCreate 移到 onPostExecute() 将 Adapter 的实例定义为全局变量,然后在 doInBackground() 中添加 Items 并调用 setAdapter onPostExec。

     //Set adapter , but i got error here >> move it to onPostExecute
        lvProf.setAdapter(new ListProfileAdapter(this,mItems));
    

    【讨论】:

      【解决方案4】:

      我认为以下行应该在设置您的适配器之前,

      mItems = new ArrayList<ListProfileItem>();
      adapter = new ListProfileAdapter(this,mItems)
      lvProf.setAdapter(adapter);
      

      使实例变量,

      ListProfileAdapter adapter;
      

      而不是放入 Asynctask。完成 onPostExecute 中的 asynctask 后还需要运行,

      adapter.notifyDatasetChanged();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多