如何在onPostExecute Asynctask中设置列表适配器?

时间:2017-03-06 04:52:19

标签: android listview android-asynctask

大家好日子,

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

我想设置列表适配器,但是我收到了错误

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

现在如何在后执行中设置列表适配器?

我的代码

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

}

4 个答案:

答案 0 :(得分: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();

答案 1 :(得分:1)

将mItems初始化为

mItems = new ArrayList<>();

为ListProfileAdapter创建对象

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

在mItems中添加项目

mItems.add(item);

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

adapter.notifyDataSetChanged(); 

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

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

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

制作实例变量

ListProfileAdapter adapter;

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

adapter.notifyDatasetChanged();