1

I have a Listview and is working well. I'm getting JSON data from remote server and using SimpleAdapter. Basically I get song list from the server. But now, I want to let user select category first. After selecting any category I want to change the URL depending on the selected category, and then populate the listview again. Like, I'm calling getlist.php to get categories. Now if user selects a category named POP, want to call getlist.php?cat=pop to get all pop songs and re-populate the listview where user will see a list of pop songs.

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

I don't think code is necessary here, if you still need please tell me, I'll update with code given.

Till now I used the following code in onItemClick but not working:

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

So, let me summerise the full thing. On category item click, I want to change the URL I'm getting data from, and refresh the Listview with new data. Thanks in advance.

Code: Please have a look at my code and suggest any change.

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);
                }
            });

        }

    }


}
baske
  • 1,316
  • 9
  • 16
A. K. M. Tariqul Islam
  • 2,824
  • 6
  • 31
  • 48

1 Answers1

1

Judging from the (very minimal) few lines of code you've provided you are loading stuff into your List that is backing your ListView from an AsyncTask (LoadAllProducts?). If that is the case, be sure to update your ListView's data in the onPostExecute() method you should override, and call something like notifyDataSetChanged() when you finished updating.

For more info on how to use AsyncTasks, check the great number of answers on this topic on SO. For instance, I put an answer with some info on AsyncTasks here: progress dialog is not displaying in async task when asynctask is called from separate class

Update after code was added:

OK, I never used a ListActivity before, but after reading some documentation I think the problem is that calling setListAdapter() a second time will not refresh the ListView (as was mentioned here). Instead of creating a new SimpleAdapter every time I think you should update your productList (clear it, add to it, whatever you want) and then call AllRBT.this.adapter.notifyDataSetChanged(). This should trigger the ListView to re-fetch the data from your adapter, which by now contains your new data.

Also some other remarks that will make your code cleaner:

  1. you need not call runOnUiThread() from onPostExecute(), since onPostExecute() is guaranteed to run on the main thread already (as per AsyncTask contract).
  2. I think you don't need to add an OnItemClickListener by yourself. It seems that a ListActivity already does that for you and you can instead simply override its onListItemClick() method.
Community
  • 1
  • 1
baske
  • 1,316
  • 9
  • 16