Problems with retaining user inputted form data when switching between activities - android

If anyone could help me with the following problem I would be eternally grateful.
My android app is a questionnaire to carry out property surveys. Each activity relates to an element of the property i.e. kitchen, bathroom, central heating etc. There will be circa 50 questions when the app is complete. Each activity has three Spinners and two Edit Texts with which the user must input data relating to the age and condition of the relevant element of the property before moving onto the next activity.
My problem is as follows:
Question 1 relates to the kitchen. Once all the relevant data is inputted I use an intent (via a 'next page' button) to start the next activity which relates to the bathroom. However, if I realise I made an error with my data input on the kitchen activity and go back via an intent from the bathroom activity (in the same way I got to the bathroom activity from the kitchen activity) the data I previously inputted is no longer there.
How do I retain this data? It is essential that my app users can flick backwards and forwards between the survey questions and view the data they have previously inputted. Once all 50 questions have been answered the data will be saved to a database and the next property can then be surveyed.
I have trawled the internet and various books for the answer to this but I am encountering conflicting information. Some say use on Pause, others say on Stop, others say on Saved Instance State. I'm confused?? I've been stuck on this for three days now so any help is very much appreciated.
Kitchen Activity below followed by Bathroom Activity..........
package com.example.basicview6;
import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class Kitchen extends Activity {
// defining the variables that will be displayed on the page
String[] age, renewal, main;
Spinner s1, s2, sMain;
ToggleButton repairs;
EditText repDesc, repCost, quantity;
Button back, next;
TextView life, qty, unit;
// creating the layout from the main xml file
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.kitchen);
// getting the string array values from the 'strings xml' resources file
// and applying them to the relevant variable
age = getResources().getStringArray(R.array.age_array);
renewal = getResources().getStringArray(R.array.renewal_array);
main = getResources().getStringArray(R.array.kitchen_array);
// getting the Spinner widget from the main xml and applying it to the
// 's1' variable
s1 = (Spinner) findViewById(R.id.spAge);
s2 = (Spinner) findViewById(R.id.spRenewal);
sMain = (Spinner) findViewById(R.id.spKitchen);
repairs = (ToggleButton) findViewById(R.id.tbRepairs);
repDesc = (EditText) findViewById(R.id.etRepDesc);
repCost = (EditText) findViewById(R.id.etRepCost);
quantity = (EditText) findViewById(R.id.etQuantity);
back = (Button) findViewById(R.id.bBack);
next = (Button) findViewById(R.id.bNext);
life = (TextView) findViewById(R.id.tvLife);
qty = (TextView) findViewById(R.id.tvQuantity);
unit = (TextView) findViewById(R.id.tvUnitM);
life.setVisibility(View.INVISIBLE);
quantity.setVisibility(View.INVISIBLE);
qty.setVisibility(View.INVISIBLE);
unit.setVisibility(View.INVISIBLE);
/*
* creating a new 'string type' ArrayAdapter and telling it to display
* the values of the relevant variable as a simple spinner item
*/
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, age);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, renewal);
ArrayAdapter<String> adapterM = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, main);
// priming the s1 Spinner variable for an array item to be selected -
// standby mode
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener() {
// telling the program what to do when an item is selected
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int index = arg0.getSelectedItemPosition();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
s2.setAdapter(adapter2);
s2.setOnItemSelectedListener(new OnItemSelectedListener() {
// telling the program what to do when an item is selected
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int index = arg0.getSelectedItemPosition();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
sMain.setAdapter(adapterM);
sMain.setOnItemSelectedListener(new OnItemSelectedListener() {
// telling the program what to do when an item is selected
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int index = arg0.getSelectedItemPosition();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
// setting up the OnClickListerner for the repairs toggle button
repairs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (repairs.isChecked()) {
repDesc.setVisibility(View.VISIBLE);
repCost.setVisibility(View.VISIBLE);
} else {
repDesc.setVisibility(View.INVISIBLE);
repCost.setVisibility(View.INVISIBLE);
}
}
});
// setting up the OnClickListener for the Next button
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent openBathroom = new Intent(
"com.example.basicview6.BATHROOM");
startActivity(openBathroom);
}
});
}
}
BATHROOM ACTIVITY ...................
package com.example.basicview6;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class Bathroom extends Activity {
// defining the variables that will be displayed on the page
String[] age, renewal, main;
Spinner s1, s2, sMain;
ToggleButton repairs;
EditText repDesc, repCost, quantity;
Button back, next;
TextView life, qty, unit;
// creating the layout from the main xml file
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bathroom);
// getting the string array values from the 'strings xml' resources file
// and applying them to the relevant variable
age = getResources().getStringArray(R.array.age_array);
renewal = getResources().getStringArray(R.array.renewal_array);
main = getResources().getStringArray(R.array.bathroom_array);
// getting the Spinner widget from the main xml and applying it to the
// 's1' variable
s1 = (Spinner) findViewById(R.id.spAge);
s2 = (Spinner) findViewById(R.id.spRenewal);
sMain = (Spinner) findViewById(R.id.spBathroom);
repairs = (ToggleButton) findViewById(R.id.tbRepairs);
repDesc = (EditText) findViewById(R.id.etRepDesc);
repCost = (EditText) findViewById(R.id.etRepCost);
quantity = (EditText) findViewById(R.id.etQuantity);
back = (Button) findViewById(R.id.bBack);
next = (Button) findViewById(R.id.bNext);
life = (TextView) findViewById(R.id.tvLife);
qty = (TextView) findViewById(R.id.tvQuantity);
unit = (TextView) findViewById(R.id.tvUnitM);
life.setVisibility(View.INVISIBLE);
quantity.setVisibility(View.INVISIBLE);
qty.setVisibility(View.INVISIBLE);
unit.setVisibility(View.INVISIBLE);
/*
* creating a new 'string type' ArrayAdapter and telling it to display
* the values of the relevant variable as a simple spinner item
*/
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, age);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, renewal);
ArrayAdapter<String> adapterM = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, main);
// priming the s1 Spinner variable for an array item to be selected -
// standby mode
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener() {
// telling the program what to do when an item is selected
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int index = arg0.getSelectedItemPosition();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
s2.setAdapter(adapter2);
s2.setOnItemSelectedListener(new OnItemSelectedListener() {
// telling the program what to do when an item is selected
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int index = arg0.getSelectedItemPosition();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
sMain.setAdapter(adapterM);
sMain.setOnItemSelectedListener(new OnItemSelectedListener() {
// telling the program what to do when an item is selected
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int index = arg0.getSelectedItemPosition();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
// setting up the OnClickListerner for the repairs toggle button
repairs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (repairs.isChecked()) {
repDesc.setVisibility(View.VISIBLE);
repCost.setVisibility(View.VISIBLE);
} else {
repDesc.setVisibility(View.INVISIBLE);
repCost.setVisibility(View.INVISIBLE);
}
}
});
// setting up the OnClickListener for the Back button
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent openKitchen = new Intent(
"com.example.basicview6.KITCHEN");
startActivity(openKitchen);
}
});
}
}

Well you can use a number of different methods which is why you keep seeing conflicting answers. However there are a few that are preferred.
For screen rotation, meaning if the device is flipped horizontally or vertically you use onSaveInstanceState.
There is another method I consider cheating and many people will tell you to stay away from as it can cause many errors down the line. However it is the easiest way possible. Simply go into your manifest and place this line
android:configChanges="orientation|keyboardHidden|screenSize
If you are trying to retain information so that when you return to an Activity it is still there you should use onPause(). It appears as though you are only transferring simple data like String, int, etc. This can be done using SharedPreferences inside your onPause(). The reason is onPause() is always (99% of the time) called before the Activity is killed, meaning you will always retain your information.
For some video references to show you how to do these things go here The New Boston
If you would rather read here are some links
SharedPreferences
onPause or onPause
onSaveInstanceState
If you need anything else just ask.

When switching between the Activities you can put extras to the Intent: putExtra() like:
intent.putExtra(Intent.EXTRA_TEXT, "my saved String");
And get them in the called activity by:
String gottenString = intent.getExtras().getString(Intent.EXTRA_TEXT);
You can also save your data in a (temporary) file: Saving Files

Related

Test if a user has selected an item from AutoCompleteTextView

My problem is that my code does not react accordingly whenever an user selects an item from an AutoCompleteTextView.
flag is a variable which is set to a value whenever one item from each AutoCompleteTextView has been selected. If it's set to 1, then it means it's right and it should proceed to main activity. Otherwise, a toast is displayed on click of button whose onClick calls the method callMainActivity.
There are no errors. Gradle build is successful, but clicking on that button (mentioned above) does nothing at all.
Code:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.Arrays;
import java.util.List;
public class Location extends AppCompatActivity {
private static int flag=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
int city = android.R.layout.simple_dropdown_item_1line;
int area = android.R.layout.simple_dropdown_item_1line;
int store = android.R.layout.simple_dropdown_item_1line;
String []city_array = getResources().getStringArray(R.array.City);
String []area_array= getResources().getStringArray(R.array.Area);
String []store_array= getResources().getStringArray(R.array.Store);
List<String> city_list= Arrays.asList(city_array);
List<String> area_list= Arrays.asList(area_array);
List<String> store_list= Arrays.asList(store_array);
ArrayAdapter<String> adapter_city = new ArrayAdapter(this,city, city_list);
ArrayAdapter<String> adapter_area = new ArrayAdapter(this, area, area_list);
ArrayAdapter<String> adapter_store = new ArrayAdapter(this, store, store_list);
final AutoCompleteTextView autocompleteView_city =
(AutoCompleteTextView) findViewById(R.id.City);
final AutoCompleteTextView autocompleteView_area =
(AutoCompleteTextView) findViewById(R.id.Area);
final AutoCompleteTextView autocompleteView_store =
(AutoCompleteTextView) findViewById(R.id.Store);
autocompleteView_area.setAdapter(adapter_area);
autocompleteView_city.setAdapter(adapter_city);
autocompleteView_store.setAdapter(adapter_store);
autocompleteView_area.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
autocompleteView_area.showDropDown();
if(autocompleteView_area.getListSelection()!= ListView.INVALID_POSITION)
flag=1;
else
flag=0;
}
});
autocompleteView_city.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
autocompleteView_city.showDropDown();
if(autocompleteView_area.getListSelection()!= ListView.INVALID_POSITION)
flag=1;
else
flag=0;
}
});
autocompleteView_store.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
autocompleteView_store.showDropDown();
if(autocompleteView_area.getListSelection()!= ListView.INVALID_POSITION)
flag=1;
else
flag=0;
}
});
//This is the newly updated part
autocompleteView_area.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick (AdapterView<?> parent, View view, int position, long id) {
//... your stuff
if(autocompleteView_area.getListSelection()>0) {
flag = 1;
System.out.println(flag + "flag at area");
}else
flag=0;
}
});
}
public void callMainActivity(View view){
if(flag==1) {
Intent in = new Intent(getBaseContext(), MainActivity.class);
startActivity(in);
}
else
Toast.makeText(getBaseContext(),"Please select all fields properly",Toast.LENGTH_LONG);
}
}
The reason you are not seeing the Toast or changing activities, is because you are never calling callMainActivity(View view) in your code. Add this line to the end of all your OnClickListeners: callMainActivity(arg0) -- if this does not work, put some log statements in your OnClickListeners to check if they are triggering or not.
Also, if you want to trigger the call when an item from your AutoCompleteTextView result list is selected, you should use an AdapterView.OnItemClickedListener instead. This will notify you when an item is selected from the AutoCompleteTextView list, or when nothing is selected and then you can react accordingly.

multiple order entries in android application

I'm working on an order management system for android.
On the order page where the user submits an order, i want it to be able to allow the user to submit multiple orders, then take the user to a page where it displays all the orders made.
What method can i use to accomplish that?
This is the order activity page which is made up of 3 spinners and one textfield. This page takes the user to a ViewOrder page which displays what the user has selected. Instead of that i would like the user to submit multiple orders first, then see the display of all orders submitted. Any help is much appreciated.
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.androidhive.R;
public class OrderActivity extends Activity {
public Button btnOrder;
public EditText txtCrates;
public Spinner sp1, sp2, sp3;
public List<String> list;
public static String crates;
public static final String EXTRA_MESSAGE = "com.example.myspinner.msg1";
public static final String EXTRA_MESSAGE2 = "com.example.myspinner.msg2";
public static final String EXTRA_MESSAGE3 = "com.example.myspinner.msg3";
public static final String EXTRA_MESSAGE4 = "com.example.myspinner.MESSAGE";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.order);
sp1 = (Spinner) findViewById(R.id.spinner1);
sp2 = (Spinner) findViewById(R.id.spinner2);
sp3 = (Spinner) findViewById(R.id.spinner3);
btnOrder = (Button) findViewById(R.id.btnOrder);
txtCrates =(EditText) findViewById(R.id.crates);
list = new ArrayList<String> ();
list.add("CocaCola");
list.add("Sprite");
list.add("Fanta Orange");
list.add("Fanta Pineapple");
list.add("Fanta Blackcurrant");
list.add("Fanta Passion");
list.add("Krest");
list.add("Stoney");
list.add("Dasani");
list.add("Minute Maid Apple");
list.add("Minute Maid Mango");
list.add("Minute Maid Orange");
final String[] str1={"300ml","500ml","1 Litre","1.25 Litres","2 Litres"};
ArrayAdapter<String> adp1 = new ArrayAdapter<String>
(this, android.R.layout.simple_dropdown_item_1line, list);
ArrayAdapter<String> adp2 = new ArrayAdapter<String>
(this, android.R.layout.simple_dropdown_item_1line, str1);
ArrayAdapter<CharSequence> adp3 = ArrayAdapter.createFromResource
(this, R.array.str2, android.R.layout.simple_dropdown_item_1line);
sp1.setAdapter(adp1);
sp2.setAdapter(adp2);
sp3.setAdapter(adp3);
btnOrder.setOnClickListener(new View.OnClickListener() {
/** Called when the user clicks the Submit Order button */
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),ViewOrder.class);
String msg1=sp1.getSelectedItem().toString();
String msg2=sp2.getSelectedItem().toString();
String msg3=sp3.getSelectedItem().toString();
String message = txtCrates.getText().toString();
intent.putExtra(EXTRA_MESSAGE, msg1);
intent.putExtra(EXTRA_MESSAGE2, msg2);
intent.putExtra(EXTRA_MESSAGE3, msg3);
intent.putExtra(EXTRA_MESSAGE4, message);
startActivity(intent);
}
});
sp1.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), list.get(arg2),
Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
sp2.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), str1[arg2],
Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
sp3.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String item = sp3.getSelectedItem().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
Once try as follows take an List for multiple orders
ArrayList<String> orders=new ArrayList<String>();
as class variable in activity
then store a complete order as string with some special character as divider like
String msg1=sp1.getSelectedItem().toString();
String msg2=sp2.getSelectedItem().toString();
String msg3=sp3.getSelectedItem().toString();
String message = txtCrates.getText().toString();
orders.add(msg1+","+msg2+","+msg3+","+message);
then for intent add as follows
intent.putStringArrayListExtra("orders", orders);
Hope this will helps you.

Having an issue with switch statement involving Android Spinners

I'm trying to use 2 spinners on my view and at the moment implementing the "OnItemSelected" method . I have a switch statement set up to tell the spinners apart, but it doesn't seem to be working for some reason.
Here is my code:
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import java.util.ArrayList;
import android.widget.AdapterView.OnItemSelectedListener;
/**
* This is the activity for feature 1 in the dashboard application.
* It displays some text and provides a way to get back to the home activity.
*
*/
public class F1Activity extends DashboardActivity implements OnItemSelectedListener
{
/**
* onCreate
*
* Called when the activity is first created.
* This is where you should do all of your normal static set up: create views, bind data to lists, etc.
* This method also provides you with a Bundle containing the activity's previously frozen state, if there was one.
*
* Always followed by onStart().
*
* #param savedInstanceState Bundle
*/
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView (R.layout.activity_f1);
setTitleFromActivityLabel (R.id.title_text);
//declaring variables
Button submitButton = (Button) findViewById(R.id.button1);
Button cancelButton = (Button) findViewById(R.id.button2);
//getting arrays from strings file
String[] regions = getResources().getStringArray(R.array.regions_array);
String[] grids = getResources().getStringArray(R.array.grids_array);
Spinner gridSpinner = (Spinner) findViewById(R.id.gridSpinner);
Spinner regionSpinner = (Spinner) findViewById(R.id.regionSpinner);
//creating adapters for both spinners
ArrayAdapter<String> dataAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, grids);
ArrayAdapter<String> regionAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, regions);
// drop down layout style with radio button type.
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
regionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapters to spinners
gridSpinner.setAdapter(dataAdapter);
regionSpinner.setAdapter(regionAdapter);
gridSpinner.setOnItemSelectedListener(this);
regionSpinner.setOnItemSelectedListener(this);
submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
Intent changeAdd = new Intent();
setResult(RESULT_OK, changeAdd);
EditText nameText = (EditText) findViewById(R.id.nameTextBox);
EditText passText = (EditText) findViewById(R.id.passwordTextBox);
if(nameText.getText().toString().length() > 0 &&
passText.getText().toString().length() > 0) //TAKE CARE OF LISRVIEW/DROPDOWN
{
Toast.makeText(getApplicationContext(),
"Loading...", Toast.LENGTH_LONG).show();
// make an intent to start the virtual world activity..................like in addGridActivity/screen switch!
finish();
}
else
{
Toast.makeText(getApplicationContext(), "Sorry, you have to complete all the fields",
Toast.LENGTH_SHORT).show();
}
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
Intent changeAdd = new Intent();
setResult(RESULT_OK, changeAdd);
// cancelled and went back to home screen
finish();
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long arg3) {
// to handle the selection of the gridSpinner or the regionSpinner
int id = parent.getId();
switch(id)
{
case R.id.gridSpinner:
Toast.makeText(parent.getContext(), "you selected" +
parent.getItemAtPosition(pos).toString() + "from the grid spinner", Toast.LENGTH_LONG);
break;
case R.id.regionSpinner:
Toast.makeText(parent.getContext(), "you selected" +
parent.getItemAtPosition(pos).toString() + "from the region spinner", Toast.LENGTH_LONG);
break;
default:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
} // end class
<code>
Your switch is working fine. The reason it seems to be not working is because your code to display the Toast is missing the show() calls.
Instead of:
Toast.makeText(parent.getContext(), ..., Toast.LENGTH_LONG);
do this:
Toast.makeText(parent.getContext(), ..., Toast.LENGTH_LONG).show();
I make the same mistake all the time myself :)
Replace int id = parent.getId(); to int id = view.getId();
You need to switch based on the id of the view not the view adapter. Try changing int id = parent.getId(); to int id = view.getId();.

Android - Selecting different spinner option doesn't update calculation in TextView, only working on 1st item in list

I have a simple spinner which has several number options. I want to just select a number and then it does some math to that number and outputs it in a text box. For some reason it's only doing math on the 1st entry in the list and if you change it doesn't update.
Any ideas?
package placeorder.com;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Spinner;
import android.widget.TextView;
public class Time extends Activity{
double totalhours, cost;
int price;
TextView total, orderid;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.time);
Spinner spinhours = (Spinner) findViewById(R.id.sp_hours);
total = (TextView) findViewById(R.id.tv_total);
orderid = (TextView) findViewById(R.id.tv_orderid);
Random order = new Random();
int randomorder = order.nextInt(9999);
order.nextInt(9999);
orderid.setText("Order ID: "+randomorder);
price = 5;
String hours = spinhours.getSelectedItem().toString();
totalhours = Integer.parseInt(hours);
cost = totalhours * price;
total.setText("£" + cost);
}
}
You should add listener for spinner
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
String str = (String) arg0.getSelectedItem();
outputTextview.setText(str);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});

add two number using spinner in android

i want to add two numbers using spinner view. here in my code two spinners .After i run the emulator it displays straight result only. it does not display spinner control and i'm not able to select the two numbers. Pls give one solution. Thanks in advance. Here code
package com.kk;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TextView;
import android.R.id;
public class TrckActivity extends Activity {
/** Called when the activity is first created. */
String[] a={"-select-","1","2"};
String[] b={"-select-","2","4"};
int first,second,f,s,c;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayAdapter<String> a1= new ArrayAdapter<String> (this,android.R.layout.simple_dropdown_item_1line,a);
final Spinner sp1=(Spinner)findViewById(R.id.spinner1);
sp1.setAdapter(a1);
sp1.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
first=sp1.getSelectedItemPosition();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
ArrayAdapter<String> a2= new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,b);
final Spinner sp2=(Spinner)findViewById(R.id.spinner1);
sp2.setAdapter(a2);
sp2.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
second=sp2.getSelectedItemPosition();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
if(first==1)
{
f=1;
}
else if(first==2)
{
f=2;
}
if(second==1)
{
s=2;
}
else if(second==2)
{
s=3;
}
c=f+s;
TextView tv=new TextView(this);
tv.setText(""+c);
setContentView(tv);
}
}
This might be because the spinner's "onItemSelected" method gets called initially as soon as your code enters the onCreate method. Maybe you have to maintain flag values to do this.
These links might help you get started with it,
Spinner onItemSelected called erroneously (without user action)
Spinner onItemSelected() executes when it is not suppose to
Try to exchange
android.R.layout.simple_dropdown_item_1line
to
android.R.layout.simple_spinner_item

Categories

Resources