【问题标题】:how to update listview item when get new data from server after few seconds几秒钟后从服务器获取新数据时如何更新列表视图项
【发布时间】:2012-02-18 06:09:52
【问题描述】:

我在 listview 中遇到问题,我从服务器获取数据,在解析这些数据后,我使用自定义 adpater 在 listview 中显示数据。我想在 3 秒后更新 listview 项目并将新数据添加到列表中。怎么可能。

我正在使用 adapter.notifyDataSetChanged() 方法,但我的列表视图没有更新它显示的是我第一次获得的旧数据。如何在列表视图中显示我在 3 秒后获得的新数据。我正在使用更新像这样的方法。

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

      }

     };

使用 getVisitorDetailFromServer() 我正在获取数据。

适配器类代码是

私有类 CustomAdapter 扩展 BaseAdapter { 私有 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;
    }
}

我的课程代码是 公共类访客扩展活动{

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

}

【问题讨论】:

  • 请帮助我为什么我的列表没有被更新。我想在 android 中每 3 秒后向列表视图添加新数据
  • 粘贴您的适配器代码。
  • 请帮助我在哪里做错了。
  • 我在课堂上每 3 秒收到一次来自服务器的新响应我检查响应的值每 3 秒更新一次我在 logcat 中打印它。但是列表视图没有被新的响应值更新.

标签: android


【解决方案1】:

简单的调用adapter.notifyDataSetChanged() 将不起作用,除非您真正在“适配器类”中更新数据集。

我怀疑您没有将更新的信息传递给您的 Adapter 课程。检查AdaptergetCount() 方法引用的数据结构是否与getVisitorDetailFromServer() 服务器正在更新的数据结构相同。

如果这不是问题,您需要发布更多代码。

【讨论】:

  • 我已经粘贴了我正在使用的代码。请查看并帮助我
  • 是的...我看到了...这就是为什么我评论...你的实施。我有一个使用通用 AsyncTask 从 web 服务获取 Json 的库......看看:github.com/sfarooq/A-droid-lib
  • 但是对于您当前的问题...我会在您的 Adapter 类中的某处放置一个 Log 并查看 getCount() 是否正在返回更新值。我认为这可能是适配器类之外的问题。
  • 先生,我每次 3 秒后都会在 logcat 中检查我的活动,我从服务器收到新的响应。我在 logcat 中打印响应的值。但在列表视图中没有添加新数据
【解决方案2】:

我遇到了同样的问题。我在添加新数据之前清除了列表并解决了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    • 1970-01-01
    • 2016-03-26
    • 1970-01-01
    相关资源
    最近更新 更多