根据android中的微调器选择在listview中填充不同的数据

时间:2016-02-09 10:07:51

标签: android listview android-adapter

我有一个微调器,我想根据微调器选择用数据填充自定义列表视图。数据来自mysql数据库。目前我能够从不同的微调器选择中获取数据,但问题是当我尝试在listview中添加数据时,它不会从listview中删除以前的数据。

我试过了listAdapter.notifyDataSetChanged(),但这对我没用。甚至我为不同的微调器选择创建了2个适配器,并尝试根据微调器选择将它们添加到列表中,但这给了我空白列表。

我为我的问题看到了多种解决方案,但对我来说没有任何效果。 所以请根据微调器选择给我一些合适的想法,将不同的数据添加到listview。

提前致谢

这是我的适配器类

公共类ListAdapter扩展了ArrayAdapter {

//static String get_empcode,get_empname,get_app_date,get_nod,get_from,get_to,get_lv_type,get_reason,get_remark,get_status;
static List list=new ArrayList();
static String[]  get_empcode,get_empname,get_app_date,get_nod,get_from,get_to,get_lv_type,get_reason,get_remark,get_status;
static ArrayList<String> empcode = new ArrayList<String>();
static ArrayList<String> from = new ArrayList<String>();
static ArrayList<String> to = new ArrayList<String>();
static ArrayList<String> lv_type = new ArrayList<String>();
static ArrayList<String> nod = new ArrayList<String>();

static int count=0;



int i;
static int arr_length;

public ListAdapter(Context context, int resource) {
    super(context, resource);

}

public void add(Details object) {

    super.add(object);
    list.add(object);
}

@Override
public void registerDataSetObserver(DataSetObserver observer) {
    super.registerDataSetObserver(observer);
}

@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
    super.unregisterDataSetObserver(observer);
}

public int getCount() {

    return list.size();
}


@Override
public Details getItem(int position) {

    return (Details) list.get(position);
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {

     View row;
    row=convertView;
    final DetailsHolder detailsHolder;

    if(row==null)
    {
        LayoutInflater layoutInflater=(LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row=layoutInflater.inflate(R.layout.list_layout_approval, parent, false);
        detailsHolder=new DetailsHolder();
        detailsHolder.empcode=(TextView) row.findViewById(R.id.empcode1);
        detailsHolder.empname=(TextView) row.findViewById(R.id.empname1);
        detailsHolder.appdate=(TextView) row.findViewById(R.id.appdate1);
        detailsHolder.lv_type=(TextView) row.findViewById(R.id.lv_type1);
        detailsHolder.from=(TextView) row.findViewById(R.id.from1);
        detailsHolder.to=(TextView) row.findViewById(R.id.to1);
        detailsHolder.nod=(TextView) row.findViewById(R.id.nod1);
        detailsHolder.reason=(TextView) row.findViewById(R.id.reason1);
        detailsHolder.status=(TextView) row.findViewById(R.id.status1);
        DetailsHolder.cb2=(CheckBox) row.findViewById(R.id.cb2);





       DetailsHolder.cb2.setOnCheckedChangeListener(new OnCheckedChangeListener() {

          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if(isChecked)
                    {

                        count=count+1;
                        empcode.add((String) detailsHolder.empcode.getText());
                        from.add((String) detailsHolder.from.getText());
                        to.add((String) detailsHolder.to.getText());
                        lv_type.add((String) detailsHolder.lv_type.getText());
                        nod.add((String) detailsHolder.nod.getText());




                    }

                else{
                    count=count-1;
                    empcode.remove(position);
                    from.remove(position);
                    to.remove(position);
                    lv_type.remove(position);
                    nod.remove(position);



                }

                arr_length=empcode.size()+from.size()+to.size()+lv_type.size()+nod.size();

            }


        });







        row.setTag(detailsHolder);





    }
    else{

        detailsHolder=(DetailsHolder) row.getTag();

    }







    Details details=(Details)this.getItem(position);
    detailsHolder.empcode.setText(details.getEmpcode());
    detailsHolder.empname.setText(details.getEmpname());
    detailsHolder.appdate.setText(details.getApplyDate());
    detailsHolder.lv_type.setText(details.getLeave_type());
    detailsHolder.from.setText(details.getFrom());
    detailsHolder.to.setText(details.getTo());
    detailsHolder.nod.setText(details.getNod());
    detailsHolder.reason.setText(details.getReason());
    detailsHolder.status.setText(details.getStatus());

    return row;
}





static class DetailsHolder
{
    TextView empcode,empname,appdate,lv_type,from,to,nod,reason,status;
    EditText remark;
    static CheckBox cb2;




}

}

下面是详细信息类: -

公共类详情{

private String empcode,empname,applyDate,leave_type,from,to,nod,reason,remark,status;


public Details(String empcode,String empname,String applyDate,String leave_type,String from,
        String to,String nod,String reason,String status){

    this.setEmpcode(empcode);
    this.setEmpname(empname);
    this.setApplyDate(applyDate);
    this.setLeave_type(leave_type);
    this.setFrom(from);
    this.setTo(to);
    this.setNod(nod);
    this.setReason(reason);
    this.setStatus(status);



}


public String getEmpcode() {
    return empcode;
}

public void setEmpcode(String empcode) {
    this.empcode = empcode;
}

public String getEmpname() {
    return empname;
}

public void setEmpname(String empname) {
    this.empname = empname;
}

public String getApplyDate() {
    return applyDate;
}

public void setApplyDate(String applyDate) {
    this.applyDate = applyDate;
}

public String getLeave_type() {
    return leave_type;
}

public void setLeave_type(String leave_type) {
    this.leave_type = leave_type;
}

public String getFrom() {
    return from;
}

public void setFrom(String from) {
    this.from = from;
}

public String getTo() {
    return to;
}

public void setTo(String to) {
    this.to = to;
}

public String getNod() {
    return nod;
}

public void setNod(String nod) {
    this.nod = nod;
}

public String getReason() {
    return reason;
}

public void setReason(String reason) {
    this.reason = reason;
}


public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

}

在mainActivity中,我传递的数据如下:

公共类Leave_approval扩展了Activity {

String JSON_STRING,php_result,LeaveType,empcode,FullName,ApplyDate,From,To,NOD,Reason,Status,bundle_id,approve_bkg_result;
String from_date,to_date,appdate;

String LeaveType1,empcode1,FullName1,ApplyDate1,From1,To1,NOD1,Reason1,Status1,bundle_id1,from_date1,to_date1,appdate1;
String[] status_data;
String[] empcode_val,lv_type_val,nod_value,status_val,from_value,to_value;
JSONObject jsonObject;
JSONArray jsonArray;
String[] date_list;
Details details;
TextView head;
ListAdapter listAdapter;
Approve_List_adapter approve_adapter;
ListView listView;
CheckBox cb1;
static Boolean cb_status;
int i;
Spinner status;




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.leave_approval);
    listView=(ListView) findViewById(R.id.list);
    cb1=(CheckBox) findViewById(R.id.cb1);
    status=(Spinner) findViewById(R.id.status);


    listAdapter=new ListAdapter(this, R.layout.list_layout_approval);
  // approve_adapter=new Approve_List_adapter(this, R.layout.approve_list_adapter);
    listView.setAdapter(listAdapter);
    //listView.setAdapter(approve_adapter);

    head=(TextView) findViewById(R.id.head);
     Bundle b = getIntent().getExtras();

     php_result=b.getString("json_data");
     bundle_id = b.getString("string");

    status_data=getResources().getStringArray(R.array.status);
    ArrayAdapter<String> adapter=new ArrayAdapter<>(this, android.R.layout.simple_spinner_item,status_data);
    status.setAdapter(adapter);

    status.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
        {
            String status_changed=arg0.getItemAtPosition(arg2).toString();
            if(status_changed.equals("Approved"))
            {


                LeaveApprovedStatus bkg=new  LeaveApprovedStatus(getApplicationContext());
                bkg.execute(bundle_id);


            }

            else{

                //Toast.makeText(getApplicationContext(), status_changed, Toast.LENGTH_SHORT).show();


                 try {
                        jsonObject=new JSONObject(php_result);
                        jsonArray=jsonObject.getJSONArray("server_response");

                        for(int i=0;i<jsonArray.length();i++){
                            JSONObject c = jsonArray.getJSONObject(i);
                            LeaveType=c.getString("LeaveType");
                            empcode=c.getString("empcode");
                            FullName=c.getString("FullName");
                            ApplyDate=c.getString("ApplyDate");
                            From=c.getString("From");
                            To=c.getString("To");
                            NOD=c.getString("NOD");
                            Reason=c.getString("Reason");
                            Status=c.getString("Status");

                            String[] from_array=From.split("-");
                            String[] to_array=To.split("-");
                            String[] apply_array=ApplyDate.split("-");
                            String from_date,to_date,appdate;


                            if(from_array[1].equals("01"))
                                from_array[1]="jan";

                            if(from_array[1].equals("02"))
                                from_array[1]="Feb";

                            if(from_array[1].equals("03"))
                                from_array[1]="Mar";

                            if(from_array[1].equals("04"))
                                from_array[1]="Apr";

                            if(from_array[1].equals("05"))
                                from_array[1]="May";

                            if(from_array[1].equals("06"))
                                from_array[1]="Jun";

                            if(from_array[1].equals("07"))
                                from_array[1]="Jul";

                            if(from_array[1].equals("08"))
                                from_array[1]="Aug";

                            if(from_array[1].equals("09"))
                                from_array[1]="Sep";

                            if(from_array[1].equals("10"))
                                from_array[1]="Oct";

                            if(from_array[1].equals("11"))
                                from_array[1]="Nov";


                            if(from_array[1].equals("12"))
                                from_array[1]="Dec";



                            if(to_array[1].equals("01"))
                                to_array[1]="jan";

                            if(to_array[1].equals("02"))
                                from_array[1]="Feb";

                            if(to_array[1].equals("03"))
                                to_array[1]="Mar";

                            if(to_array[1].equals("04"))
                                to_array[1]="Apr";

                            if(to_array[1].equals("05"))
                                to_array[1]="May";

                            if(to_array[1].equals("06"))
                                to_array[1]="Jun";

                            if(to_array[1].equals("07"))
                                to_array[1]="Jul";

                            if(to_array[1].equals("08"))
                                to_array[1]="Aug";

                            if(to_array[1].equals("09"))
                                to_array[1]="Sep";

                            if(to_array[1].equals("10"))
                                to_array[1]="Oct";

                            if(to_array[1].equals("11"))
                                to_array[1]="Nov";


                            if(to_array[1].equals("12"))
                                to_array[1]="Dec";




                            if(apply_array[1].equals("01"))
                                apply_array[1]="jan";

                            if(apply_array[1].equals("02"))
                                apply_array[1]="Feb";

                            if(apply_array[1].equals("03"))
                                apply_array[1]="Mar";

                            if(apply_array[1].equals("04"))
                                apply_array[1]="Apr";

                            if(apply_array[1].equals("05"))
                                apply_array[1]="May";

                            if(apply_array[1].equals("06"))
                                apply_array[1]="Jun";

                            if(apply_array[1].equals("07"))
                                apply_array[1]="Jul";

                            if(apply_array[1].equals("08"))
                                apply_array[1]="Aug";

                            if(apply_array[1].equals("09"))
                                apply_array[1]="Sep";

                            if(apply_array[1].equals("10"))
                                apply_array[1]="Oct";

                            if(apply_array[1].equals("11"))
                                apply_array[1]="Nov";


                            if(apply_array[1].equals("12"))
                                apply_array[1]="Dec";

                            from_date=from_array[2]+"-"+from_array[1]+"-"+from_array[0];
                            to_date=to_array[2]+"-"+to_array[1]+"-"+to_array[0];
                            appdate=apply_array[2]+"-"+apply_array[1]+"-"+apply_array[0];



                            details=new Details(empcode,FullName,appdate,LeaveType,from_date,to_date,NOD,Reason,Status);

                            listAdapter.add(details);

                            //listView.invalidate();



                          }




                       } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }






            }


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


    });

}

public void approve(View view){

    //Toast.makeText(getApplicationContext(), String.valueOf(ListAdapter.count), Toast.LENGTH_SHORT).show();

    ArrayList<String> emplist=new ArrayList<>();
    ArrayList<String> fromlist=new ArrayList<>();
    ArrayList<String> tolist=new ArrayList<>();
    ArrayList<String> lv_typelist=new ArrayList<>();
    ArrayList<String> nodlist=new ArrayList<>();
    ArrayList<String> status=new ArrayList<>();


    emplist=ListAdapter.getemplist();
    fromlist=ListAdapter.getfromlist();
    tolist=ListAdapter.gettolist();
    lv_typelist=ListAdapter.getlv_typelist();
    nodlist=ListAdapter.getnodlist();
    status.add("Approved");


    JSONArray jArr1= new JSONArray();
    for(String data:emplist)
     {
       jArr1.put(data);
     }


    JSONArray jArr2= new JSONArray();
    for(String data:fromlist)
     {
       jArr2.put(data);
     }

    JSONArray jArr3= new JSONArray();
    for(String data:tolist)
     {
       jArr3.put(data);
     }

    JSONArray jArr4= new JSONArray();
    for(String data:lv_typelist)
     {
       jArr4.put(data);
     }

    JSONArray jArr5= new JSONArray();
    for(String data:status)
     {
       jArr5.put(data);
     }

    JSONArray jArraySet = new JSONArray();
      jArraySet.put(jArr1);
      jArraySet.put(jArr2);
      jArraySet.put(jArr3);
      jArraySet.put(jArr4);
      jArraySet.put(jArr5);

      String json_string=String.valueOf(jArraySet);
    // Toast.makeText(getApplicationContext(), json_string, Toast.LENGTH_LONG).show();

    BackgroundTask backgroundTask = new BackgroundTask(getApplicationContext());
    backgroundTask.execute(json_string);



}


@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
        listView.onWindowFocusChanged(true);
        listView.invalidate();
        listView.invalidateViews();
    }
}


public void reject(View view){


    ArrayList<String> emplist=new ArrayList<>();
    ArrayList<String> fromlist=new ArrayList<>();
    ArrayList<String> tolist=new ArrayList<>();
    ArrayList<String> lv_typelist=new ArrayList<>();
    ArrayList<String> nodlist=new ArrayList<>();
    ArrayList<String> status=new ArrayList<>();


    emplist=ListAdapter.getemplist();
    fromlist=ListAdapter.getfromlist();
    tolist=ListAdapter.gettolist();
    lv_typelist=ListAdapter.getlv_typelist();
    nodlist=ListAdapter.getnodlist();
    status.add("Rejected");


    JSONArray jArr1= new JSONArray();
    for(String data:emplist)
     {
       jArr1.put(data);
     }


    JSONArray jArr2= new JSONArray();
    for(String data:fromlist)
     {
       jArr2.put(data);
     }

    JSONArray jArr3= new JSONArray();
    for(String data:tolist)
     {
       jArr3.put(data);
     }

    JSONArray jArr4= new JSONArray();
    for(String data:lv_typelist)
     {
       jArr4.put(data);
     }

    JSONArray jArr5= new JSONArray();
    for(String data:status)
     {
       jArr5.put(data);
     }

    JSONArray jArraySet = new JSONArray();
      jArraySet.put(jArr1);
      jArraySet.put(jArr2);
      jArraySet.put(jArr3);
      jArraySet.put(jArr4);
      jArraySet.put(jArr5);

      String json_string=String.valueOf(jArraySet);
     //Toast.makeText(getApplicationContext(), json_string, Toast.LENGTH_LONG).show();

    BackgroundTask backgroundTask = new BackgroundTask(getApplicationContext());
    backgroundTask.execute(json_string);




    }




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

     AsyncResponse delegate = null;

     Context ctx;  
       BackgroundTask(Context ctx)  
       {  
        this.ctx =ctx;  
       }


       @Override  
       protected void onPreExecute() {  

       }  

       protected String doInBackground(String... params) {  



               String login_url = "http://10.0.2.2/neha/leave_approval_json.php";
               String json_data = params[0];

                   try {  
                     URL url = new URL(login_url);  
                     HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();  
                     httpURLConnection.setRequestMethod("POST");  
                     httpURLConnection.setDoOutput(true);  
                     httpURLConnection.setDoInput(true);  
                     OutputStream outputStream = httpURLConnection.getOutputStream();  
                     BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));  
                     String data = URLEncoder.encode("json_data","UTF-8")+"="+URLEncoder.encode(json_data,"UTF-8");          

                     bufferedWriter.write(data);  
                     bufferedWriter.flush();  
                     bufferedWriter.close();  
                     outputStream.close();  
                     InputStream inputStream = httpURLConnection.getInputStream();  
                     BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));  
                     String response = "";  
                     String line = "";  
                     while ((line = bufferedReader.readLine())!=null)  
                     {  
                       response+= line;  
                     }  
                     bufferedReader.close();  
                     inputStream.close();  
                     httpURLConnection.disconnect();  
                     return response;  
                   } catch (MalformedURLException e) {  
                     e.printStackTrace();  
                   } catch (IOException e) {  
                     e.printStackTrace();  
                   }  
                // }  
                 return null;  
               }  
               @Override  
               protected void onProgressUpdate(Void... values) {  
                 super.onProgressUpdate(values);  
               }  
               @Override  
               protected void onPostExecute(String result) { 


                     Toast.makeText(ctx, result, Toast.LENGTH_SHORT).show();




                }  







}




class LeaveApprovedStatus extends AsyncTask<String, Void, String>
{

    String json_url;


    Context ctx;  

    LeaveApprovedStatus(Context ctx)  
       {  
        this.ctx =ctx;  
       }

    @Override
    protected void onPreExecute() {


    }




    @Override
    protected String doInBackground(String... params) {


        json_url = "http://10.0.2.2/neha/leave_approval_approvedStatus.php";


        final String empcode = params[0];  

           try {  
             URL url = new URL(json_url);  
             HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();  
             httpURLConnection.setRequestMethod("POST");  
             httpURLConnection.setDoOutput(true);  
             httpURLConnection.setDoInput(true);  
             OutputStream outputStream = httpURLConnection.getOutputStream();  
             BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));  
           String data = URLEncoder.encode("empcode","UTF-8")+"="+URLEncoder.encode(empcode,"UTF-8");  
             bufferedWriter.write(data);  
             bufferedWriter.flush();  
             bufferedWriter.close();  
             outputStream.close(); 

             InputStream inputStream = httpURLConnection.getInputStream();  
             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1")); 

             StringBuilder stringBuilder1=new StringBuilder();
             while((JSON_STRING=bufferedReader.readLine())!=null)
             {

                 stringBuilder1.append(JSON_STRING+"\n");




             }

             bufferedReader.close();
             inputStream.close();
             httpURLConnection.disconnect();
             return stringBuilder1.toString().trim();




        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;








    }

    @Override
    protected void onProgressUpdate(Void... values) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {


        approve_bkg_result=result;





                Details details1=new Details (empcode1,FullName1,appdate1,LeaveType1,from_date1,to_date1,NOD1,Reason1,Status1);
                listAdapter.add(details1);
                listAdapter.notifyDataSetChanged();
                listView.invalidate();






              }




           } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }










    }

}

}

2 个答案:

答案 0 :(得分:1)

假设您将数据存储在ArrayList中:

private ArrayList<VideoPreview> dataList = new ArrayList<>();

您可以在微调器onItemSelectedListener中填充它:

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position != currentPosition) {
                    dataList.clear();
                    dataList = myData[position];
                    dataListView.getAdapter().notifyOnDataSetChanged();
                }
            }

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

            }
        });

在不了解您的问题和代码的任何其他内容的情况下,我无法为您提供更具体的解决方案。

您对适配器的声明应该类似于:

    final DataAdapter adapter = new DataAdapter(getContext(), dataList);
    dataListView.setAdapter(adapter);

答案 1 :(得分:0)

如果您传递的数据对象是ArrayList<MyObject>

只需使自定义适配器扩展ArrayAdapter<MyObject>而不是BaseAdapter。实现所需的方法(保留默认值),你应该没问题。