如果响应是空数组,清除ListView?

时间:2016-06-09 12:18:27

标签: java android android-spinner

我有两个旋转器,第一个用于月份,第二个用于年份。我正在尝试调用方法send_date(),如果在2个微调器中的任何一个上调用了Item Selected。

  

所以我有两个问题: - 1)send_date()第一次被调用两次   时间它按预期获得正确的数据,但第二次返回   一个空数组。 2)当我选择旧数据时,我选择另一个月或一年   不被删除,即列表不刷新。

以下是我选择的项目代码: -

 public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
            {
                int i = spinYear.getSelectedItemPosition();
                selected_year = years.get(i);
                Log.d("Selection Year",selected_year);
                tv_year.setText(selected_year);

                try {
                    send_date();

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

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

对于月份微调器: -

 public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
            {

                int j = spinMonths.getSelectedItemPosition();
                selected_month = Months[j];
                Date date = null;
                try {
                    date = new SimpleDateFormat("MMMM").parse(selected_month);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                Calendar cal = Calendar.getInstance();
                cal.setTime(date);
                tv_month.setText(String.valueOf(cal.get(Calendar.MONTH)+1));

                Log.d("Selection Month",selected_month);
                try {
                    send_date();
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

在响应时,我调用以下方法用数据填充列表视图: -

public void showBS(String response)
{
    ParseBS_all pb = new ParseBS_all(response);
    pb.parseBS();

     bl = new BS_allList(getActivity(),ParseBS_all.doc_no,ParseBS_all.balance,ParseBS_all.total,ParseBS_all.vat,ParseBS_all.profit);
    lv_bsall.setAdapter(bl);

}

这是send_date方法的代码: -

    //This method is used to send month and year
    private void send_date() throws JSONException {

        final String year = tv_year.getText().toString();
        final String month = tv_month.getText().toString();


        StringRequest stringRequest = new StringRequest(Request.Method.POST, SEND_DATE,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        //display.setText("This is the Response : " + response);
                        String resp = response.toString().trim();

                        if (resp.equals("Nothing to display"))
                        {
                            Toast.makeText(getContext(), "Nothing to Display", Toast.LENGTH_SHORT).show();
//                            bl.clear();
                            lv_bsall.setAdapter(bl);
                            bl.notifyDataSetChanged();

                        }else
                        {
                            Toast.makeText(getContext(), "Response" + response, Toast.LENGTH_LONG).show();
                            Log.d("RESPONSE for date", response.toString().trim());
                            showBS(response);
                        }


                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                GlobalClass gvar = (GlobalClass) getActivity().getApplicationContext();
                String dbname = gvar.getDbname();
                Map<String, String> params = new HashMap<>();
                params.put(KEY_DBNAME, dbname);
                params.put(KEY_MONTH, month);
                params.put(KEY_YEAR,year);
                return params;
            }
        };

        RequestQueue requestQ = Volley.newRequestQueue(getContext());
        requestQ.add(stringRequest);
    }

列表视图的适配器代码。

public class BS_allList extends ArrayAdapter<String>
{

    private String[] doc_no;
    private String[] balance;
    private String[] total;
    private String[] vat;
    private String[] profit;
    private Activity context;

    public BS_allList(Activity context, String[] doc_no, String[]balance, String[] total, String[] vat, String[] profit)
    {
        super(context, R.layout.bs_list_all, doc_no);
        this.context =context;
        this.doc_no= doc_no;
        this.balance = balance;
        this.total = total;
        this.vat=vat;
        this.profit = profit;
    }



    @Override
    public View getView(int position, View listViewItem, ViewGroup parent)
    {
        if (null == listViewItem)
        {
            LayoutInflater inflater = context.getLayoutInflater();
            listViewItem = inflater.inflate(R.layout.bs_list_all, null, true);
        }
        TextView tv_docNo = (TextView) listViewItem.findViewById(R.id.tvdoc_no);
        TextView tv_balance = (TextView) listViewItem.findViewById(R.id.tv_balance);
        TextView tv_tot = (TextView) listViewItem.findViewById(R.id.tv_total);
        TextView tv_vat = (TextView) listViewItem.findViewById(R.id.tv_vat);
        TextView tv_pf = (TextView) listViewItem.findViewById(R.id.tv_profit);

        tv_docNo.setText(doc_no[position]);
        tv_balance.setText(balance[position]);
        tv_tot.setText(total[position]);
        tv_vat.setText(vat[position]);
        tv_pf.setText(profit[position]);

        return listViewItem;
    }
}

另请注意,我已将微调器设置为指向当前月份和年份,以便第一次正常工作。 我是编程新手,所以感谢任何帮助或建议。谢谢。

3 个答案:

答案 0 :(得分:1)

首先,您不应该使用这么多String[],而是将它们包装在一个类中

Class BSDataModel{
    private String doc_no;
    private String balance;
    private String total;
    private String vat;
    private String profit;
   //getters and setters
}

现在应该添加reponse结果,它会返回List<BSDataModel>

   List<BSDataModel> reponseList = new ArrayList<>();

    //for example adding single response
    for(int i=0;i<jsonArrayResponse.length();i++){
        BSDataModel singleResponse = new BSDataModel();
        singleResponse.setDocNo(jsonArrayResponse.get(i).getString("doc_no"));
        singleResponse.setBalace(jsonArrayResponse.get(i).getString("balance")); 
        //etc..finall add that single response to responseList
        reponseList.add(singleResponse);
    }

<强> BS_allList.java

public class BS_allList extends ArrayAdapter<BSDataModel>
{

    private List<BSDataModel> bsList;
    private Activity context;

    public BS_allList(Activity context,List<BSDataModel> bsList)
    {
        super(context, R.layout.bs_list_all, bsList);
        this.context =context;
        this.bsList = bsList;
    }


    @Override
    public View getView(int position, View listViewItem, ViewGroup parent)
    {
        if (null == listViewItem)
        {
            LayoutInflater inflater = context.getLayoutInflater();
            listViewItem = inflater.inflate(R.layout.bs_list_all, null, true);
        }
        TextView tv_docNo = (TextView) listViewItem.findViewById(R.id.tvdoc_no);
        TextView tv_balance = (TextView) listViewItem.findViewById(R.id.tv_balance);
        TextView tv_tot = (TextView) listViewItem.findViewById(R.id.tv_total);
        TextView tv_vat = (TextView) listViewItem.findViewById(R.id.tv_vat);
        TextView tv_pf = (TextView) listViewItem.findViewById(R.id.tv_profit);
        BSDataModel bsData = bsList.get(position);
        tv_docNo.setText(bsData.getDoc());
        tv_balance.setText(bsData.getBalance());
        tv_tot.setText(bsData.getTot());
        tv_vat.setText(bsData.getVat());
        tv_pf.setText(bsData.getPF());

        return listViewItem;
    }
}

现在在你的班级

BS_allList bl = new BS_allList(getActivity(),responseList);//which you got above

收到新回复后

      // remove old data

        responseList.clear(); // list items in the sense list of array used to populate listview

           if(newresponseArray.size() > 0){
             for(int i=0;i<newjsonArrayResponse.length();i++){
                BSDataModel singleResponse = new BSDataModel();
                singleResponse.setDocNo(newjsonArrayResponse.get(i).getString("doc_no"));
                singleResponse.setBalace(newjsonArrayResponse.get(i).getString("balance")); 
                //etc..finall add that single response to responseList
                reponseList.add(singleResponse);
            }
           }

        //refresh listview
        bl.notifyDataSetChanged();

答案 1 :(得分:1)

你好@AndroidNewBee,

根据我们在您的代码更改后进行的讨论,您将获得正确的输出,它将解决您的问题。

  if (resp.equals("Nothing to display"))
  {
      Toast.makeText(getContext(), "Nothing to Display", Toast.LENGTH_SHORT).show();
      bl = new BS_allList(getActivity(),{""},{""},{""},{""},{""});
      lv_bsall.setAdapter(bl);
  }

第二个是检查验证,如下所示,

  try {
         if((selected_year != null & selected_year.length > 0 ) & (tv_month.getText().toString() != null & tv_month.getText().toString().length > 0))
         {
            send_date();
         }

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

答案 2 :(得分:0)

试试这种方式,

1. adapter.clear();
2. Add/Remove your list Items.
3. listview.setAdapter(adapter);
4. adapter.notifyDatasetChanged();

此程序应该有效。