listactivity中的Android-listview没有得到更新

时间:2015-03-22 08:04:04

标签: android android-listview

这里我实现了list活动中的searchview,并将服务器数据库中的值检索到listview中。但问题是每当我搜索时,listview没有用新项目更新现有项目,它会使listview中的所有项目都存在和新项目。 这是我的代码

public class ListResult extends ListActivity {


private ProgressDialog pDialog;

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

ArrayList<HashMap<String, String>> idiomsList;

// url to get the idiom list
private static String url_search = "http://192.168.43.192/policephp/listhome.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_IDIOMS = "idioms";
private static final String TAG_NAME = "name";


// products JSONArray
JSONArray idioms = null;
//search key value
public String searchkey;
ListView lv;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_listhome);   
      //Intent myIntent = getIntent(); 
     // gets the arguments from previously created intent
    //searchkey = myIntent.getStringExtra("keyword");
    if(android.os.Build.VERSION.SDK_INT>9)
        {
            StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }


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

    // Loading idioms in Background Thread
   // new LoadIdioms().execute();

    // Get listview
    lv = getListView();

    // on seleting single idioms
    // to do something 
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.name)).getText()
                    .toString();
            Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
            Intent i=new Intent(ListResult.this,PersonalDetails.class);
            i.putExtra("uname",name);

            startActivity(i);

        }
    });



}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);

    // Associate searchable configuration with the SearchView
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
    searchView.setSearchableInfo(searchManager
            .getSearchableInfo(getComponentName()));




            searchView.setOnQueryTextListener(new OnQueryTextListener() {

                public boolean onQueryTextChange(String query) {
                    searchkey=query;
                    new LoadIdioms().execute();
                    lv = getListView();

                    return true;

            }

                @Override
                public boolean onQueryTextSubmit(String query) {

                    return true;
                }

            });









    return super.onCreateOptionsMenu(menu);




}



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

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

    /**
     * getting Idioms from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        //value captured from previous intent
        params.add(new BasicNameValuePair("keyword", searchkey));
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_search, "GET", params);

        // Check your log cat for JSON response
        Log.d("Search idioms: ", json.toString());
       // Toast.makeText(getApplicationContext(), json.toString(), Toast.LENGTH_LONG).show();

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

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

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

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


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

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


                    // adding HashList to ArrayList
                    idiomsList.add(map);
                }
            } else {
                // no idioms found
                //do something
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        //return "success";
        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting the related idioms
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        ListResult.this, idiomsList,
                        R.layout.list_item, new String[] { TAG_NAME},
                        new int[] { R.id.name});
                // updating listview
                setListAdapter(adapter);
            }
        });

    }



  }
@Override
protected void onStop() {
    super.onStop();

    if(pDialog!= null)
        pDialog.dismiss();
}
  }

请帮助我以理想的方式更新我的代码...

1 个答案:

答案 0 :(得分:0)

您必须在onPreExecute()方法

中再次重新初始化ArrayList
idiomsList = new ArrayList<HashMap<String, String>>();

doInBackground()范围内,arraylist不断在旧记录中添加记录。

另外,我建议您不要在runOnUIthread()方法中编写onPostExecute(),因为它已在UI线程上运行。

相关问题