单击项目时重新创建相同的Listview

时间:2014-01-02 12:50:57

标签: android listview android-listview android-asynctask

我有Listview并且运作良好。我从远程服务器获取JSON数据并使用SimpleAdapter。基本上我从服务器获得歌曲列表。但现在,我想让用户先选择类别。选择任何类别后,我想根据所选类别更改URL,然后再次填充列表视图。就像,我正在呼叫getlist.php来获取类别。现在,如果用户选择名为POP的类别,则要调用getlist.php?cat=pop以获取所有流行歌曲并重新填充列表视图,用户将看到流行歌曲列表。

private static String url_json = "http://10.0.2.2/aaa/getlist.php"; //this gives only the categories
private static String url_json = "http://10.0.2.2/aaa/getlist.php?cat=pop"; //this gives all songs those are under category pop

我觉得这里不需要代码,如果你仍然需要请告诉我,我会用给出的代码进行更新。

直到现在我在onItemClick中使用了以下代码但没有工作:

categorySelected = true;
url_json += "?c=Bangla";
new LoadAllProducts().execute();
lv.invalidateViews(); //final ListView lv = getListView();

所以,让我夏天完整的事情。在类别项目点击时,我想更改URL我从中获取数据,并使用新数据刷新Listview。提前谢谢。

代码:请查看我的代码并提出更改建议。

public class AllRBT extends ListActivity {

    // Progress Dialog
    private ProgressDialog pDialog;


    ArrayList<HashMap<String, String>> productsList;

    // url to get all products list
    //private static String url_all_products = "http://aloashbei.com.bd/vasonapps/getList.php";
    private static String url_all_products = "http://10.0.2.2/aaa/getlist.php";
    private static Boolean categorySelected = false;
    private static String confTitle = "Confirmation needed !";
    private static String confBody = "We want to send message from next time you select any ring back tone. This may cost 15 taka by your network operator.";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "rbts";
    private static final String TAG_PID = "code";
    private static final String TAG_NAME = "name";
    private static final String TAG_ARTIST = "artist";
    private String mobileNumber = "";

    // products JSONArray
    JSONArray products = null;

    private EditText inputSearch;
    SimpleAdapter adapter;
    //ListAdapter adapter;

    ///////////////////////////////////////////////////////////////////////////////////////////////////    
    private void getMobileNumber(){
        AlertDialog.Builder alert = new AlertDialog.Builder(this);

        alert.setTitle(confTitle);
        alert.setMessage(confBody);//Are you sure want to buy this ring back tones?

        // Set an EditText view to get user input 
        //final EditText input = new EditText(this);
        //alert.setView(input);

        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
          //String m = input.getText().toString();
          // Do something with value!
          mobileNumber = "017";

          }
        });

        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton) {
            // Canceled.
              mobileNumber = "";
          }
        });
        alert.show();
    }

    public String[] generateMessage(String number, int code){
        String opCode = number.substring(0, 3);
        String messageBody = "", destination = "";
        String[] returnValue;
        if(opCode.equals("015")){
            messageBody = "TT "+code;
            destination = "5000";
        }else if(opCode.equals("017")){
            messageBody = "WT "+code;
            destination = "4000";
        }else if(opCode.equals("019")){
            messageBody = ""+code;
            destination = "2222";
        }else if(opCode.equals("016")){
            messageBody = "CT "+code;
            destination = "3123";
        }else if(opCode.equals("018")){
            messageBody = "GET  "+code;
            destination = "8466";
        }else if(opCode.equals("011")){
            messageBody = "Get"+code;
            destination = "9999";
        }else{
            messageBody = "Invalid number";
        }

        return new String[] {messageBody, destination};
    }

    private void sendMessage(String dest, String body, String popupText){
        if(popupText != "")
            Toast.makeText(getApplicationContext(), popupText, Toast.LENGTH_LONG).show();

        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(dest, null, body, null, null);
    }
    ///////////////////////////////////////////////////////////////////////////////////////////////////

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

        //setContentView(R.layout.activity_all_rbt);
        //filterText = (EditText) findViewById(R.id.search_box);
        //filterText.addTextChangedListener(filterTextWatcher);
        //setListAdapter(new ArrayAdapter<String>(this,
                //android.R.layout.list_content, 
                //getStringArrayList());

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

        //filter listView
        inputSearch = (EditText) findViewById(R.id.inputSearch);
        inputSearch.addTextChangedListener(new TextWatcher() {             
            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3){
                // When user changed the Text
                AllRBT.this.adapter.getFilter().filter(cs);
            }             
            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }

            @Override
            public void afterTextChanged(Editable arg0) {
            }
        });

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

        // Get listview
        final ListView lv = getListView();

        // on seleting single product
        // launching Edit Product Screen
        lv.setOnItemClickListener(new OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id){
                //lv.invalidateViews();

                //if(false){
                    categorySelected = true;
                    url_all_products += "?c=Bangla";
                    new LoadAllProducts().execute();
                    lv.invalidateViews();
                //}

                //Context context = getApplicationContext();
                String[] values;
                // getting values from selected ListItem
                String pid = ((TextView) view.findViewById(R.id.pid)).getText().toString();
                if(mobileNumber == ""){
                    getMobileNumber();
                    return;
                }


                values = generateMessage(mobileNumber, Integer.parseInt(pid));
                String popup = "Sending message '"+values[0]+"' to "+values[1];
                sendMessage(values[1], values[0], popup);
                //Toast toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
                //toast.show();
            }
        }); 
    }


    // Response from Edit Product Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received
            // means user edited/deleted product
            // reload this screen again
            Intent intent = getIntent();
            finish();
            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(AllRBT.this);
            pDialog.setMessage("Loading ring back tones. 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
            //Toast toast = Toast.makeText(getApplicationContext(), "text", Toast.LENGTH_LONG);
            //toast.show();

            JSONParser jParser = new JSONParser();
            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);


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

            try {
                // Checking for SUCCESS TAG
                int success = 1;//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 artist = c.getString(TAG_ARTIST);

                        // 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_ARTIST, artist);

                        // adding HashList to ArrayList
                        productsList.add(map);
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    //Intent i = new Intent(getApplicationContext(),
                      //      NewProductActivity.class);
                    // Closing all previous activities
                    //i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    //startActivity(i);
                }
            } 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
                     * */
                    AllRBT.this.adapter = new SimpleAdapter(
                            AllRBT.this, productsList,
                            R.layout.list_item, new String[] { TAG_PID, TAG_NAME, TAG_ARTIST}, new int[] { R.id.pid, R.id.name, R.id.artist });
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }

    }


}

1 个答案:

答案 0 :(得分:1)

从您提供的(非常极少的)几行代码判断,您正在将内容加载到从List(LoadAllProducts?)支持ListView的{​​{1}}中。如果是这种情况,请务必使用您应覆盖的AsyncTask方法更新ListView的数据,并在完成更新后调用类似onPostExecute()的内容。

有关如何使用AsyncTasks的更多信息,请在SO上查看有关此主题的大量答案。例如,我在这里给出了一些关于AsyncTasks的信息答案:progress dialog is not displaying in async task when asynctask is called from separate class

添加代码后更新:

好的,我之前从未使用notifyDataSetChanged(),但在阅读了一些文档之后,我认为问题是第二次调用ListActivity将不会刷新ListView(如前所述here )。每次我认为你应该更新setListAdapter()(清除它,添加它,无论你想要什么),而不是创建一个新的SimpleAdapter,然后调用productList。这应该会触发AllRBT.this.adapter.notifyDataSetChanged()从适配器重新获取数据,该数据现在包含新数据。

还有其他一些可以使您的代码更清晰的评论:

  1. 您无需从ListView致电runOnUiThread(),因为onPostExecute()已保证在主线程上运行(根据onPostExecute()合约)。
  2. 我认为您不需要自己添加AsyncTask。似乎OnItemClickListener已经为您执行了此操作,您可以简单地覆盖其ListActivity方法。