Android的ListView控件更新/刷新数据,但不关闭应用程序 [英] android listview update/refresh data without closing the app

查看:193
本文介绍了Android的ListView控件更新/刷新数据,但不关闭应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Android应用程序从我的Web服务器获取数据,然后显示他们对我的列表视图并保存到我的本地数据库(sqlite的)。如果我添加另一条记录到我的Web服务器,应用程序应该刷新/更新我的列表视图,就像Facebook的应用程序,如果有新的职位则显示这些职位。

I have an android application which fetches data from my web server and then display them on my listview and save to my local database (sqlite). If I add another record to my web server, the application should refresh/update my listview, just like the facebook app if there are new posts then display those posts.

这是我迄今为止:

ListViewAdapter adapter;

// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {

@Override
protected void onPreExecute() {
        super.onPreExecute();
        // Create a progressdialog
        mProgressDialog = new ProgressDialog(MainActivity.this);
        // Set progressdialog title
        mProgressDialog.setTitle("Downloading Records");
        // Set progressdialog message
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setIndeterminate(false);
        // Show progressdialog
        mProgressDialog.show();
}

@Override
protected Void doInBackground(Void... params) {
        // Create the array 
        arraylist = new ArrayList<HashMap<String, String>>();
        // Retrieve JSON Objects from the given website URL in JSONfunctions.class
        String result = JSONFunctions.getJSONfromURL(URL);

        try {
            JSONArray jr = new JSONArray(result);
            for(int i=0;i<jr.length();i++)
             {  
                    HashMap<String, String> map = new HashMap<String, String>();
                      jb = (JSONObject)jr.get(i);
                      map.put(TAG_ID, jb.getString(TAG_ID));
                      map.put(TAG_NAME, jb.getString(TAG_NAME));
                      arraylist.add(map);

                    String strID = jb.getString(TAG_NAME);

                    dbHelper.createEntry(strID);


             }
        } catch (JSONException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
} 

@Override
protected void onPostExecute(Void args) {
        // Locate the listview in listview_main.xml
        listview = (ListView) findViewById(R.id.listView1);
        // Pass the results into ListViewAdapter.java
        adapter = new ListViewAdapter(MainActivity.this, arraylist);
        // Binds the Adapter to the ListView
        listview.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        //TextView tv = (TextView) findViewById (R.id.textView1);
        //tv.setText("Successfully processed");

        // Close the progressdialog
        mProgressDialog.dismiss();
    }
}

的片段我的 listviewadapter.class

 public View getView(final int position, View convertView, ViewGroup parent) {
    // Declare Variables
    TextView id;

    inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View itemView = inflater.inflate(R.layout.list_item, parent, false);
    // Get the position from the results
    HashMap<String, String> resultp = new HashMap<String, String>();
    resultp = data.get(position);

    // Locate the TextViews in list_item.xml
    id = (TextView) itemView.findViewById(R.id.listitem_id); 

    // Capture position and set results to the TextViews
    id.setText(resultp.get(MainActivity.TAG_NAME));
    // Capture position and set results to the ImageView
    // Passes movie images URL into ImageLoader.class to download and cache
    // images
    // Capture button clicks on ListView items
    itemView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // Get the position from the results
            HashMap<String, String> resultp = new HashMap<String, String>();
            resultp = data.get(position);
            // Send single item click data to SingleMenuItemView Class
            Intent intent = new Intent(context, SingleMenuItemActivity.class);
            // Pass data 
            intent.putExtra("id", resultp.get(MainActivity.TAG_ID));
            intent.putExtra("name", resultp.get(MainActivity.TAG_NAME));
            // Start SingleItemView Class
            context.startActivity(intent);
        }
    });

    return itemView;
}

我也没有补充一点:

I also did add this:

   adapter.notifyDataSetChanged();

无济于事。它不更新列表。这只是在更新,如果我关闭应用程序,然后再次打开它。任何想法如何做到这一点?帮助是pretty多少AP preciated。谢谢你。

to no avail. It's not updating the list. It's just updating if I close the app and open it again. Any ideas how to do this? Help is pretty much appreciated. Thanks.

推荐答案

您应该安排你的 DownloadJSON 任务定期运行如下:

You should schedule your DownloadJSON task to run periodically as follows:

public void callAsynchronousTask() {
    final Handler handler = new Handler();
    Timer timer = new Timer();
    TimerTask doAsynchronousTask = new TimerTask() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    try {
                        DownloadJSON performBackgroundTask = new DownloadJSON();
                        performBackgroundTask.execute();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    };
    timer.schedule(doAsynchronousTask, 0, 10000); //execute in every 10 sec
}

这应该工作,但它不是最有效的方法,你一次又一次请求整个数据。 (有正在下载大量数据,这是不是必须的)。

This should work however its not the most efficient way as you are requesting the whole data again and again. (There is lots of data being downloaded which is not required).

相反,你应该定期运行任务,如果存在任何新的更新,检查服务器。如果服务器说是..然后它获取的完整列表..否则它将等待一段时间再进行新的更新请求。但是,为此,你需要修改服务器API(这样你就可以在未来考虑这个)

Instead you should run a task periodically that checks the server if any new updates exist. If server says yes.. then it fetches the complete list.. otherwise it waits for some time and requests for new update again. But for this you need to modify the server API (so you can consider this in the future)

这篇关于Android的ListView控件更新/刷新数据,但不关闭应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆