简体   繁体   中英

Android: How to make my retrieved (from mysql) JSON parsed data added to ListView refresh it self every minute

In the code below, there's one activity that is fetching data from a mysql database (6 strings) via php to the android app and straight to a ListView.

<?php

    define('HOST','my_hostname..');
    define('USERNAME','mysql username');
    define('PASSWORD','mysql password');
    define('DB','mysql db name');

    $con = mysqli_connect(HOST,USERNAME,PASSWORD,DB) or die('Unable to      

    connect');

    $sql = "select * from orders";

    $res = mysqli_query($con,$sql);

    $result = array();

   while($row = mysqli_fetch_array($res)){
   array_push($result,
   array('user'=>$row[0],'city'=>$row[1],'street'=>$row[2],          
   'streetnumber'=>$row[3],'phone'=>$row[4],'name'=>$row[5]));
   }

   echo json_encode(array("result"=>$result));

   mysqli_close($con);

   ?>
 public void refreshlistview(){  
 CountDownTimer mCountDownTimer = new CountDownTimer(60000, 1000) {
        public void onTick(long millisUntilFinished) {

        }
        public void onFinish() {
          //do refresh here 

          //then call it again - Recursive 
          refreshlistview();
        }
    } ;
 }

you can use timer and refresh every 1 mins = 60000 millisecond

to compare data i see you're using a hashmap on your showlist() so make it to return a hashmap and you can call it whenever you need to fetch new data and pass the old and new one to this method if it return true then the data is equal else you can inform the user that the data has been changed and set listview adapter again

public HashMap<String,String> compare(Map<String, String> old,Map<String,String> new)
{
    for (String i : old.keySet())
    {
        if (old.get(i) != new.get(i)) {
            return false;
        }
    } 
 return true;
}

This question can be done in two ways one is by TimerTask class and other is by Handler class. I prefer Handler one so i am posting how to do using Handler

http://developer.android.com/reference/java/util/TimerTask.html

final Handler handler = new Handler()
handler.postDelayed( new Runnable() {

    @Override
    public void run() {
        YOUR_ADAPTER_GOES_HERE.notifyDataSetChanged();
        //dont forget to call getData();
        handler.postDelayed( this, 60 * 10000 ); //ensure to run after 10 minutes
    }
}, 60 * 10000 );

You must only update UI in the main (UI) thread.

By creating the handler in the main thread, you ensure that everything you post to the handler is run in the main thread also.

Android WorkManager api 是最好的解决方案工作管理器

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM