nikki
nikki

Reputation: 3228

how to update listview item when get new data from server after few seconds

I have facing problem in listview i am getting data from server and after parsing this data i am using custom adpater for showing the data in listview.I want to update the listview item each after 3 seconds and add new data to list.how can it possible.

i am using adapter.notifyDataSetChanged() method but my listview is not updating it is showing the old data that i gets first time.how to show new data in listview that i got each after 3 seconds.i am using the update method like this.

private Handler handler = new Handler();
     private Runnable updater = new Runnable() {

     public void run() {

       /*
        * Update the list 
        */


         //list.clearTextFilter();
         getVisitorDetailFromServer();
         list.invalidateViews();

         adapter.notifyDataSetChanged();

       try {
          Log.i("UPDATE", "Handler called");
         // searchAdapter = getFeed(URL);
          adapter.notifyDataSetChanged();
          handler.postDelayed(this, 3000);
       } catch(Exception e) {
          Log.e("UPDATE ERROR", e.getMessage());
       }

      }

     };

Using getVisitorDetailFromServer() i am getting the data.

adapter class code is

private class CustomAdapter extends BaseAdapter { private LayoutInflater mInflater;

    public CustomAdapter(Context context) {
        mInflater = LayoutInflater.from(context);



    }

    public void setContext(Context context) {
        // TODO Auto-generated method stub
        //caching. notifyDataSetChanged();

    }

    public int getCount() {
        return sizeoflist;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.row1, null);
            holder = new ViewHolder();
            holder.IP = (TextView) convertView.findViewById(R.id.ip);
            holder.duration = (TextView) convertView.findViewById(R.id.duration);
            holder.status =(TextView) convertView.findViewById(R.id.status);
            holder.noOfVisit = (TextView) convertView.findViewById(R.id.NoOfvisit);
            holder.invite =(Button)convertView.findViewById(R.id.btnjoin);
            holder.deny = (Button) convertView.findViewById(R.id.btndeny);

            holder.deny.setVisibility(View.INVISIBLE);

            holder.invite.setId(position);


            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();

        }


        String result = response;

        String delimiter = "<fld>";
        String delimiter1 = "<ln>";
        String delimiter2 = "<blk>";
        String delimiter3 = "<fld><fld><blk>";
        operatorDetail = result.split(delimiter1);
        String[] operatorlist = result.split(delimiter3);
        noofvisitors = operatorlist[1].split(delimiter2);

        System.out.println("no of visitor================"+noofvisitors[0]);

        for(int i=0;i<operatorDetail.length;i++){


            operatorList = operatorDetail[i].split(delimiter);

            operatorlist = result.split(delimiter2);


            SessionText.add(operatorList[0]);
            IPText.add(operatorList[1]);
            DurationText.add(operatorList[4]);
            StatusText.add(operatorList[3]);
            NoOfVisit.add(operatorList[2]);
            ButtonText.add(operatorList[6]);

            iptext = IPText.get(i) ;
            sessionid = SessionText.get(i);

            //System.out.println("session value is"+SessionText.get(position));
            //System.out.println("ip values are"+IPText.get(position));
            //System.out.println("duration values are"+DurationText.get(position));
            //System.out.println("status values are"+StatusText.get(position));
            //System.out.println("no of visit"+NoOfVisit.get(position));


            if(StatusText.get(position).equalsIgnoreCase("chat request")){
                holder.deny.setVisibility(View.VISIBLE);
                holder.invite.setText("Accept");
                holder.invite.setOnClickListener(new View.OnClickListener() {

                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        holder.invite.setText("Join");
                        holder.deny.setVisibility(View.INVISIBLE);
                    }
                });

            }
            else{
                holder.invite.setText("Invite");
                holder.deny.setVisibility(View.INVISIBLE);
            }




            if(holder.invite.getText().equals("Join")){

                holder.invite.setOnClickListener(new View.OnClickListener() {

                    public void onClick(View v) {
                        // TODO Auto-generated method stub

                        chatRequest(iptext,sessionid);
                    }
                });
            }



            holder.IP.setText(IPText.get(position));
            holder.duration.setText(DurationText.get(position));
            holder.status.setText(StatusText.get(position));
            holder.noOfVisit.setText(NoOfVisit.get(position));


            //---------------------When user click on invite Button---------------------


            holder.invite.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    callToServer(SessionText.get(position));
                }
            });



            //-----------------------------When user click on deny button------------------------

            holder.deny.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    refuseToServer(sessionid);
                    holder.deny.setVisibility(View.INVISIBLE);
                }




            });



        }



        System.out.println("no of visitor================"+noofvisitors[0]);


        convertView.setOnClickListener(new OnClickListener(){

            public void onClick(View v) {
                Intent i=new Intent(Visitors.this,VisitorDetail.class);
                i.putExtra("ID", id);
                i.putExtra("Position",position);
                i.putExtra("From", from);
                i.putExtra("SessionText", SessionText.get(position));
                i.putExtra("IPTEXT",IPText.get(position));
                startActivity(i);
            }});
        //startService();
        return convertView;
    }


    class ViewHolder {
        TextView IP;
        TextView duration;
        Button deny;
        TextView status;
        TextView noOfVisit;
        Button invite;
    }
}

my class code is public class Visitors extends Activity {

private ListView list;

private final int NOTIFICATION_ID = 1010;
private Timer timer = new Timer();
private  String response,response1;
protected Dialog m_ProgressDialog;
String[] operatorList,operatorDetail,operatordetail,tempoperatordata;
String[] noofvisitors,opt;
private static final String DEB_TAG = "Error Message";
public static ArrayList<String> SessionText,IPText,DurationText;
private ArrayList<String> StatusText,NoOfVisit,ButtonText;
private int sizeoflist;
private String IP;
Context context;
public static String from,sessionid,id,text,iptext,status;
private int position,noofchat;
private boolean IsSoundEnable,IsChatOnly;
private Button logout;
private CustomAdapter adapter;
NotificationManager notificationManager;



final HashMap<String, String> postParameters = new HashMap<String, String>();
private String url;

 private Handler handler = new Handler();
private Runnable updater = new Runnable() {

 public void run() {

   /*
    * Update the list 
    */


    //list.clearTextFilter();
     getVisitorDetailFromServer();
     list.invalidateViews();

     adapter.notifyDataSetChanged();

   try {

      adapter.notifyDataSetChanged();
      handler.postDelayed(this, 3000);
   } catch(Exception e) {
      Log.e("UPDATE ERROR", e.getMessage());
  }

  }

 };



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.visitor);

    list = (ListView) findViewById(R.id.list01);

    logout = (Button) findViewById(R.id.btnlogout);

    adapter = new CustomAdapter(Visitors.this);


    updater.run();



    //-----------------Making the object of arrayList----------------

    SessionText = new ArrayList<String>();
    IPText = new ArrayList<String>();
    DurationText = new ArrayList<String>();
    StatusText = new ArrayList<String>();
    NoOfVisit = new ArrayList<String>();
    ButtonText = new ArrayList<String>();

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        IsSoundEnable = Controls.IsSoundEnable;
        IsChatOnly = Controls.IsChatOnly;
        IsSoundEnable = extras.getBoolean("IsSoundOnly", Controls.IsSoundEnable);
        IsChatOnly= extras.getBoolean("IsCOnlyhat", Controls.IsChatOnly);
        extras.getString("From");
        position=extras.getInt("Position");


    }



}



@Override
protected void onStart() {

    super.onStart();

    //------------Getting the visitor detail-------------------------


     getVisitorDetailFromServer();




    //---------------When user click on logout button-----------------------------------


        logout.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            logoutFromServer();


        }



    });


}


//----------------------------Getting the detail from server of monitoring window-------------------------


private void getVisitorDetailFromServer() {
    // TODO Auto-generated method stub



    if(IsChatOnly){
        url = "http://sa.live2support.com/cpn/wz1-allonlineu.php?";
        postParameters.put("adminid",Main.loginId.getText().toString());
        postParameters.put("sid",Main.siteId.getText().toString());
        postParameters.put("nvar","Y");
        postParameters.put("conly", "Y");
    }
    else{
        url = "http://sa.live2support.com/cpn/wz1-allonlineu.php?";
        postParameters.put("adminid",Main.loginId.getText().toString());
        postParameters.put("sid",Main.siteId.getText().toString());
        postParameters.put("nvar","Y");
        postParameters.put("conly", "N");

    }

    Runnable searchThread = new Runnable(){

        public void run() {
            // TODO Auto-generated method stub

            try {

                response = CustomHttpClient.executeHttpPost1(url,postParameters);

                Log.i(DEB_TAG, "Requesting to server"+response);
                //CustomHttpClient.getResponseInString(response );

                System.out.println("Output of httpResponse:"+response);

                String result = response;

                String delimiter1 = "<ln>";
                String delimiter = "<fld>";

                operatorDetail = result.split(delimiter1);
                for(int i=0;i<operatorDetail.length;i++){

                    operatorList = operatorDetail[i].split(delimiter);
                    SessionText.add(operatorList[0]);
                    IPText.add(operatorList[1]);
                    DurationText.add(operatorList[4]);
                    StatusText.add(operatorList[3]);
                    NoOfVisit.add(operatorList[2]);
                    ButtonText.add(operatorList[6]);




                }




                //--------Getting the size of the list---------------------

                sizeoflist = operatorDetail.length;




            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if(response!=null){

                runOnUiThread(new Runnable() {

                    public void run() {
                        // TODO Auto-generated method stub
                        playsound3();
                        noofchat =0;
                        System.out.println(response);

                        list.setAdapter(adapter);
                        list.getDrawingCache(false);
                        list.invalidateViews();
                        list.setCacheColorHint(Color.TRANSPARENT);
                        list.requestFocus(0);
                        list.setSelected(false);

                        list.setOnItemClickListener(new OnItemClickListener() {
                            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {

                                String item = ((TextView)view).getText().toString();


                                Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();

                            }
                        });

                        if(IsChatOnly==false){
                            TimerTask timerTask = new TimerTask()
                            {
                                @Override
                                public void run()
                                {

                                    //triggerNotification();
                                    //playsound();

                                }
                            };
                            timer.schedule(timerTask, 3000);
                        }
                        else{

                            playsound();
                        }



                    }


                });
            }

            else {

                ShowAlert();
            }


        }
    };

    Thread thread =  new Thread(null, searchThread, "MagentoBackground");
    thread.start();




}

//--------------------When internet connection is failed show alert

private void ShowAlert() {
    // TODO Auto-generated method stub
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    final AlertDialog alert = builder.create();
    alert.setTitle("Live2Support");
    alert.setMessage("Internet Connection failed");
    alert.setButton("OK", new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            //startActivity(new Intent(CreateAccount.this,CreateAccount.class));
            alert.dismiss();

        }
    });

    alert.show();
}

//--------------------Play sound when notification occurs-------------------

private void playsound() {
    // TODO Auto-generated method stub

    MediaPlayer mp = MediaPlayer.create(this, R.raw.newvisitsound);

        mp.start();

}

Upvotes: 0

Views: 2998

Answers (2)

Husnain Iqbal
Husnain Iqbal

Reputation: 466

I was having the same problem. I cleared the list before adding the new data and it resolved

Upvotes: 0

Saad Farooq
Saad Farooq

Reputation: 13402

Simple calling adapter.notifyDataSetChanged() will not work unless you actually update the dataset 'within the adapter class'.

I suspect you are not passing the updated information into your Adapter class. Check to see if the datastructure referenced by your Adapter's getCount() method is the same as the one being updated by the getVisitorDetailFromServer() server.

If that is not the problem, you'll need to post more code.

Upvotes: 1

Related Questions