Question

So i need to set an adpter for my spinner but the information is set on a ArrayList(HashMap(String, String)) and the example ive seen is just stored in an Arraylist how can i change it.

i have:

 public class NewProductActivity extends Activity{




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

ArrayList<HashMap<String, String>> productsList;

// url to get all products list
private static String url_all_estabs =   "http://10.0.2.2/webprojecto4/index_pesagem.php";

// JSON Node names
 private static final String TAG_PRODUCTS = "estab";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "design";
// products JSONArray
JSONArray products = null;

/** WebServices */
private ProgressDialog pDialog;

 JSONParser jsonParser = new JSONParser();
 EditText inputdt_ini;
 EditText inputdt_fim;
 EditText inputDesc;



/**
 * Before starting background thread Show Progress Dialog
 * */
@Override
protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(NewProductActivity.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.makeHttpRequest(url_all_estabs, "GET", 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_ID);
                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_ID, id);
                map.put(TAG_NAME, name);

                // 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() {


            // Locate the spinner in activity_main.xml
            Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);


            // Spinner adapter
            mySpinner
                    .setAdapter(new ArrayAdapter<String>(MainActivity.this,
                            android.R.layout.simple_spinner_dropdown_item,
                            worldlist));


            // Spinner on item click listener
            mySpinner
                    .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()         {

                        @Override
                        public void onItemSelected(AdapterView<?> arg0,
                                View arg1, int position, long arg3) {
                            // TODO Auto-generated method stub
                            // Locate the textviews in activity_main.xml
                            TextView txtrank = (TextView) findViewById(R.id.rank);

                            // Set the text followed by the position

                            txtpopulation.setText(world.get(position).getPopulation());
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> arg0) {
                            // TODO Auto-generated method stub
                        }
                    });
        }

This is what i have, i need to change it to ArrayList(HashMap(String, String))

            // Spinner adapter
            mySpinner
                    .setAdapter(new ArrayAdapter<String>(MainActivity.this,
                            android.R.layout.simple_spinner_dropdown_item,
                            worldlist));

}

Was it helpful?

Solution

// first way to do it
List<String> worldList; // as global variable


// in doInBackground(String... args) {} function instead of this line productsList.add(map);
// use this one :  
protected String doInBackground(String... args) {
   // your code ....
   worldList = new ArrayList<String>(map.values()); // return List object
}

// in onPostExecute(String file_url) function
// then use it in your ArrayAdapter now you are happy
protected void onPostExecute(String file_url) {
   // your code ...
    mySpinner.setAdapter(new ArrayAdapter<String>(MainActivity.this,
                        android.R.layout.simple_spinner_dropdown_item,
                        worldlist));
}

//Value of worldList could be String or Integer what ever you want
//done


// second way to do it
// however you can convert HashMap to array like so
String[] worldArray; // as global variable

// in doInBackground(String... args) {} function instead of this line productsList.add(map);
// use this one :  
protected String doInBackground(String... args) {
   // your code ....
   worldArray = map.values().toArray(new String[map.size()]); // return array   
}


// in onPostExecute(String file_url) function
// then use it in your ArrayAdapter now you are happy
protected void onPostExecute(String file_url) {
   // your code ...
    mySpinner.setAdapter(new ArrayAdapter<String>(MainActivity.this,
                        android.R.layout.simple_spinner_dropdown_item,
                        worldArray ));
}

//done



i show you tow ways to do it coz ArrayAdapter constructor could take array or list,
i hope that's helpfull.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top