Search code examples
androidandroid-listviewrefreshdynamic-list

How to keep old items in listview after refreshing it dynamically?


I have listview whose child items are coming from server. I have managed to get 10 list items after each smooth scroll but my problem is after adding new items, previous data gets cleared. I want old child items as well. I have used MyListAdapter().notifyDataSetChanged(); as well but not getting desired result. Guys please help me. Thank you in advance. Here is my code snippet:

Get_list.java:

private class getbride extends AsyncTask<String, String, String>{
    ProgressDialog pDialog;
     @Override
     protected void onPreExecute(){
        pDialog = new ProgressDialog(User_list.this);
        pDialog.setMessage("Loading...");
        pDialog.show();
     }                      
    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub

        try{
            String link = "http://Webservice.php";          

            HttpClient client = new DefaultHttpClient();
            HttpPost request = new HttpPost();
            request.setURI(new URI(link));

            List<NameValuePair> postParameters = new ArrayList<NameValuePair>();

            String lazy=String.valueOf(lcnt);
            postParameters.add(new BasicNameValuePair("lazy_cnt", lazy));

            UrlEncodedFormEntity form = new UrlEncodedFormEntity(postParameters);
            request.setEntity(form);

            HttpResponse response = client.execute(request); 
            HttpEntity entity = response.getEntity();

            result=EntityUtils.toString(entity);
            result1 = result;
            System.out.println("Result: "+result);

            SharedPreferences pref1 = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
            Editor ed = pref1.edit();
            ed.putString("search_res", result);
            ed.commit();

        }catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;            
    }
     @Override
        protected void onPostExecute(String result) {
         pDialog.dismiss();
        lv=(ListView)findViewById(R.id.listreq15);  

        try {     
              if(User_list.result!=null){
                jArray=new JSONArray(User_list.result);  

                prgmNameList =new ArrayList<String>();
                prgmImages=new ArrayList<String>();
                if(jArray.length()>0)
                {
                    for(int j=0;j<jArray.length();j++){
                        prgmNameList.add(new JSONObject(jArray.getString(j)).get("name")+"");   
                        prgmImages.add(new JSONObject(jArray.getString(j)).get("education")+"");
                       }        
                    System.out.println("#########"+prgmNameList);
        CustomAdapter cadapt = new CustomAdapter(c, prgmNameList, prgmImages);

                    flag_loading=false; 

                    lv.setAdapter(cadapt);
                    lv.invalidateViews();
                    cadapt.notifyDataSetChanged();

                    int count=lv.getAdapter().getCount();
                    String cnt_bride=String.valueOf(count);
                    TextView list_cnt=(TextView)findViewById(R.id.cnt);
                    list_cnt.setText(cnt_bride);

                    lv.setOnScrollListener(new OnScrollListener() {
                        @Override
                        public void onScroll(AbsListView view, int firstVisibleItem,
                                int visibleItemCount, int totalItemCount) {
                            // TODO Auto-generated method stub
                            if(firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0)
                            {
                                if(flag_loading == false)
                                {
                                    flag_loading = true;
                                    new getbride().execute("param1","param2","param3");
                                    lcnt++;

                                    int count=lv.getAdapter().getCount();
                                    String cnt_bride=String.valueOf(count);
                                    TextView list_cnt=(TextView)findViewById(R.id.cnt);
                                    list_cnt.setText(cnt_bride);
                                }
                            }                               
                        }
                        @Override
                        public void onScrollStateChanged(AbsListView arg0,
                                int arg1) {
                            // TODO Auto-generated method stub

                        }
                    });
                }
              }else{
                  Toast.makeText(getApplicationContext(),"No internet connection...", Toast.LENGTH_SHORT).show();
              }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
}

Activity.java:

public class User_list extends Activity {
ListView lv;
JSONArray jArray;
Context c;
public static int cnt,lcnt;
public static String result,result1,partial,u_id,result2,edu,f_name;
int age,ht;
boolean flag_loading;
public static List<String> prgmImages;
public static List<String> prgmNameList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user_list);

    Intent i = getIntent();
    String call=i.getStringExtra("call_for");
    if(call==null){
        try {
            search();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    else if(call.equalsIgnoreCase("br")){
    new getbride().execute("param1","param2","param3");
    lcnt=0;
    }

    else{
        new getgroom().execute("param1","param2","param3");
        lcnt=0;
    }
    c=this;  }

Solution

  • Declare and set the CustomAdapter, and initialize the ArrayLists in the Activity:

    public class User_list extends Activity {
    ListView lv;
    JSONArray jArray;
    Context c;
    public static int cnt,lcnt;
    public static String result,result1,partial,u_id,result2,edu,f_name;
    int age,ht;
    boolean flag_loading;
    public static List<String> prgmImages;
    public static List<String> prgmNameList;
    CustomAdapter cadapt; //Added declaration here
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_list);
    
    
         lv=(ListView)findViewById(R.id.listreq15); //added
         prgmNameList =new ArrayList<String>(); //added
         prgmImages=new ArrayList<String>(); //added
         cadapt = new CustomAdapter(c, prgmNameList, prgmImages); //initialize this here
         lv.setAdapter(cadapt); //added
    
    
        Intent i = getIntent();
        String call=i.getStringExtra("call_for");
        if(call==null){
            try {
                search();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        else if(call.equalsIgnoreCase("br")){
        new getbride().execute("param1","param2","param3");
        lcnt=0;
        }
    
        else{
            new getgroom().execute("param1","param2","param3");
            lcnt=0;
        }
        c=this;
    }
    

    Then in your AsyncTask just call notifyDataSetChanged() once new values have been added to the data set:

           @Override
            protected void onPostExecute(String result) {
             pDialog.dismiss();
            //lv=(ListView)findViewById(R.id.listreq15);  //remove
    
            try {     
                  if(User_list.result!=null){
                    jArray=new JSONArray(User_list.result);  
    
                    //prgmNameList =new ArrayList<String>(); //remove
                    //prgmImages=new ArrayList<String>(); //remove
                    if(jArray.length()>0)
                    {
                        for(int j=0;j<jArray.length();j++){
                            prgmNameList.add(new JSONObject(jArray.getString(j)).get("name")+"");   
                            prgmImages.add(new JSONObject(jArray.getString(j)).get("education")+"");
                           }        
                        System.out.println("#########"+prgmNameList);
                       //CustomAdapter cadapt = new CustomAdapter(c, prgmNameList, prgmImages); //remove
    
                        flag_loading=false; 
    
                        //lv.setAdapter(cadapt); //remove
                        //lv.invalidateViews(); //don't think this is needed
                        cadapt.notifyDataSetChanged(); //This is needed!
    
                        int count=lv.getAdapter().getCount();
                        String cnt_bride=String.valueOf(count);
                        TextView list_cnt=(TextView)findViewById(R.id.cnt);
                        list_cnt.setText(cnt_bride);
    
                        lv.setOnScrollListener(new OnScrollListener() {
                            @Override
                            public void onScroll(AbsListView view, int firstVisibleItem,
                                    int visibleItemCount, int totalItemCount) {
                                // TODO Auto-generated method stub
                                if(firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0)
                                {
                                    if(flag_loading == false)
                                    {
                                        flag_loading = true;
                                        new getbride().execute("param1","param2","param3");
                                        lcnt++;
    
                                        int count=lv.getAdapter().getCount();
                                        String cnt_bride=String.valueOf(count);
                                        TextView list_cnt=(TextView)findViewById(R.id.cnt);
                                        list_cnt.setText(cnt_bride);
                                    }
                                }                               
                            }
                            @Override
                            public void onScrollStateChanged(AbsListView arg0,
                                    int arg1) {
                                // TODO Auto-generated method stub
    
                            }
                        });
                    }
                  }else{
                      Toast.makeText(getApplicationContext(),"No internet connection...", Toast.LENGTH_SHORT).show();
                  }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
    

    Note that I don't think that calling invalidateViews() is necessary here. See this post: Is there any difference between `ListView.invalidateViews()` and 'Adapter.notifyDataSetChanged()'?