Rishabh
Rishabh

Reputation: 29

How to set values in spinner dynamically

I am working on an android application. I am able to display values from the database into the listview but i want to display them into the spinner instead of listview. Here is the code which i have written for listview

      package com.example.festipedia_logo;

//import com.actionbarsherlock.app.SherlockFragment;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.example.festipedia_logo.details2.LoadAllProducts;

import android.app.Activity;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class mainpageact extends SherlockFragmentActivity {
     Button button1;
     Button button4;
     ArrayAdapter<String> adapter1;
//      String[] city;
        String loc;
        Spinner spinner;
        String location;
        ArrayAdapter<String> adapter;
        String[] city;
        // Progress Dialog
        private ProgressDialog pDialog;
        String az;
        // Creating JSON Parser object
        JSONParser jParser = new JSONParser();
    EditText b;
//      ArrayList<HashMap<String, String>> productsList;
    ArrayList<String> productsList;
        // url to get all products list
        private static String url_all_products = "http://192.168.0.104:8080/festipedia/sports.php";
    Button a;

        // JSON Node names
        private static final String TAG_SUCCESS = "success";
        private static final String TAG_PRODUCTS = "products";
        private static final String TAG_NAME = "eventname";

        // products JSONArray
        JSONArray products = null;
    ListView l;
//  Spinner spinner;

        //String loc;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        getActionBar().setDisplayShowTitleEnabled(false);
        getActionBar().setDisplayUseLogoEnabled(false);
        getActionBar().setDisplayShowCustomEnabled(true);
        getActionBar().setDisplayShowHomeEnabled(false);
        //getSupportActionBar().setIcon(R.drawable.fest);
        //getSupportActionBar().setLogo(R.drawable.fest);
        Drawable d=getResources().getDrawable(R.drawable.a5);
        getActionBar().setBackgroundDrawable(d);

        setContentView(R.layout.mainmenu);
        spinner = (Spinner)this.findViewById(R.id.spinner1);




            spinner.setAdapter(adapter);
            productsList = new ArrayList<String>();
        //    productsList = new ArrayList<HashMap<String, String>>();
            new LoadAllProducts().execute();

            spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { 
                    location=spinner.getSelectedItem().toString();
                }

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

                }});
//  View rootView = inflater.inflate(R.layout.mainmenu, container, false);
        //Intent in = getIntent();
        //loc = in.getStringExtra("loc");
        Button button1 = (Button) findViewById(R.id.button1);
        Button button4 = (Button) findViewById(R.id.button4);
        Button button2 = (Button) findViewById(R.id.button2);
        Button button5 = (Button) findViewById(R.id.button5);
        Button button3 = (Button) findViewById(R.id.button3);
        //TextView t1= (TextView) findViewById(R.id.getlocation);
        //t1.setText(loc);


        button1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                // creating new product in background thread

                /*final FragmentTransaction ft = getFragmentManager().beginTransaction(); 
                ft.replace(R.id.content_frame,new home1() , "Fest Content"); 
                ft.commit();*/

                Intent i = new Intent(getApplicationContext(),
                        MainActivity.class);
                // Closing all previous activities
                //i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);

                //new CreateNewProduct().execute();
            }
        });
button4.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View view) {
        // creating new product in background thread
    /*  final FragmentTransaction ft = getFragmentManager().beginTransaction(); 
        ft.replace(R.id.content_frame,new testing() , "Fest Content"); 
        ft.commit();*/
        Intent i = new Intent(getApplicationContext(),
                testing.class);
        // Closing all previous activities
        //i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);
        //new CreateNewProduct().execute();
    }
});
button5.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View view) {
        // creating new product in background thread
    /*  final FragmentTransaction ft = getFragmentManager().beginTransaction(); 
        ft.replace(R.id.content_frame,new testing() , "Fest Content"); 
        ft.commit();*/


        Intent i = new Intent(getApplicationContext(),
                search.class);

        startActivity(i);

    }
});

button2.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View view) {
        // creating new product in background thread

        /*final FragmentTransaction ft = getFragmentManager().beginTransaction(); 
        ft.replace(R.id.content_frame,new home1() , "Fest Content"); 
        ft.commit();*/

        Intent i = new Intent(getApplicationContext(),
                MainActivity.class);
        // Closing all previous activities
        //i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);

        //new CreateNewProduct().execute();
    }
}); 

button3.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View view) {
        // creating new product in background thread

        /*final FragmentTransaction ft = getFragmentManager().beginTransaction(); 
        ft.replace(R.id.content_frame,new home1() , "Fest Content"); 
        ft.commit();*/

        Intent i = new Intent(getApplicationContext(),
                CopyMainActivity.class);
        // Closing all previous activities
        //i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        i.putExtra("location", location);

        // starting new activity and expecting some response back
        startActivityForResult(i, 100);
        //startActivity(i);

        //new CreateNewProduct().execute();
    }
}); 

    }
    class LoadAllProducts extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pDialog = new ProgressDialog(mainpageact.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>();
            params.add(new BasicNameValuePair("location", az));

            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

        //  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 name = c.getString(TAG_NAME);
                    //  city[i] = name;
                        String name = c.getString(TAG_NAME);
                        productsList.add(name);
                        //l.setFilterText(id);
                        // 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
                //      productsList.add(map);
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                }
            } 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
                     * */
            //      city = new String[] { "Mumbai", "Chennai",
                //  "Dubai"};

    //   adapter = new ArrayAdapter<String>(mainpageact.this, R.layout.list_item, productsList);    

         //ArrayAdapter<CharSequence> 
                    adapter = new ArrayAdapter<String>(mainpageact.this,R.layout.mainmenu, productsList);
                     spinner.setAdapter(adapter); 
                     adapter.notifyDataSetChanged();
         //spinner.setAdapter(adapter);
                }
            });


        }

    }

}

Upvotes: 0

Views: 5048

Answers (2)

Libin
Libin

Reputation: 17085

There are three issue in your code.

1) Change the productsList declaration as ArrayList( I don't see any need of having HashMap)

So change this line

ArrayList<HashMap<String, String>> productsList;

to

ArrayList<String> productsList;

and instantiate the productsList as

productsList = new ArrayList<String>();

2) In doInBackground() add the response string item directly to the productsList.

String name = c.getString(TAG_NAME);
productsList.add(name);

3) Now the main issue , change the adapter as

 adapter = new ArrayAdapter<String>(this,R.layout.list_item, productsList);
 spinner.setAdapter(adapter);

Upvotes: 0

Luis Lavieri
Luis Lavieri

Reputation: 4129

It seems, that you are not calling notifyDataSetChanged() after you have loaded the Spinner on onPostExecute(). That will tell your adapter that the data of the spinner needs to be refreshed.

So, basically try this:

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
                 * */
        //      city = new String[] { "Mumbai", "Chennai",
            //  "Dubai"};

     adapter = new ArrayAdapter<String>(mainpageact.this, productsList,
                R.layout.list_item, new String[] {
                TAG_NAME},
        new int[] {  R.id.name });  

     adapter.notifyDataSetChanged();
            }
        });


    }

NOTE: When you set the spinner to the adapter on your OnCreate(), the adapter is null at that moment. Try doing it inside the onPostExecute(). Also, try to avoid the use of that Thread inside the AsyncTask. It seems unnecessary, but I might be wrong.

Upvotes: 1

Related Questions