繁体   English   中英

Android-在服务器中添加数据时更新ListView

[英]Android - Update ListView when data is added in sever

我是android开发的新手。 我正在尝试制作一个从Web服务器检索数据并在列表视图中更新它的应用程序。 问题是,每当在数据库中输入新数据时,列表视图都不会更新。

当数据库中有新条目时,如何自动更新列表?

public class NotificationTask extends ListActivity {


UserFunctions userFunctions;
Button btnLogout;
DatabaseHandler dbHandler;
private HashMap<String, String> user;

SessionManager session;

// Progress Dialog
private ProgressDialog pDialog;

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

ArrayList<HashMap<String, String>> productsList;

// url to get all products list
private static String url_all_products = "http://192.168.1.9/android_login_api/get_notifications.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "notifications";
private static final String TAG_PID = "id";
private static final String TAG_NAME = "title";
private static final String TAG_DESCRIPTION = "discription";

// products JSONArray
JSONArray products = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    session = new SessionManager(getApplicationContext());       

    userFunctions = new UserFunctions();
    if(userFunctions.isUserLoggedIn(getApplicationContext())){
   // user already logged in show databoard
        setContentView(R.layout.notifications);
        btnLogout = (Button) findViewById(R.id.btnlogout);

        dbHandler = new DatabaseHandler(getApplicationContext());
        user = dbHandler.getUserDetails();
        TextView emailTextView = (TextView) findViewById(R.id.user);
        emailTextView.setText(user.get("name"));

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

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

        btnLogout.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {
                session.logoutUser();     
            }
        });

    }
        }

        @Override
        public void onBackPressed() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
        }

/**
 * 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(NotificationTask.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.getJSONFromUrl(url_all_products, params);

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

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);

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

                    // Storing each json item in variable
                    String id = c.getString(TAG_PID);
                    String name = c.getString(TAG_NAME);
                    String description = c.getString(TAG_DESCRIPTION);

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

                    // adding each child node to HashMap key => value
                    map.put(TAG_PID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_DESCRIPTION, description);

                    // adding HashList to ArrayList
                    productsList.add(map);
                }
            } else {
                // no products found
                // Launch Add New product Activity

            }
        } 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
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        NotificationTask.this, productsList,
                        R.layout.list_item, new String[] { TAG_PID,
                                TAG_NAME, TAG_DESCRIPTION},
                        new int[] { R.id.pid, R.id.name, R.id.description });
                setListAdapter(adapter) 
    }
}

}

在我看来,这是同步适配器的理想用例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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