sara Almaghrabi
sara Almaghrabi

Reputation: 3

setOnItemSelectedListener is not seen in spinner for android

please could you help me to found what is the problem with the following code ! when the item from spinner selected nothing occurs

i.e : the body of spinner.setOnItemSelectedListener is not seen !

code :

 package com.example.spinner;


 import java.util.ArrayList;
 import java.util.List; 
 import org.json.JSONArray;
 import org.json.JSONObject;
 import android.os.Bundle;
 import android.app.Activity;
 import android.util.Log; 
 import android.view.View;
   import android.widget.AdapterView;
   import android.widget.ArrayAdapter;
   import android.widget.Spinner;
   import android.widget.Toast;
   import android.widget.AdapterView.OnItemSelectedListener;

   import java.util.HashMap; 
   import org.apache.http.NameValuePair; 
   import org.json.JSONException; 


   import android.annotation.SuppressLint; 
   import android.content.Intent;
   import android.os.AsyncTask;  
   public class MainActivity extends Activity {


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

        ArrayList<HashMap<String, String>> productsList;


        // url to get all products list
        private static String url_all_products = "http://10.0.2.2/RPM-connect/get_all_patients.php";

        // JSON Node names
        private static final String TAG_SUCCESS = "success";
        private static final String TAG_DOCTOR = "products";

        private static final String TAG_ID = "id";
        private static final String TAG_F_NAME = "F_name";
        private static final String TAG_S_NAME = "S_name";
        private static final String TAG_L_NAME = "L_name"; 

        // products JSONArray
        JSONArray doctor = null;

        ArrayList<String> spinnerArray ;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

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

            spinnerArray = new ArrayList<String>();

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


              Spinner spinner = new Spinner(this);
                              //ArrayAdapter <HashMap<String, String>> spinnerArrayAdapter = new ArrayAdapter<HashMap<String, String>>(

              ArrayAdapter <String> spinnerArrayAdapter = new ArrayAdapter <String >(
                        this, android.R.layout.simple_spinner_item,  spinnerArray );
                spinnerArrayAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );

                spinner = (Spinner) findViewById( R.id.spinner1 );
                spinner.setAdapter(spinnerArrayAdapter);
                spinner.setOnItemSelectedListener(new OnItemSelectedListener(){

                    @Override
                    public void onItemSelected(AdapterView<?> arg0,
                            View arg1, int arg2, long arg3) {


                        Toast.makeText(MainActivity.this, "You have selected : "  , 
                                Toast.LENGTH_SHORT).show();
                    }

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

                    }

                } );
            }




        // 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) { 
                Intent intent = getIntent();
                finish();
                startActivity(intent);
            }

        }

        /**
         * Background Async Task to Load all product by making HTTP Request
         * */
        @SuppressLint("NewApi")
        class LoadAllProducts extends AsyncTask<String, String, String> {

            /**
             * 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_products, "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
                        doctor = json.getJSONArray(TAG_DOCTOR);



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


                            // Storing each json item in variable
                            String ID = c.getString(TAG_ID);
                            String F_name = c.getString(TAG_F_NAME);
                            String S_name = c.getString(TAG_S_NAME);
                            String L_name = c.getString(TAG_L_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_F_NAME, F_name);
                            map.put(TAG_S_NAME, S_name);
                            map.put(TAG_L_NAME, L_name);



                            // adding HashList to ArrayList
                            productsList.add(map);


                            Log.d("Before temp", productsList.toString());

                            spinnerArray.add(F_name + " " +  L_name);
                            // temp[i]=  F_name+" "+L_name ; 
                            Log.d("TT",spinnerArray.get(i) );
                        }



                    } else {
                        // no products found
                        // Launch Add New product Activity
                        Intent i = new Intent(getApplicationContext(),
                                MainActivity.class);
                        // Closing all previous activities
                        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(i);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                return null;
            }


        }


        } 

Upvotes: 0

Views: 1474

Answers (2)

codeMagic
codeMagic

Reputation: 44571

Your ArrayList may not be populated from the AsyncTask before you set the adapter. Implement onPostExecute() in your AsyncTask and call notifyDataSetChanged() on your adapter there. Also, you create a new Spinner then use one that exists in your xml

 Spinner spinner = new Spinner(this);

this is not needed. Just declare your Spinner like this

public class MainActivity extends Activity {
 Spinner spinner;

then initialize it from xml as you are doing later

spinner = (Spinner) findViewById( R.id.spinner1 );

notifyDataSetChanged() Docs

Upvotes: 1

Darwind
Darwind

Reputation: 7371

After your done with loading the items into the SpinnerAdapter inside your AsyncTask you need to tell the Adapter to refresh itself to load the new values.

This can be done by calling: spinnerArrayAdapter.notifyDataSetChanged().

Because the AsyncTask is running on another thread, you will need to implement

@Override
public void onPostExecute(String result) {
    spinnerArrayAdapter.notifyDataSetChanged()
}

and call the spinnerArrayAdapter.notifyDataSetChanged() inside it, as seen above. onPostExecute and onPreExecute is run on the main thread, so they can change Views on the UI thread.

Upvotes: 1

Related Questions