Android:在哪里以及如何自动刷新列表视图(我有刷新功能)

Posted

技术标签:

【中文标题】Android:在哪里以及如何自动刷新列表视图(我有刷新功能)【英文标题】:Android: Where and how to auto refresh listview (I have the refresh function) 【发布时间】:2015-09-11 22:47:25 【问题描述】:

这是我的 MainActivity,我真的需要帮助来创建一个每分钟自动刷新列表视图的函数

在我的 MainActivity 我有这个代码:

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

    @Override
    public void onRefresh() 
        fetchOrders();
    

我已经阅读了一些关于处理程序的文章,我得说我不知道​​将处理程序的代码放在哪里,因此如果你能帮我发布我的完整 MainActivity 以及额外的所需代码,那就是不胜感激

提前致谢!

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

【问题讨论】:

【参考方案1】:

您可以通过向 Handler 添加延迟任务来做到这一点。完整代码如下:

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,感谢您的回复,我在 2 行上遇到编译错误:mAutoRefreshRunnable.fetchOrders(); .postDelayed(mAutoRefreshRunnable, 1000);可能是因为要求我导入 java.util.logging.Handler 或 android.Os.Handler 而我选择了 android.Os.Handler,介意我通过电子邮件将完整代码发送给您吗? 嗯,我打错了,再检查更新的代码 另一个重要的问题,我如何在获取新数据后添加振动和声音响铃? , 毕竟不是在每次自动刷新数据都插入之后 ***.com/questions/6462105/…,你可以看看这里。您可能需要创建一个单独的问题以获得最佳答案 将其作为一个新问题发布,并希望听到您的回答 - ***.com/questions/32537861/…

以上是关于Android:在哪里以及如何自动刷新列表视图(我有刷新功能)的主要内容,如果未能解决你的问题,请参考以下文章

如何自动刷新列表视图? [复制]

知道如何防止 Android Widget 中显示的列表视图在每次刷新数据时闪烁吗?

Android 列表视图刷新

在android的片段中设置列表视图适配器

刷新列表视图数据库

Android - 如何像每 1 秒一样自动刷新卡片视图