簡體   English   中英

在Android中使用ArrayList填充Spinner

[英]Populating Spinner using ArrayList in Android

我有一個活動,我必須解析XML並使用解析的數據填充Spinner。

我完成了解析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);
                        }


                    }

如果你注意到你可以看到KEY_SETIDKEY_SETNAME到arraylist。 我必須使用KEY_SETNAME填充微調器,並且不會在微調器中顯示KEY_SETID 但是,如果單擊該項,則應獲取與該名稱對應的id,以便發送到服務器。

我有一個填充微調器的方法,如下所示:

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

我應該如何使用解析XML時獲得的ArrayList填充微調器?

這是完整的活動

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


}

這是布局文件

<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>

我該怎么做才能從XML解析方法返回的Arraylist中填充Spinner?

這就是你如何去做。

首先,創建一個POJO MyObject ,它有2個字段KEY_SETIDKEY_SETNAME及其相關的getter/setter 重寫toString() ,返回KEY_SETNAME ,因為您希望在Spinner中將其顯示為項目名稱。

然后從解析XML填充的HashMap創建MyObjectArrayList

然后使用下面的示例代碼段填充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);

現在要選擇項目,請使用以下代碼。

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.

嘗試一下,讓我知道,如果你被困在任何地方。

更新: -

你的POJO會是這樣的。

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

提示:嘗試使代碼變得簡單和有效。首先,在解析函數中而不是向ArrayList添加HashMap 。取兩個arraylists,這些ArrayList應該在類級別聲明。相應地,填充兩個ArrayList和在Spinner click中獲取它們。所以你的Activity代碼代表:

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


}

注意:簡單替換就行了。我只更改了detailsBtn.setOnClickListener(new View.OnClickListener() {代碼detailsBtn.setOnClickListener(new View.OnClickListener() {和你的parseExamList()並在類level.try中聲明了兩個ArrayLists ,看看你是否在點擊時獲得兩個Toast啟動新活動之前的詳細信息按鈕。

更新:我假設您已經按照Android hive教程解析XML。只需在XMLParser類中更改getValue函數:

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

但是如果你不遵循那個......那么按照那個教程來構建解析器就可以解決你的問題.Insha Allah。如果我幫助你找到解決方案那么請把它標記為答案

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

我已經通過將我的代碼xml解析代碼更改為:

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

    }  

但問題是,id和name都顯示在微調器中,我只想顯示名稱並在顯示時隱藏id。 但是后來我會要求帶有所選名稱的id

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM