Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating ArrayAdapter using xml resource and retrieving "id" or "value" fields using spinner

I am trying to create a spinner, the values of which I am populating from a resource xml, using ArrayAdapter.

I also want to give the resource items some "id" or "value". How can i retrieve these values inside the onItemSelected() callback ?

Here is the Java code.

package com.waus.waus;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class Register extends Activity implements OnItemSelectedListener {

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

        Spinner countrySpinner = (Spinner) findViewById(R.id.country_code_spinner);
        ArrayAdapter<CharSequence> countryAdapter = ArrayAdapter.createFromResource(this, R.array.country_codes, android.R.layout.simple_spinner_item);
        countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        countrySpinner.setOnItemSelectedListener(this);
        countrySpinner.setAdapter(countryAdapter);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View arg1, int pos,
            long arg3) {
        // TODO Auto-generated method stub

        Toast.makeText(this, "THIS IS WHERE I WANT TO SHOW THE ID/VALUE" ,Toast.LENGTH_SHORT).show();

    }

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

    }

}

This is the XML file I want to use.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="country_codes">
        <item value="91">India</item>
        <item value="1">United States</item>
             // OR
        <item id="1">United States</item>

    </string-array>    
</resources>

How can it be done without using 2 resource files. i.e. one for codes and another for names.

like image 368
geekoraul Avatar asked Sep 16 '13 11:09

geekoraul


1 Answers

String[] SortByField= activity.getResources().getStringArray(
                R.array.country_codes);

or

Arrayadapter adapterFillClass = ArrayAdapter.createFromResource(activity,
                R.array.country_codes,
                android.R.layout.simple_spinner_dropdown_item);
spinner.setadapter(adapterFillClass);

i hope it useful to you.

like image 163
dipali Avatar answered Nov 15 '22 05:11

dipali