Save spinner and use it for another activity - android

I have tried to use the examples and read those links that I think related to my project, but all of it have a different structure from mine. Hope anybody could help.
I have 3 spinners in my NewProfile.java class. In this class, user can input their profiles and also selecting the type of workout with the user interests. I have no problem saving the profile text input. But I have a problem to save the spinner value selected by the user. Following are my codes.
NewProfile.java
public class NewProfile extends Activity {
EditText profileName, profileDOB, profileSex, profileWeight, profileHeight;
Spinner workoutspinner, levelspinner, weightplan1, weightplan2,
weightplan3;
TextView display;
DBController controller = new DBController(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.newdata);
profileName = (EditText) findViewById(R.id.etName);
profileDOB = (EditText) findViewById(R.id.etDOB);
profileSex = (EditText) findViewById(R.id.etSex);
profileWeight = (EditText) findViewById(R.id.etWeight);
profileHeight = (EditText) findViewById(R.id.etHeight);
chooseWorkout();
chooseLevel();
chooseWeight1();
chooseWeight2();
chooseWeight3();
}
public void addNewProfile(View view) {
HashMap<String, String> queryValuesMap = new HashMap<String, String>();
queryValuesMap.put("profileName", profileName.getText().toString());
queryValuesMap.put("profileDOB", profileDOB.getText().toString());
queryValuesMap.put("profileSex", profileSex.getText().toString());
queryValuesMap.put("profileWeight", profileWeight.getText().toString());
queryValuesMap.put("profileHeight", profileHeight.getText().toString());
controller.insertProfile(queryValuesMap);
this.startingpointActivity(view);
}
private void startingpointActivity(View view) {
// TODO Auto-generated method stub
Intent objIntent = new Intent(getApplicationContext(),
StartingPoint.class);
startActivity(objIntent);
finish();
}
private void chooseWorkout() {
// TODO Auto-generated method stub
workoutspinner = (Spinner) findViewById(R.id.spinWorkout);
ArrayAdapter<CharSequence> workoutadapter = ArrayAdapter
.createFromResource(this, R.array.saWorkout,
android.R.layout.simple_spinner_item);
workoutadapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
workoutspinner.setAdapter(workoutadapter);
workoutspinner.setOnItemSelectedListener(new workoutOnClickListener());
}
private void chooseLevel() {
// TODO Auto-generated method stub
levelspinner = (Spinner) findViewById(R.id.spinLevel);
ArrayAdapter<CharSequence> leveladapter = ArrayAdapter
.createFromResource(this, R.array.saLevel,
android.R.layout.simple_spinner_item);
leveladapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
levelspinner.setAdapter(leveladapter);
levelspinner.setOnItemSelectedListener(new levelOnClickListener());
}
private void chooseWeight1() {
// TODO Auto-generated method stub
weightplan1 = (Spinner) findViewById(R.id.spinWeight);
ArrayAdapter<CharSequence> weightadapter1 = ArrayAdapter
.createFromResource(this, R.array.saWeight1,
android.R.layout.simple_spinner_item);
weightadapter1
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
weightplan1.setAdapter(weightadapter1);
}
private void chooseWeight2() {
// TODO Auto-generated method stub
weightplan2 = (Spinner) findViewById(R.id.spinWeight);
ArrayAdapter<CharSequence> weightadapter2 = ArrayAdapter
.createFromResource(this, R.array.saWeight2,
android.R.layout.simple_spinner_item);
weightadapter2
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
weightplan2.setAdapter(weightadapter2);
}
private void chooseWeight3() {
// TODO Auto-generated method stub
weightplan3 = (Spinner) findViewById(R.id.spinWeight);
ArrayAdapter<CharSequence> weightadapter3 = ArrayAdapter
.createFromResource(this, R.array.saWeight3,
android.R.layout.simple_spinner_item);
weightadapter3
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
weightplan3.setAdapter(weightadapter3);
}
public class workoutOnClickListener implements OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos,
long id) {
// TODO Auto-generated method stub
parent.getItemAtPosition(pos);
if (pos == 0) {
chooseLevel();
levelspinner.setClickable(true);
weightplan1.setClickable(true);
weightplan2.setClickable(true);
weightplan3.setClickable(true);
} else if (pos != 0){
levelspinner.setClickable(false);
weightplan1.setClickable(false);
weightplan2.setClickable(false);
weightplan3.setClickable(false);
Toast.makeText(getApplicationContext(),
"Wollaaaa! Only Program 1 is available for this moment. Sorry.. :)",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
public class levelOnClickListener implements OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
// TODO Auto-generated method stub
parent.getItemAtPosition(pos);
if (pos == 0) {
chooseWeight1();
} else if (pos == 1){
chooseWeight2();
} else if (pos == 2){
chooseWeight3();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
}
Do I need to change anything in my DBController in order to save these spinners? Please help. Thanks.
p/s Just to inform that the addNewProfile is a button that save all the information.

Okay, I'll do my best to answer as requested:
For a start, these are the key parts of setting and getting values from your spinners:
If you need to set the values in your spinners, you can use this.
mySpinner.setSelection(arrayAdapter.getPosition("Category 2")); //This assumes that "Category 2" exists in your spinner list.
To get the value from your spinner.
String Text = mySpinner.getSelectedItem().toString();
Here is a great discussion on what to DO with those values.
SharedPreferences example.
That pretty well explains how to save your preferences. It also should give you almost everything to answer your initial question.
The key part afterward is what to do with those prefs. This line shows how to set a string based on what it finds in the saved prefs, and if it finds nothing, will load "default".
This is helpful for when the user is running the app for the first time and prefs have never been set.
test_string=shared_preferences.getString("test_key", "Default");
Once those prefs have been set, and you want them to show in a different view, just add all this same sort of technique to the other view.
Hope that helps. For what it's worth, every last bit of this was taken from here, through various searches. Sometimes you need to look through a bunch of different things to find an answer if a simple solution is not in one place.

Related

Android dynamic listview added position

Hi I am working with android listview.I want to create a dynamic list view in which user can add data dynamically to listview .So far its works fine. Now my problem is my contets are added at start position of listview .I want to add the added contents at last position of list view (like adding comments in facebook post). Is it possible to make ?? Please help me .Thanks in advance :)
MY activity class
public class MainActivity extends Activity {
private EditText etInput;
private Button btnAdd;
private ListView lvItem;
private ArrayList<String> itemArrey;
private ArrayAdapter<String> itemAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpView();
}
private void setUpView() {
// TODO Auto-generated method stub
etInput = (EditText)this.findViewById(R.id.editText_input);
btnAdd = (Button)this.findViewById(R.id.button_add);
lvItem = (ListView)this.findViewById(R.id.listView_items);
itemArrey = new ArrayList<String>();
itemArrey.clear();
itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,itemArrey);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addItemList();
}
});
etInput.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_ENTER) {
addItemList();
}
return true;
}
});
}
protected void addItemList() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
if (isInputValid(etInput)) {
itemArrey.add(0,etInput.getText().toString());
etInput.setText("");
itemAdapter.notifyDataSetChanged();
}
}
protected boolean isInputValid(EditText etInput2) {
// TODO Auto-generatd method stub
if (etInput2.getText().toString().trim().length()<1) {
etInput2.setError("Please Enter Item");
return false;
} else {
return true;
}
}
}
Remove position from
itemArrey.add(0,etInput.getText().toString()); // Position=0
Try this way.
itemArrey.add(etInput.getText().toString());
that directly add your string at the end.
You are specifying position to add new element to. Just avoid using position and new item will be added at the end of list.
itemArrey.add( etInput.getText().toString() );
Further more, you might also like to scroll down to this newly added item. So you can use these in xml
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll"
or use setSelection() to do so like -
lvItem.setSelection(countOfItems-1);

Android temp update spinner before it gets values from SQLite

I'm wondering if there is some trick to get the spinner updated from an edittext and onClick, before it gets committed to the database and retrieve from there? The list and the spinnerAdapter are set for retrieving values from database, so I'm aware that this question might be stupid.
I was thinking of this logic: enter some text to edittext, click ok, then temporary update the spinner with this text, before it goes to database, then do some other stuff in the activity and last commit everything to database. When you then close and open your activity again, the temporary value is lost, but the spinner gets populatet with the same value, but this time from database.
here is some code:
public class Vnos extends Activity {
//... some values
#Override
protected void onCreate(Bundle savedInstanceState) {
//...
final Spinner spinner = (Spinner) findViewById(R.id.spinner1);
final List<VnosiDB> spinerItems = datasource.getAllNiz();
final ArrayAdapter<VnosiDB> spinnerAdapter = new ArrayAdapter<VnosiDB>(
this, android.R.layout.simple_spinner_item, spinerItems);
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerAdapter);
String nizIzSpinerja = spinner.getItemAtPosition(
spinner.getSelectedItemPosition()).toString();
nizDB = nizIzSpinerja;
// nov niz
novNiz = (TextView) findViewById(R.id.dodaj);
novNiz.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(Vnos.this,
android.R.style.Theme_Holo_Dialog);
dialog.setContentView(R.layout.nov_niz);
TextView okNov = (TextView) dialog.findViewById(R.id.okNovNiz);
okNov.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText inputNiz = (EditText) dialog
.findViewById(R.id.niz);
dialog.dismiss();
nizDB = inputNiz.getText().toString();
spinnerAdapter.notifyDataSetChanged();
}
});
dialog.show();
}
});
// ...some other code...
//...
//.. then, here I commit everything to database...
shrani = (TextView) findViewById(R.id.shrani);
shrani.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
vnosDB = (int) System.currentTimeMillis();
datasource.createVnos(zacetekDB, razlikaDB, nizDB, deloDB,
postavkaDB, dodatekDB, opisDB, vnosDB);
datasource.close();
Toast test = Toast.makeText(Vnos.this, "Vnos " + deloDB
+ " uspešen!", Toast.LENGTH_LONG);
test.show();
startActivity(new Intent("com.sandpit.jazstudent.URE"));
finish();
}
});
}
}
you are using ArrayAdapter, which is loaded by List<VnosiDB>. I assume that VnosiDB represents a record from the database. Why don't you just put a temporary record in this list when you need it?
List<VnosiDB> spinerItems = new ArrayList<VnosiDB>();
VnosiDB tempRec = new VnosiDB();
//set some values to the properties if you need to
spinnerItems.add(tempRec);
//populate the spinner with the temp record

Update the Activity based on what item is selected in the Spinner

In the current Activity I'm printing a graph (using Androidplot) of the closing prices of a selected stock from the previous activity.
In this activity I have a spinner of a list of indicators the user can overlay.
Now I want the graph to be redrawn with this new selection from the spinner.
I did try refreshing/reloading the page onItemSelected but that causes the page to keep refreshing even without waiting for a user input.
public class DispGraph extends Activity {
private XYPlot plotstock;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.graph);
// PRINTING SELECTED STOCK_NAME
Bundle bundle = getIntent().getExtras();
String sname = bundle.getString("SN");
TextView t = (TextView) findViewById(R.id.textView1);
t.setText(sname);
// INDICATOR LIST
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.Indicators, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
String iname = spinner.getSelectedItem().toString();
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
startActivity(getIntent());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}});
//PASSING STOCK-TICKER & INDICATOR TO PHP
// PLOTTING GRAPH
plotstock = (XYPlot) findViewById(R.id.mySimpleXYPlot);
Number[] series1Numbers = ind;
Number[] series2Numbers = closing;
XYSeries series1 = new SimpleXYSeries(Arrays.asList(series1Numbers),SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, iname);
XYSeries series2 = new SimpleXYSeries(Arrays.asList(series2Numbers),SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "Closing Price");
plotstock.setDomainLabel("Date");
plotstock.setRangeLabel("Price");
plotstock.addSeries(series1,new LineAndPointFormatter(Color.rgb(0, 200, 0), Color.rgb(0,100, 0), null, new PointLabelFormatter(Color.TRANSPARENT)));
plotstock.addSeries(series2,new LineAndPointFormatter(Color.rgb(0, 0, 200), Color.rgb(0, 0, 100),null, new PointLabelFormatter(Color.TRANSPARENT)));
plotstock.setTicksPerRangeLabel(2);
}
}
Using your current approach, each time the user select a spinner value your current activity will be started again, so it will be put on Android Stack. Soon, if the user change your spinner n times, you should press n + 1 times to close your app. This is a really annoying behavior.
Well, I do not know the AndroidPlot, but looking its API I found the method redraw.So, i think you could try on that way:
Every time the user select a spinner value, i can do your modifications on plotstock after call plotstock.redraw()
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
//Change the graphics value here!
plotstock.redraw();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}});

setOnitemSelectedListener is not triggering with the programmatically created spinner Android

My need is to
create a dynamic spinner on a button click
select the spinner values and set the values into an edit text field.
For this I have created a dynamic spinner programatically. Put that code inside button click listener. Its working fine upto here.
but the setOnitemSelectedListener of the dynamic spinner is not at all working.. there are no errors in the Logcat... please help me..
------------ These are the methods inside onCreate ------------
Spinner spnOutHospitalList = new Spinner(Referance.this);
// list button on click event
btnList = (Button) findViewById(R.id.btn_list);
btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// function to create spinner dynamically
createDynamicSpinner();
}
});
// Out Hospital List Spinner on item click listener
spnOutHospitalList.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long arg3) {
// TODO Auto-generated method stub
outHospitalName = hospitalNameListArray.get(position);
outHospital.setText(outHospitalName);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
------------ These are the functions outside onCreate but inside the Activity------------
// to create spinner dynamically
private void createDynamicSpinner() {
// TODO Auto-generated method stub
spnOutHospitalList.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
loadOutHospitalListSpinner();
spnOutHospitalList.performClick();
}
// to load out hospital/ clinic data into spinner
private void loadOutHospitalListSpinner() {
// TODO Auto-generated method stub
try {
if (getFirstRun()) {
sampleDB = dbAdapter.getDatabase();
setRunned();
}
else {
sampleDB = dbAdapter.getWritableDatabase();
}
Cursor c1 = sampleDB.rawQuery("select DISTINCT EPR_OUT_HOSPITAL from EMR_PT_REFERNCE",null);
System.out.println("count is " + c1.getCount());
if (c1 != null && c1.getCount() != 0) {
hospitalNameListArray.clear();
if (c1.moveToFirst()) {
do {
hospitalNameListArray.add(c1.getString(c1.getColumnIndex("EPR_OUT_HOSPITAL")));
} while (c1.moveToNext());
}
}
c1.close();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, hospitalNameListArray);
// dropdownlist
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnOutHospitalList.setAdapter(dataAdapter);
}
catch (Exception e) {
// TODO: handle exception
System.out.println("CAT LIST ERROR IS: " + e.getMessage());
}
}
Try this
Write setOnItemSelectedListener inside createDynamicSpinner
private void createDynamicSpinner() {
//Remove this line from top in your code and add here
Spinner spnOutHospitalList = new Spinner(Referance.this);
spnOutHospitalList.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
//Pass Spinner Object to this function to load data in it!
loadOutHospitalListSpinner(spnOutHospitalList);
spnOutHospitalList.performClick();
spnOutHospitalList.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long arg3) {
// TODO Auto-generated method stub
outHospitalName = hospitalNameListArray.get(position);
outHospital.setText(outHospitalName);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}

Is there a way for a spinner option to open another spinner?

I want it where when someone clicks an option in a Spinner, it opens another spinner with more options. Also, is there a way for an "Other" option to open an EditText where someone can input their selection if theirs isn't available in the Spinner?
Example:
Spinner 1 has these options:
iOS
Android
And if they select iOS, another spinner comes up immediately where the options are all the iPhone versions. (i.e., titled "Which iPhone do you have?")
And if they select Android, it does the same thing, but with Android devices.
AND if their phone isn't on the second spinner, they type the model of their phone in.
How could I do this if I have the first spinner already in my code?
P.S., if needed, I can post the code for the first spinner, though it's pretty standard.
Basically build your second spinner programmatically depending on which option they choose. I'd add "other" to each second spinner. If they choose "other" then you can display the text box.
I hope this will be useful to you.
Try this Code...
public class MainActivity extends Activity {
Spinner sp1,sp2;
ArrayAdapter<String> adp1,adp2;
List<String> l1,l2;
int pos;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l1=new ArrayList<String>();
l1.add("A");
l1.add("B");
sp1= (Spinner) findViewById(R.id.spinner1);
sp2= (Spinner) findViewById(R.id.spinner2);
adp1=new ArrayAdapter<String> (this,android.R.layout.simple_dropdown_item_1line,l1);
adp1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
sp1.setAdapter(adp1);
sp1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
pos=arg2;
add();
}
private void add() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), ""+pos, Toast.LENGTH_SHORT).show();
switch(pos)
{
case 0:
l2= new ArrayList<String>();
l2.add("A 1");
l2.add("A 2");
adp2=new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_dropdown_item_1line,l2);
adp2.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
sp2.setAdapter(adp2);
select();
break;
case 1:
l2= new ArrayList<String>();
l2.add("B 1");
l2.add("B 2");
adp2=new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_dropdown_item_1line,l2);
adp2.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
sp2.setAdapter(adp2);
select();
break;
}
}
private void select() {
// TODO Auto-generated method stub
sp2.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "Test "+arg2, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}

Categories

Resources