How to update ui from asynctask

后端 未结 3 573
被撕碎了的回忆
被撕碎了的回忆 2020-11-29 07:05

I\'ve seen many examples of how to do this, but I can\'t figure how to implement it in my code.

I am using this code.
I have updated the url, so it will receive

3条回答
  •  [愿得一人]
    2020-11-29 07:17

    The first thing is using postdelayed() will not run your code in repetition If you want to run code in repetitive pattern use this code. This will run after every 5 sec

      ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
    
        /*This schedules a runnable task every second*/
        scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
          public void run() 
          {
            runOnUiThread(new Runnable(){
    
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    new GetContacts().execute();
                }
    
            });
          }
        }, 0, 5, TimeUnit.SECONDS);
    

    The code you are following is creating new instance of SimpleAdapter in postExecute() each time so you will see the same data again and again. So if you want to update your adapter create SimpleAdapter instance as class member and replace the postExecute() by this

    @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                // Dismiss the progress dialog
                if (pDialog.isShowing())
                    pDialog.dismiss();
                /**
                 * Updating parsed JSON data into ListView
                 * */
                if(adapter == null)
                {
                    adapter = new SimpleAdapter(
                        MainActivity.this, contactList,
                        R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL,
                                TAG_PHONE_MOBILE }, new int[] { R.id.name,
                                R.id.email, R.id.mobile });
    
                                setListAdapter(adapter);
                }
                else
                {
                    adapter.notifyDataSetChanged();
                }
    
    
            }
    

    Now this will update adapter but will add same contact

提交回复
热议问题