1

This is my MainActivity, I really need help on creating a function that will autorefresh the listview every minute

In my MainActivity I have this code:

    //This method is called when swipe refresh is pulled down

    @Override
    public void onRefresh() {
        fetchOrders();
    }

I've read a few articles about the handler, I gotta say I have no idea where to put the handler's code, therefore if you can give me a hand and post my full MainActivity with that additional desired code, it would be more than appreciated

Thanks in advance!

public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {

    private int mInterval = 5000; // 5 seconds by default, can be changed later
    private Handler mHandler;

    private String TAG = MainActivity.class.getSimpleName();

    private String URL = "http://troyka.esy.es/troyka/orders.php";


    private SwipeRefreshLayout swipeRefreshLayout;
    private ListView listView;
    private SwipeListAdapter adapter;
    private List<Order> orderList;

    // initially offset will be 0, later will be updated while parsing the json
    private int offSet = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        listView = (ListView) findViewById(R.id.listView);
        //RelativeLayout.LayoutParams layout_description = new RelativeLayout.LayoutParams(50,10);

        //Rl.setLayoutParams(layout_description);

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);

        orderList = new ArrayList<>();
        adapter = new SwipeListAdapter(this, orderList);
        listView.setAdapter(adapter);

        swipeRefreshLayout.setOnRefreshListener(this);

        /**
         * Showing Swipe Refresh animation on activity create
         * As animation won't start on onCreate, post runnable is used
         */
        swipeRefreshLayout.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        swipeRefreshLayout.setRefreshing(true);

                                        fetchOrders();
                                    }
                                }
        );

        mHandler = new Handler();
        startRepeatingTask();
    }
    Runnable mStatusChecker = new Runnable() {
        @Override
        public void run() {
            //updateStatus(); //this function can change value of mInterval.
            mHandler.postDelayed(mStatusChecker, mInterval);
        }
    };
    void startRepeatingTask() {
        mStatusChecker.run();
    }

    void stopRepeatingTask() {
        mHandler.removeCallbacks(mStatusChecker);
    }

    /**
     * This method is called when swipe refresh is pulled down
     */


    @Override
    public void onRefresh() {
        fetchOrders();
    }

    /**
     * Fetching movies json by making http call
     */
    private void fetchOrders() {

        // showing refresh animation before making http call
        swipeRefreshLayout.setRefreshing(true);

        // appending offset to url
        String url = URL + offSet;

        // Volley's json array request object
        JsonArrayRequest req = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());

                        if (response.length() > 0) {

                            // looping through json and adding to order list
                            for (int i = 0; i < response.length(); i++) {
                                try {
                                    JSONObject orderObj = response.getJSONObject(i);

                                    int rank = orderObj.getInt("rank");
                                    String title = orderObj.getString("title");

                                    Order m = new Order(rank, title);

                                    orderList.add(0, m);

                                    // updating offset value to highest value
                                    if (rank >= offSet)
                                        offSet = rank;

                                } catch (JSONException e) {
                                    Log.e(TAG, "JSON Parsing error: " + e.getMessage());
                                }
                            }

                            adapter.notifyDataSetChanged();
                        }

                        // stopping swipe refresh
                        swipeRefreshLayout.setRefreshing(false);

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Server Error: " + error.getMessage());

                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();

                // stopping swipe refresh
                swipeRefreshLayout.setRefreshing(false);
            }
        });

        // Adding request to request queue
        MyApplication.getInstance().addToRequestQueue(req);
    }
}
iguana
  • 77
  • 1
  • 9

1 Answers1

3

You can do that by added a delayed task to Handler. Here is the full code:

public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {

    private int mInterval = 5000; // 5 seconds by default, can be changed later
    private Handler mHandler;

    private String TAG = MainActivity.class.getSimpleName();

    private String URL = "http://troyka.esy.es/troyka/orders.php";


    private SwipeRefreshLayout swipeRefreshLayout;
    private ListView listView;
    private SwipeListAdapter adapter;
    private List<Order> orderList;

    // initially offset will be 0, later will be updated while parsing the json
    private int offSet = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        listView = (ListView) findViewById(R.id.listView);
        //RelativeLayout.LayoutParams layout_description = new RelativeLayout.LayoutParams(50,10);

        //Rl.setLayoutParams(layout_description);

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);

        orderList = new ArrayList<>();
        adapter = new SwipeListAdapter(this, orderList);
        listView.setAdapter(adapter);

        swipeRefreshLayout.setOnRefreshListener(this);

        /**
         * Showing Swipe Refresh animation on activity create
         * As animation won't start on onCreate, post runnable is used
         */
        swipeRefreshLayout.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        swipeRefreshLayout.setRefreshing(true);

                                        fetchOrders();
                                    }
                                }
        );

        mHandler = new Handler();
        startRepeatingTask();
    }
    Runnable mStatusChecker = new Runnable() {
        @Override
        public void run() {
            //updateStatus(); //this function can change value of mInterval.
            mHandler.postDelayed(mStatusChecker, mInterval);
        }
    };
    void startRepeatingTask() {
        mStatusChecker.run();
    }

    void stopRepeatingTask() {
        mHandler.removeCallbacks(mStatusChecker);
    }

    //added code start here
    Runnable mAutoRefreshRunnable = new Runnable() {
        @Override
        public void run() {
            fetchOrders()
            mHandler.postDelayed(mAutoRefreshRunnable, 1000);
        }
    };

    @Override
    protected void onResume() {
       mHandler.postDelayed(mAutoRefreshRunnable, 1000);
    }

    @Override
    protected void onPause() {
        mHandler.removeCallbacks(mAutoRefreshRunnable);
    }
    //added code ends here


    /**
     * This method is called when swipe refresh is pulled down
     */


    @Override
    public void onRefresh() {
        fetchOrders();
    }

    /**
     * Fetching movies json by making http call
     */
    private void fetchOrders() {

        // showing refresh animation before making http call
        swipeRefreshLayout.setRefreshing(true);

        // appending offset to url
        String url = URL + offSet;

        // Volley's json array request object
        JsonArrayRequest req = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());

                        if (response.length() > 0) {

                            // looping through json and adding to order list
                            for (int i = 0; i < response.length(); i++) {
                                try {
                                    JSONObject orderObj = response.getJSONObject(i);

                                    int rank = orderObj.getInt("rank");
                                    String title = orderObj.getString("title");

                                    Order m = new Order(rank, title);

                                    orderList.add(0, m);

                                    // updating offset value to highest value
                                    if (rank >= offSet)
                                        offSet = rank;

                                } catch (JSONException e) {
                                    Log.e(TAG, "JSON Parsing error: " + e.getMessage());
                                }
                            }

                            adapter.notifyDataSetChanged();
                        }

                        // stopping swipe refresh
                        swipeRefreshLayout.setRefreshing(false);

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Server Error: " + error.getMessage());

                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();

                // stopping swipe refresh
                swipeRefreshLayout.setRefreshing(false);
            }
        });

        // Adding request to request queue
        MyApplication.getInstance().addToRequestQueue(req);
    }
}
Derek Fung
  • 8,171
  • 1
  • 25
  • 28
  • Hi Derek, thanks for your reply, I'm getting compile errors on 2 lines : mAutoRefreshRunnable.fetchOrders(); .postDelayed(mAutoRefreshRunnable, 1000); maybe it's caused when asked me to import the java.util.logging.Handler OR android.Os.Handler and I chose android.Os.Handler, mind if I send you the full code via email? – iguana Sep 12 '15 at 09:30
  • um, I made a typo there, check the updated code again – Derek Fung Sep 12 '15 at 09:39
  • another important question, how can I add a vibration and sound ring once new data is fetched? , after all not after every auto refresh data is inserted – iguana Sep 12 '15 at 10:16
  • http://stackoverflow.com/questions/6462105/how-do-i-access-androids-default-beep-sound, you can have a look here. You may want to create a separate question for best answer – Derek Fung Sep 12 '15 at 10:33
  • posted it as a new question, and would love to hear your answer - http://stackoverflow.com/questions/32537861/listview-how-to-notify-the-user-about-new-fetched-data-with-sound-and-vibration – iguana Sep 12 '15 at 10:41