在Android中向数据库添加新数据后更新列表视图

3

我希望制作一个Android聊天室应用程序,使用PHP、MYSQL作为web服务,并在我的Android应用程序中解析JSON数据。一开始我能够查看数据,但即使在我的数据库中更新后,我也无法在我的应用程序中更新数据,必须重新运行应用程序才能获取更新的数据。我该如何解决这个问题。

代码:

package com.example.androidhive;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

//import com.mekya.R;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class AllProductsActivity extends ListActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> all_chat;

    // url to get all products list
    private static String url_all_products = "http://url.com/chat-app/";

    // JSON Node names
    private static final String TAG_CHAT = "chat";
    private static final String TAG_FROM = "from_u";
    private static final String TAG_MESSAGE = "message";
    private static final String TAG_DATE = "date";


    // products JSONArray
    JSONArray chat = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_products);

        // Hashmap for ListView
        all_chat = new ArrayList<HashMap<String, String>>();

        // Loading products in Background Thread
        new LoadAllProducts().execute();  


    }

    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllProducts extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AllProductsActivity.this);
            pDialog.setMessage("Loading products. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());

            try {
                    // products found
                    // Getting Array of Products
                    chat = json.getJSONArray(TAG_CHAT);

                    // looping through All Products
                    for (int i = 0; i < chat.length(); i++) {
                        JSONObject c = chat.getJSONObject(i);

                        // Storing each json item in variable
                        String date = c.getString(TAG_DATE);
                        String from = c.getString(TAG_FROM);
                        String message = c.getString(TAG_MESSAGE);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_DATE, date);
                        map.put(TAG_FROM, from);
                        map.put(TAG_MESSAGE, message);

                        // adding HashList to ArrayList
                        all_chat.add(map);
                    }

            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread

            runOnUiThread(new Runnable() {

                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            AllProductsActivity.this, all_chat, R.layout.list_item, new String[] { TAG_FROM,TAG_DATE, TAG_MESSAGE },
                            new int[] { R.id.from,R.id.date, R.id.message });
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }

    }
}

请在此处添加您的适配器Java代码。 - Simon Dorociak
Sajmon_d先生,我不明白您的意思... :( 我没有Java代码适配器,我该怎么办? - l3l4c7_h4t
先生,我使用默认的ListAdapter。我使用了“import android.widget.ListAdapter;”。 - l3l4c7_h4t
1个回答

0

流程应该是这样的,

假设这是你的URL:http://www.xxx.com/get_chat.php?id="" 服务器应该根据id参数发送响应。如果没有发送整个列表,否则发送新数据比那个id更新。

所以,第一次您将获得整个列表,之后服务器只会发送新数据,基于最后一个项目的id。根据您提到的内容,我假设您可以更新您的数据库。

现在假设您有一个计时器,并且您的应用程序每秒向服务器发送请求(如果要使其真实,这是可怕的假设。只需假设10000个设备每秒发送请求!) 如果没有数据:不要做任何事情(应该在onPostExecute方法中检查) 如果有数据:从数据库中获取整个列表(因为已添加新数据,因此您将拥有更新的项目)并将其传递给适配器。

希望它能帮助您 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接