Populating Spinner using ArrayList in Android

31,099

Solution 1

I have done a workaround by changing my code xml parsing code to this:

void parse_ExamList()
{

ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
    XMLParser parser = new XMLParser();
    Document doc = parser.getDomElement(xmlContent); // getting DOM element

    //list object to populate spinner
    List<String> list = new ArrayList<String>();

    NodeList nl = doc.getElementsByTagName(KEY_EXAMSET);
    // looping through all item nodes <item>
    for ( int i = 0; i < nl.getLength();i++) {



    // creating new HashMap
    HashMap<String, String> map = new HashMap<String, String>();

    Element e = (Element) nl.item(i);
    // adding each child node to HashMap key => value
    //map.put(KEY_EXAMSET, parser.getValue(e, KEY_EXAMSET));
    map.put(KEY_SETID, parser.getValue(e, KEY_SETID));
    map.put(KEY_SETNAME, parser.getValue(e, KEY_SETNAME));
    //adding items to spinners
    list.add("("+parser.getValue(e, KEY_SETID)+") "+parser.getValue(e, KEY_SETNAME));
    menuItems.add(map);
    }

    //populating the spinner with the list items
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
    android.R.layout.simple_spinner_item, list);
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    exam_list_spinner.setAdapter(dataAdapter);

    }  

But the problem is that, both the id and name are getting displayed in the spinner, I just want to show the name and hide the id while displaying. But later I will require the id with the selected name

Solution 2

This is how you can go about doing it.

First, create a POJO MyObject, which has the 2 fields KEY_SETID and KEY_SETNAME and its related getter/setter. Override the toString(), to return KEY_SETNAME, as you want to display this as the item name in the Spinner.

Then create an ArrayList of your MyObject, from the HashMap you populated by parsing your XML.

Then using the sample code snippet below, populate data in your Spinner.

Spinner s = (Spinner) findViewById(R.id.SpinnerSpcial);
ArrayList<MyObject> objects = new ArrayList<MyObject>(); // This is actually the list created from the HashMap
ArrayAdapter<MyObject> adapter = new ArrayAdapter<ObjectName>(this, android.R.layout.simple_spinner_item, objects);
s.setAdapter(adapter);

Now to get the item selected, use the below code.

MyObject selectedItem = (MyObject) s.getSelectedItem(); // Object which was selected.
selectedItem.getKEY_SETID(); // This will give you the ID of the item selected. Do whatever you wish with to do.

Try it out and let me know, if you're stuck up anywhere.

Update:-

Your POJO will be like this.

public class MyObject {
    private String KEY_SETID;
    private String KEY_SETNAME;

    public String getKEY_SETID() {
        return KEY_SETID;
    }

    public void setKEY_SETID(String kEY_SETID) {
        KEY_SETID = kEY_SETID;
    }

    public String getKEY_SETNAME() {
        return KEY_SETNAME;
    }

    public void setKEY_SETNAME(String kEY_SETNAME) {
        KEY_SETNAME = kEY_SETNAME;
    }

    @Override
    public String toString() {
        return this.KEY_SETNAME; // Value to be displayed in the Spinner
    }
}

Solution 3

Tip:Try to make the code simple and working.So first,in your parsing function instead of adding a HashMap to the ArrayList .. take two arraylists and these ArrayLists should be declared at a class level.Correspondingly,fill both ArrayLists and fetch them at Spinner click.So your Activity code stands:

    public class SpeedTestExamNameActivity extends Activity {

        Spinner exam_list_spinner;
        Button  detailsBtn;
        TextView showUser;
    String full_name;
    ArrayList<String> menuItems = new ArrayList<String>();
    ArrayList<String> menuKeys = new ArrayList<String>();

    //variables to get response from server
    String responseBody;

    //variables required for parsing the XML
    String xmlContent=null;

     // XML node keys
        static final String KEY_EXAMSET = "ExamSet"; // parent node
        static final String KEY_SETID = "SetId";
        static final String KEY_SETNAME = "SetName";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_speed_test_exam_name);

        //checking internet connectivity to download list
        isOnline_downloadList();

        //Showing user full name after login
        full_name=getFromPreference("user_name");
        //textview to show user name
        showUser=(TextView)findViewById(R.id.speed_username_textView);
        showUser.setText("Welcome, "+full_name);
        //spinner
        exam_list_spinner = (Spinner) findViewById(R.id.speed_examlist_spinner);
        //adding items to spinners
        addItemsOnExamListSpinner();

        // onclick details button
        detailsBtn = (Button) findViewById(R.id.speed_exam_details_button);
        detailsBtn.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        Toast.makeText(SpeedTestExamNameActivity.this,                      
                                "Exam List Spinner: "+ 

    String.valueOf(exam_list_spinner.getSelectedItem()),
                                    Toast.LENGTH_SHORT).show();
    //here you get the menuKey too
    Toast.makeText(SpeedTestExamNameActivity.this,                      
                                    "Exam List Spinner Key: "+ menuKeys.get(exam_list_spinner.getSelectedItemPosition()),
                                    Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(SpeedTestExamNameActivity.this, SpeedTestActivity.class);
                        SpeedTestExamNameActivity.this.startActivity(intent);
                    }
                  });
    }



    //getting content from preferences
        public String getFromPreference(String variable_name)
        {
            String preference_return;
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
            preference_return = preferences.getString(variable_name,"");

           return preference_return;
        }


        //check connection
        public boolean isOnline_downloadList() {
            ConnectivityManager cm =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if (netInfo != null && netInfo.isConnectedOrConnecting()) {

                //sending request for login
                new MyAsyncTask().execute(getFromPreference("student_code"));



                return true;
            }

          //alert box to show internet connection error
            AlertDialog.Builder Internet_Alert = new AlertDialog.Builder(SpeedTestExamNameActivity.this);
            // set title
            Internet_Alert.setCancelable(false);
            Internet_Alert.setTitle("Attention!");
            Internet_Alert.setMessage("This application requires internet connectivity, no internet connection detected");
            Internet_Alert.setPositiveButton("Quit", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) 
                {
                    Intent intent = new Intent(Intent.ACTION_MAIN);
                    intent.addCategory(Intent.CATEGORY_HOME);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    onQuitPressed(); 
                }
            });

            Internet_Alert.create().show();
            return false;
        }

        //to remove application from task manager
        public void onQuitPressed() {

            int pid = android.os.Process.myPid();
            android.os.Process.killProcess(pid);
        }



        //===================================================================================================================================
        //sending student code to server to get exam list
        //===================================================================================================================================
        private class MyAsyncTask extends AsyncTask<String, Integer, Double>{


            @Override
            protected Double doInBackground(String... params) {
                // TODO Auto-generated method stub
                postData(params[0]);
                return null;
            }

            protected void onPostExecute(Double result){

                //Toast.makeText(getApplicationContext(), responseBody, Toast.LENGTH_LONG).show();
                //Log.i("response: ", responseBody);
                //processResponce(responseBody);
                //going to next activity
                xmlContent=responseBody;
                parse_ExamList();
            }

            protected void onProgressUpdate(Integer... progress){

            }

            public void postData(String student_code) {
                // Create a new HttpClient and Post Header
                HttpClient httpclient = new DefaultHttpClient();
                //HttpPost httppost = new HttpPost("http://icaerp.com/AndroidDataService/dataServiceAndroid.asmx/login");

                SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(SpeedTestExamNameActivity.this);
                  final String url_first = preferences.getString("URLFirstPart","");
                HttpPost httppost = new HttpPost(url_first+"ExamList");

                try {
                    // Data that I am sending
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                    nameValuePairs.add(new BasicNameValuePair("StudentCode", student_code));
                    //nameValuePairs.add(new BasicNameValuePair("Password", passwrd));
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    // Execute HTTP Post Request
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost);
                    responseBody = EntityUtils.toString(response.getEntity());

                    Log.d("result", responseBody);
                } 
                catch (Throwable t ) {
                    //Toast.makeText( getApplicationContext(),""+t,Toast.LENGTH_LONG).show();
                    Log.d("Error Time of Login",t+"");
                } 
            }
        }
        //===================================================================================================================================
        //END sending EmailAddress and Password to server 
        //===================================================================================================================================

        // function to populate SPINNER with exam list from xml
                    void parse_ExamList()
                    {



                        XMLParser parser = new XMLParser();
                        //String xml = parser.getXmlFromUrl(URL); // getting XML
                        Document doc = parser.getDomElement(xmlContent); // getting DOM element

                        //count_questions=2;

                        NodeList nl = doc.getElementsByTagName(KEY_EXAMSET);
                        // looping through all item nodes <item>
                        for ( int i = 0; i < nl.getLength();i++) {


//                      while(counter< nl.getLength())
//                      {

                            Element e = (Element) nl.item(i);
                            // adding each child node to HashMap key => value
                            //map.put(KEY_EXAMSET, parser.getValue(e, KEY_EXAMSET));
                            menuKeys.add( parser.getValue(e, KEY_SETID));
                            menuItems.add( parser.getValue(e, KEY_SETNAME));
                            //Log.i("Set ID: ", parser.getValue(e, KEY_SETID));
                            //Log.i("Set Name: ", parser.getValue(e, KEY_SETNAME));


                        }


                    }

                    // add items into exam list spinner dynamically
                    public void addItemsOnExamListSpinner()
                    {
                        List<String> list = new ArrayList<String>();
                        list.add("Speed Test 150(min) PO Set-01");

                        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                        android.R.layout.simple_spinner_item, menuItems);
                        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        exam_list_spinner.setAdapter(dataAdapter);
                    }


}

Note: Simple replace will do.I have only changed code in detailsBtn.setOnClickListener(new View.OnClickListener() { and your parseExamList() and just declared two ArrayLists at the class level.try it and see if you get two Toasts on Clicking details button before launching the new activity.

UPDATE: i assume that you've followed the android hive tutorial for parsing XML.Just change the getValue function with this in your XMLParser class:

public String getValue(Element item, String str) {
    NodeList n = item.getElementsByTagName(str);
    return this.getElementValue(n.item(0));
}

But in case you're not following that.. then following that tutorial to build the parser would solve your issue.Insha Allah.If i have helped you to reach a solution then please mark it as an answer

Solution 4

Spinner spinnerLocation;
spinnerLocation = (Spinner)findViewById(R.id.spinnerLocation);
    ArrayList<String> locationArray = new ArrayList<String>();
    for(int i=0;i<10;i++)
    {
        locationArray.add("value "+i);
    } 
    ArrayAdapter<String> locationAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, locationArray);
            locationAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinnerLocation = (Spinner)findViewById(R.id.spinnerLocation);
            spinnerLocation.setAdapter(locationAdapter);
            spinnerLocation.setAdapter(locationAdapter);
            spinnerLocation.setOnItemSelectedListener(new OnItemSelectedListener() {
                int count=0;
                @Override
                public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) 
            {
                    System.out.println("whatever you wanna do");


                }
                @Override
                public void onNothingSelected(AdapterView<?> arg0) {
                    Toast.makeText(getBaseContext(),"inside no item selected ",Toast.LENGTH_SHORT).show();
                }
            });
Share:
31,099
kittu88
Author by

kittu88

I am an android, Phonegap and Titanium Appcelerator Developer

Updated on March 15, 2020

Comments

  • kittu88
    kittu88 about 4 years

    I have an activity in which I have to parse an XML and populate a Spinner using the parsed data.

    I am done with parsing the XML. This is the method:

    void parse_ExamList()
                        {
    
                            ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
    
                            XMLParser parser = new XMLParser();
                            //String xml = parser.getXmlFromUrl(URL); // getting XML
                            Document doc = parser.getDomElement(xmlContent); // getting DOM element
    
                            //count_questions=2;
    
                            NodeList nl = doc.getElementsByTagName(KEY_EXAMSET);
                            // looping through all item nodes <item>
                            for ( int i = 0; i < nl.getLength();i++) {
    
    
    //                      while(counter< nl.getLength())
    //                      {
                                // creating new HashMap
                                HashMap<String, String> map = new HashMap<String, String>();
    
                                Element e = (Element) nl.item(i);
                                // adding each child node to HashMap key => value
                                //map.put(KEY_EXAMSET, parser.getValue(e, KEY_EXAMSET));
                                map.put(KEY_SETID, parser.getValue(e, KEY_SETID));
                                map.put(KEY_SETNAME, parser.getValue(e, KEY_SETNAME));
                                //Log.i("Set ID: ", parser.getValue(e, KEY_SETID));
                                //Log.i("Set Name: ", parser.getValue(e, KEY_SETNAME));
    
                                menuItems.add(map);
                            }
    
    
                        }
    

    If you notice you can see that KEY_SETID and KEY_SETNAME to the arraylist. I have to populate the spinner with the KEY_SETNAME and the KEY_SETID will not be shown in the spinner. But if the item is clicked then the id corresponding to the name should be acquired in order to send to the server.

    I have a method to populate a spinner, like this:

    // add items into exam list spinner dynamically
                        public void addItemsOnExamListSpinner()
                        {
                            List<String> list = new ArrayList<String>();
                            list.add("Speed Test 150(min) PO Set-01");
    
                            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                            android.R.layout.simple_spinner_item, list);
                            dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                            exam_list_spinner.setAdapter(dataAdapter);
                        }
    

    How should I populate the spinner with the ArrayList that is obtained while parsing the XML?

    This is the full activity:

    public class SpeedTestExamNameActivity extends Activity {
    
        Spinner exam_list_spinner;
        Button  detailsBtn;
        TextView showUser;
        String full_name;
    
        //variables to get response from server
        String responseBody;
    
        //variables required for parsing the XML
        String xmlContent=null;
    
     // XML node keys
        static final String KEY_EXAMSET = "ExamSet"; // parent node
        static final String KEY_SETID = "SetId";
        static final String KEY_SETNAME = "SetName";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_speed_test_exam_name);
    
            //checking internet connectivity to download list
            isOnline_downloadList();
    
            //Showing user full name after login
            full_name=getFromPreference("user_name");
            //textview to show user name
            showUser=(TextView)findViewById(R.id.speed_username_textView);
            showUser.setText("Welcome, "+full_name);
            //spinner
            exam_list_spinner = (Spinner) findViewById(R.id.speed_examlist_spinner);
            //adding items to spinners
            addItemsOnExamListSpinner();
    
            // onclick details button
            detailsBtn = (Button) findViewById(R.id.speed_exam_details_button);
            detailsBtn.setOnClickListener(new View.OnClickListener() {
    
                        @Override
                        public void onClick(View v) {
    
                            Toast.makeText(SpeedTestExamNameActivity.this,                      
                                    "Exam List Spinner: "+ String.valueOf(exam_list_spinner.getSelectedItem()),
                                    Toast.LENGTH_SHORT).show();
    
                            Intent intent = new Intent(SpeedTestExamNameActivity.this, SpeedTestActivity.class);
                            SpeedTestExamNameActivity.this.startActivity(intent);
                        }
                      });
        }
    
    
    
        //getting content from preferences
            public String getFromPreference(String variable_name)
            {
                String preference_return;
                SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
                preference_return = preferences.getString(variable_name,"");
    
               return preference_return;
            }
    
    
            //check connection
            public boolean isOnline_downloadList() {
                ConnectivityManager cm =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo netInfo = cm.getActiveNetworkInfo();
                if (netInfo != null && netInfo.isConnectedOrConnecting()) {
    
                    //sending request for login
                    new MyAsyncTask().execute(getFromPreference("student_code"));
    
    
    
                    return true;
                }
    
              //alert box to show internet connection error
                AlertDialog.Builder Internet_Alert = new AlertDialog.Builder(SpeedTestExamNameActivity.this);
                // set title
                Internet_Alert.setCancelable(false);
                Internet_Alert.setTitle("Attention!");
                Internet_Alert.setMessage("This application requires internet connectivity, no internet connection detected");
                Internet_Alert.setPositiveButton("Quit", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) 
                    {
                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.addCategory(Intent.CATEGORY_HOME);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        onQuitPressed(); 
                    }
                });
    
                Internet_Alert.create().show();
                return false;
            }
    
            //to remove application from task manager
            public void onQuitPressed() {
    
                int pid = android.os.Process.myPid();
                android.os.Process.killProcess(pid);
            }
    
    
    
            //===================================================================================================================================
            //sending student code to server to get exam list
            //===================================================================================================================================
            private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
    
    
                @Override
                protected Double doInBackground(String... params) {
                    // TODO Auto-generated method stub
                    postData(params[0]);
                    return null;
                }
    
                protected void onPostExecute(Double result){
    
                    //Toast.makeText(getApplicationContext(), responseBody, Toast.LENGTH_LONG).show();
                    //Log.i("response: ", responseBody);
                    //processResponce(responseBody);
                    //going to next activity
                    xmlContent=responseBody;
                    parse_ExamList();
                }
    
                protected void onProgressUpdate(Integer... progress){
    
                }
    
                public void postData(String student_code) {
                    // Create a new HttpClient and Post Header
                    HttpClient httpclient = new DefaultHttpClient();
                    //HttpPost httppost = new HttpPost("http://icaerp.com/AndroidDataService/dataServiceAndroid.asmx/login");
    
                    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(SpeedTestExamNameActivity.this);
                      final String url_first = preferences.getString("URLFirstPart","");
                    HttpPost httppost = new HttpPost(url_first+"ExamList");
    
                    try {
                        // Data that I am sending
                        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                        nameValuePairs.add(new BasicNameValuePair("StudentCode", student_code));
                        //nameValuePairs.add(new BasicNameValuePair("Password", passwrd));
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    
                        // Execute HTTP Post Request
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        HttpResponse response = httpclient.execute(httppost);
                        responseBody = EntityUtils.toString(response.getEntity());
    
                        Log.d("result", responseBody);
                    } 
                    catch (Throwable t ) {
                        //Toast.makeText( getApplicationContext(),""+t,Toast.LENGTH_LONG).show();
                        Log.d("Error Time of Login",t+"");
                    } 
                }
            }
            //===================================================================================================================================
            //END sending EmailAddress and Password to server 
            //===================================================================================================================================
    
            // function to populate SPINNER with exam list from xml
                        void parse_ExamList()
                        {
    
                            ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
    
                            XMLParser parser = new XMLParser();
                            //String xml = parser.getXmlFromUrl(URL); // getting XML
                            Document doc = parser.getDomElement(xmlContent); // getting DOM element
    
                            //count_questions=2;
    
                            NodeList nl = doc.getElementsByTagName(KEY_EXAMSET);
                            // looping through all item nodes <item>
                            for ( int i = 0; i < nl.getLength();i++) {
    
    
    //                      while(counter< nl.getLength())
    //                      {
                                // creating new HashMap
                                HashMap<String, String> map = new HashMap<String, String>();
    
                                Element e = (Element) nl.item(i);
                                // adding each child node to HashMap key => value
                                //map.put(KEY_EXAMSET, parser.getValue(e, KEY_EXAMSET));
                                map.put(KEY_SETID, parser.getValue(e, KEY_SETID));
                                map.put(KEY_SETNAME, parser.getValue(e, KEY_SETNAME));
                                //Log.i("Set ID: ", parser.getValue(e, KEY_SETID));
                                //Log.i("Set Name: ", parser.getValue(e, KEY_SETNAME));
    
                                menuItems.add(map);
                            }
    
    
                        }
    
                        // add items into exam list spinner dynamically
                        public void addItemsOnExamListSpinner()
                        {
                            List<String> list = new ArrayList<String>();
                            list.add("Speed Test 150(min) PO Set-01");
    
                            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                            android.R.layout.simple_spinner_item, list);
                            dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                            exam_list_spinner.setAdapter(dataAdapter);
                        }
    
    
    }
    

    This is the layout file:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context=".SpeedTestExamNameActivity" >
    
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="30dp"
            android:text="@string/speed_choose_exam"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    
        <Spinner
            android:id="@+id/speed_examlist_spinner"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/textView1"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="68dp" />
    
        <Button
            android:id="@+id/speed_exam_details_button"
            android:layout_width="95dp"
            android:layout_height="wrap_content"
            android:layout_below="@+id/speed_examlist_spinner"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="36dp"
            android:text="@string/details" />
    
        <TextView
            android:id="@+id/speed_username_textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:text="Name Title"
            android:textAppearance="?android:attr/textAppearanceSmall" />
    
    </RelativeLayout>
    

    What should I do to populate the Spinner from the Arraylist returned by the XML parsing method?

  • kittu88
    kittu88 about 11 years
    menuKeys.put(KEY_SETID, parser.getValue(e, KEY_SETID)); menuItems.put(KEY_SETNAME, parser.getValue(e, KEY_SETNAME)); Here i am getting an error like: The method getValue(Element, String) in the type XMLParser is not applicable for the arguments (Element, String)
  • kittu88
    kittu88 about 11 years
    What is spinnerLocation = (Spinner)findViewById(R.id.spinnerLocation);?
  • kittu88
    kittu88 about 11 years
    The array list which you are using is different from mine. Where should I put this code? How should I use it?
  • Hussain Akhtar Wahid 'Ghouri'
    Hussain Akhtar Wahid 'Ghouri' about 11 years
    i have used mine array . you can simply use your ArrayList , locationArray you can replace by your own array
  • kittu88
    kittu88 about 11 years
    your arraylist is like this: ArrayList<String> locationArray = new ArrayList<String>(); But mine is like this: ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
  • Hussain Akhtar Wahid 'Ghouri'
    Hussain Akhtar Wahid 'Ghouri' about 11 years
    @kittu88 : Hashmap<String,String> , you might be wanting only one of the String , store the desired String in locationArray
  • kittu88
    kittu88 about 11 years
    The way you are using your ArrayList, I can not use it in the same way. If I pass my ArrayList in place of yours, ide is asking me to change my ArrayList
  • kittu88
    kittu88 about 11 years
    Actually, I want the id and the name, which makes two strings, I have to show the name in the spinner, but the id will be required while picking up the selected item from the spinner
  • kittu88
    kittu88 about 11 years
    Can you please elaborate the process?
  • Hussain Akhtar Wahid 'Ghouri'
    Hussain Akhtar Wahid 'Ghouri' about 11 years
  • Nezam
    Nezam about 11 years
    sorry i missed that change over there.. see the change of code in parseExamList() .. changed to menuKeys.add( parser.getValue(e, KEY_SETID)); menuItems.add(parser.getValue(e, KEY_SETNAME));.Hope that solves your issue Insha Allaah
  • kittu88
    kittu88 about 11 years
    Still getting this error: The method getValue(Element, String) in the type XMLParser is not applicable for the arguments (Element, String) for menuKeys.add( parser.getValue(e, KEY_SETID)); menuItems.add( parser.getValue(e, KEY_SETNAME));
  • Rahul
    Rahul about 11 years
    what part of the process are you stuck at? Because I've explained it in a pretty detailed manner.
  • kittu88
    kittu88 about 11 years
    I want to know the requirement of the POJO
  • kittu88
    kittu88 about 11 years
    Its working, but the spinner is showing only 1 tem from the XML file, whereas there should be 3 items in the spinner
  • kittu88
    kittu88 about 11 years
    I also do not want the position of the spinner item selected, but I want the parser.getValue(e, KEY_SETID) value
  • Rahul
    Rahul about 11 years
    it should be the POJO you want to have. A java object with just 2 fields.
  • Nezam
    Nezam about 11 years
    menuKeys.get(exam_list_spinner.getSelectedItemPosition()) try to understand.Thats EXACTLY what you are getting.. you are getting the Key which you added not 0,1,2,3...
  • Nezam
    Nezam about 11 years
    You need to set breakpoints in the code in the for loop and see why only one arraylist item is added.We do not have your XML so i cant tell.. your issue is solved.
  • kittu88
    kittu88 about 11 years
    But why is only 1 item showing up in the spinner when the XML has 3 items?
  • Nezam
    Nezam about 11 years
    did you check setting breakpoints in that place ? is the ArrayList having only one item added or does it have 3 items?
  • Nezam
    Nezam about 11 years
    tell me is it showing just this:Speed Test 150(min) PO Set-01
  • Nezam
    Nezam about 11 years
    see the edit i changed a single variable in the fourth line from the last.. check it.. stackoverflow.com/posts/15404595/revisions and this is an end to your issue.Inshallah..finally
  • kittu88
    kittu88 about 11 years
    Now its not even populating the spinner
  • Nezam
    Nezam about 11 years
    theres something more to it than meets the eye.. are you sure thats all the code which you are using without alterations?
  • kittu88
    kittu88 about 11 years
    yup dude! I am using the same code. But I think the method public void addItemsOnExamListSpinner() might not be used. I have done a workaround but its not full proof. You may take a look into this: stackoverflow.com/a/15406954/1627599
  • Nezam
    Nezam about 11 years
    well i gave a better solution than the workaround.. you can roll back to the last change which i told you,which was showing single item and put breakpoints and debug to find the problem.Its all clear from my end.