Question

I am new to android. I am displaying strings in my spinner and when user selects a string, i want to enter selected spinner string value using edit text view(when user select food item from spinner i want to enter food's value 10 using edit text view). I am done with setting up the spinner items but i don't know how to enter selected spinner value.

this is my java file,

public class PaymentsActivity extends Activity implements OnItemSelectedListener {

private Button btnViewExpenses;
private Spinner spinner;
private EditText selectedSpinner;
// array list for spinner adapter
private ArrayList<Category> categoriesList;
ProgressDialog pDialog;

// API urls
// Url to get all categories
private String URL_CATEGORIES = "http://10.0.2.2/category_api/get_categories.php";

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

    selectedSpinner = (EditText) findViewById(R.id.categoryItem);
    spinner = (Spinner) findViewById(R.id.categoryList);
    btnViewExpenses = (Button) findViewById(R.id.btnViewExpenses);

    categoriesList = new ArrayList<Category>();

    // spinner item select listener
    spinner.setOnItemSelectedListener(this);

    new GetCategories().execute();

}

/**
 * Adding spinner data
 * */
private void populateSpinner() {
    List<String> lables = new ArrayList<String>();

//  txtCategory.setText("");

    for (int i = 0; i < categoriesList.size(); i++) {
        lables.add(categoriesList.get(i).getName());
    }

    // Creating adapter for spinner
    ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, lables);

    // Drop down layout style - list view with radio button
    spinnerAdapter
            .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // attaching data adapter to spinner
    spinner.setAdapter(spinnerAdapter);
}

/**
 * Async task to get all categories
 * */
private class GetCategories extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(PaymentsActivity.this);
        pDialog.setMessage("Loading Expenses Information...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        ServiceHandler jsonParser = new ServiceHandler();
        String json = jsonParser.makeServiceCall(URL_CATEGORIES, ServiceHandler.GET);

        Log.e("Response: ", "> " + json);

        if (json != null) {
            try {
                JSONObject jsonObj = new JSONObject(json);
                if (jsonObj != null) {
                    JSONArray categories = jsonObj
                            .getJSONArray("categories");                        

                    for (int i = 0; i < categories.length(); i++) {
                        JSONObject catObj = (JSONObject) categories.get(i);
                        Category cat = new Category(catObj.getInt("id"),
                                catObj.getString("category"));
                        categoriesList.add(cat);
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        } else {
            Log.e("JSON Data", "Didn't receive any data from server!");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        if (pDialog.isShowing())
            pDialog.dismiss();
        populateSpinner();
    }

}


@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
        long id) {
    Toast.makeText(
            getApplicationContext(),
                    parent.getItemAtPosition(position).toString() + " Selected" ,
            Toast.LENGTH_LONG).show();

}

@Override
public void onNothingSelected(AdapterView<?> arg0) {        
}

public void onClickViewExpenses(View view){
    Intent viewExpenses = new Intent(this, ExpensesList.class);
    startActivity(viewExpenses);
}
}

this is my xml file,

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" 
android:layout_gravity="center_horizontal">

<TextView
    android:id="@+id/accountBalanceView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/labelView"
    android:layout_marginLeft="26dp"
    android:textSize="20dp"
    android:text="Account Balance :" />

<Spinner
    android:id="@+id/categoryList"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true" />

<Button
    android:id="@+id/btnSubmitJobOpenAmount"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/jobOpeningAmount"
    android:layout_alignRight="@+id/accBalanced"
    android:text="Submit" />

<TextView
    android:id="@+id/jobOpeningbalance"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/accountBalanceView"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="18dp"
    android:gravity="center_horizontal"
    android:text="Job Opening Amount"
    android:textSize="20dp" />

<TextView
    android:id="@+id/accBalanced"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/labelView"
    android:layout_below="@+id/labelView"
    android:layout_marginRight="17dp"
    android:text="10000"
    android:textColor="#FF0040"
    android:textSize="20dp" />

<EditText
    android:id="@+id/jobOpeningAmount"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/categoryList"
    android:layout_alignLeft="@+id/accountBalanceView"
    android:layout_alignRight="@+id/accountBalanceView"
    android:layout_marginBottom="22dp"
    android:ems="10"
    android:inputType="number" >

    <requestFocus />
</EditText>

<EditText
    android:id="@+id/categoryItem"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/jobOpeningAmount"
    android:layout_alignRight="@+id/jobOpeningAmount"
    android:layout_below="@+id/categoryList"
    android:layout_marginTop="46dp"
    android:ems="10"
    android:inputType="number" />

<Button
    android:id="@+id/btnSubmitCategoryItem"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/categoryItem"
    android:layout_alignLeft="@+id/btnSubmitJobOpenAmount"
    android:text="Submit" />

<Button
    android:id="@+id/btnViewExpenses"
    android:onClick="onClickViewExpenses"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="31dp"
    android:text="View Previous Expenses" />

<TextView
    android:id="@+id/labelView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:gravity="center"
    android:padding="10dp"
    android:text="Enter Expenses Here"
    android:textSize="25dp"
    android:textStyle="bold" />

</RelativeLayout>

please help me to do this thing.

Was it helpful?

Solution

Use this.

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
    long id) {

   String myStr = spinner.getSelectedItem().toString();
   selectedSpinner.setText(myStr);

}

@Override
public void onNothingSelected(AdapterView<?> arg0) {        
}

OTHER TIPS

Try this..

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
        long id) {
    Toast.makeText(
            getApplicationContext(),
                    parent.getItemAtPosition(position).toString() + " Selected" ,
            Toast.LENGTH_LONG).show();

       String type = spinner.getSelectedItem().toString().trim();
       selectedSpinner.setText(type);

}

@Override
public void onNothingSelected(AdapterView<?> arg0) {        
}

Use This.....

MainActivity.java

String[] text1 = { "SUNDAY", "MONDAY", "TUESDAY",
        "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY" };
int[] val1 = { 0, 1, 2, 3, 4, 5, 6};


Spinner  spinner1;
TextView  textView1;

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

    textView1 = (TextView)findViewById(R.id.text1);
    spinner1 = (Spinner)findViewById(R.id.spinner1);
    ArrayAdapter<String> adapter1 =
            new ArrayAdapter<String>(MainActivity.this,
                    android.R.layout.simple_spinner_item, text1);
    adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner1.setAdapter(adapter1);
    spinner1.setOnItemSelectedListener(onItemSelectedListener1);
}

OnItemSelectedListener onItemSelectedListener1 =
        new OnItemSelectedListener(){

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                String s1 = String.valueOf(val1[position]);
                textView1.setText(s1);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}

        };

XML CODE

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/text1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />


</LinearLayout>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top