从MySQL数据库添加/删除内容后,ListView不会刷新

时间:2013-04-13 12:11:33

标签: android mysql database listview refresh

我编写了一个Android应用程序来管理MySQL数据库,并且我使用一些PHP类来连接/添加/删除行,这些类在后台的AsyncTask中由HttpRequest调用。我只想要一件简单的事情,例如:

主屏幕 - >添加屏幕 - 按添加按钮 - >主屏幕

但是当我在数据库中添加一行时,listview将不会刷新。但是,如果我重新启动应用程序,一切都会重新创建,我的列表视图会显示添加的行。

要从数据库中获取信息,我使用以下代码:

class LoadAllBooks extends AsyncTask<String, String, String> {

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

    /**
     * Getting all books from a 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_books, "GET",
                params);

        // Check your log cat for JSON reponse
        Log.d("All Authors: ", 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_BOOKS);

                // Looping through all products
                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);

                    // Storing each JSON item in variable
                    String author = c.getString(TAG_AUTHOR);

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

                    // Adding each child node to HashMap key => value.
                    // map.put(TAG_ID, id);
                    map.put(TAG_AUTHOR, author);

                    // Adding HashList to ArrayList
                    booksList.add(map);
                }
            } else {
                // No products found
            }
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * After completing a background task, dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // Dismiss the dialog after getting all products
        pDialog.dismiss();

        // Updating UI from the background thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                SimpleAdapter adapter = new SimpleAdapter(
                        LoadAllActivity.this, booksList, R.layout.menu_row,
                        new String[] { TAG_ID, TAG_AUTHOR }, new int[] {
                                R.id.id, R.id.book });
                // Updating listview
                setListAdapter(adapter);
            }
        });
    }

我知道在更新booksList时有一种方法可以更新它,但我尝试了很多不同的方式,而且这并不是我认为最简单的方式。

我想解决的方法就是重启主活动,回想一下onCreate(Bundle ...)方法:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

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

    // Loading products in the background thread
    new LoadAllBooks().execute();

    // Get listview
    ListView lv = getListView();

    // On seleting single product
    // Launching Edit Product Screen
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int pos,
                                long id) {
            String author = ((TextView) view.findViewById(R.id.book))
                            .getText().toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(),
                               AuthorTitlesActivity.class);
            // Sending pid to next activity
            in.putExtra(TAG_AUTHOR, author);

            // Starting a new activity and expecting some response back.
            startActivityForResult(in, 100);
        }
    });
}

有没有办法实现这个解决方案?

0 个答案:

没有答案