Android spinners dynamic data binding - android

I am new to android , I have an activity with 3 multiple spinners as bellow
Spinner 1:department
Spinner2:semester
Spinner3:subjects
and one button
spinner1 shows the department on select of department it has to display the semester on select of semester it has to display the subject spinner
NOTE:-SUBJECT SPINNER DEPENDS ON THE SELECTION OF SEMESTER SPINNER AS WELL AS DEPARTMENT SPINNER.
something like country, state, city spinners but suggest me some other ideas to do it because i am using string resources to list the items of spinners
Please help me

Try something like this in your activity.
Firstly, make your activity implement AdapterView.OnItemSelectedListener & View.OnClickListener.
private Spinner mDepartmentSpinner;
private Spinner mSemesterSpinner;
private Spinner mSubjectSpinner;
private Button mButton;
// Values to fill first spinner with.
private String[] mDepartments = {
"Department 1",
"Department 2",
"Department 3",
"Department 4",
};
private String[] mSemesters;
private String[] mSubjects;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews() {
// Find the spinners and button, declared in the activity's resource file
mDepartmentSpinner = (Spinner) findViewById(R.id.department_spinner);
mSemesterSpinner = (Spinner) findViewById(R.id.semester_spinner);
mSubjectSpinner = (Spinner) findViewById(R.id.subject_spinner);
mButton = (Button) findViewById(R.id.button);
// Initialise spinner with values, placing them into a textview
mDepartmentSpinner.setAdapter(new ArrayAdapter<String>(getContext(), R.layout.text_view, mDepartments));
// Attach a listener for item selection
departmentSpinner.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// Work out which spinner was selected
switch (view.getId()) {
case R.id.department_spinner:
// Get the selected item
String selectedDepartment = mDepartments[position];
// Get values to fill the semester spinner with, based on initial selection.
mSemesters = getSemestersFor(selectedDepartment);
// Initialise spinner with values, placing them into a textview
mSemesterSpinner.setAdapter(new ArrayAdapter<String>(getContext(), R.layout.text_view, mSemesters));
// Attach a listener for item selection
mSemesterSpinner.setOnItemSelectedListener(this);
break;
case R.id.semester_spinner:
// Get the selected item
String selectedSemester = mSemesters[position];
// Get values to fill the subject spinner with, based on second spinner selection.
mSubjects = getSubjectsFor(selectedSemester);
// Initialise spinner with values, placing them into a textview
mSubjectSpinner.setAdapter(new ArrayAdapter<String>(getContext(), R.layout.text_view, subjects));
// Attach a listener for item selection
mSubjectSpinner.setOnItemSelectedListener(this);
break;
case R.id.subject_spinner:
mButton.setOnClickListener(this);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Please select an option from each spinner.", Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onClick(View v) {
// Go to your new activity, passing the selected subject
Intent intent = new Intent(this, SubjectActivity.class);
intent.putExtra("KEY_SUBJECT", (String) mSubjectSpinner.getSelectedItem());
startActivity(intent);
}
You can get the selected subject in the SubjectActivity like so...
#Override
public void onCreate(Bundle savedInstanceState) {
if (getIntent().getExtras().containsKey("KEY_SUBJECT") {
String subject = getIntent().getExtras().getString("KEY_SUBJECT");
}
}
Code for R.layout.text_view
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
You will need to implement the following methods yourself, I don't know your logic!
private String[] getSemestersFor(String department) {
// your code here
}
private String[] getSubjectsFor(String semester) {
// your code here
}

Related

"If Spinner = Value Then" in Android Studio

It's Will Be Good For Your Help,,
i have 2 Spinner + Mediam Text + Button
First Spinner "hint" [where i'm Now]
(Los angeles, California, London)
Second Spinner "hint" [i Want To Go]
(Florida, Origin, London)
When i Click On Button, Will Show Result in Text Box ..
Example:
When I choose I'm in "Los angeles" And Want To Go "London" Then Result Will Show in Text Box, that Says "If you Want Go To London You Have To Travel with Airplane".
Please explain because I'm Lv1 in Android Studio.
Try this code..!
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
Spinner temp1,temp2;
TextView t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
t1=(TextView)findViewById(R.id.t1);
temp1=(Spinner)findViewById(R.id.temp);
ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(this,R.array.temperature,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
temp1.setAdapter(adapter);
temp2=(Spinner)findViewById(R.id.temp2);
ArrayAdapter<CharSequence> adapter2=ArrayAdapter.createFromResource(this,R.array.temperature,android.R.layout.simple_spinner_item);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
temp2.setAdapter(adapter2);
temp1.setOnItemSelectedListener(this);
temp2.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Spinner temp1=(Spinner)parent;
Spinner temp2=(Spinner)parent;
if (temp1.getId()==R.id.temp) {
String item = parent.getItemAtPosition(position).toString();
t1.setText(item);
}
if (temp2.getId()==R.id.temp2) {
String item = parent.getItemAtPosition(position).toString();
t1.setText(item);
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}

how to store spinner selected value and retrieve it in another activity for display

i've searched for a solution on google ,and on stack overflow.Yes i also know this could be a duplicate of another question asked in stack overflow but i tried the code snippets offered but none of them worked.Like: Taking user selection in a spinner, storing it in sharedPrefences, and using it in another activity and not getting integer value from SharedPreference and http://www.acnenomor.com/4379973p1/how-to-save-spinner-selecteditem-to-sharedpreferences
Here is my problem.I have the first activity,with two spinners from this tutorial http://www.mkyong.com/android/android-spinner-drop-down-list-example/ .On pressing the submit button,id like to save the selected values on SharesPreferences.On going to the second activity,i retrieve the selected values and display them on a text view.So that on the next app launch i go to the second activity to find the displayed saved values.I've been really stranded on this.Please point me in the right direction.Any help will be very much appreciated.
main activity
public class MyAndroidAppActivity extends Activity {
private Spinner spinner1, spinner2;
private Button btnSubmit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addItemsOnSpinner2();
addListenerOnButton();
addListenerOnSpinnerItemSelection();
}
// add items into spinner dynamically
public void addItemsOnSpinner2() {
spinner2 = (Spinner) findViewById(R.id.spinner2);
List<String> list = new ArrayList<String>();
list.add("list 1");
list.add("list 2");
list.add("list 3");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);
}
public void addListenerOnSpinnerItemSelection() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
// get the selected dropdown list value
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MyAndroidAppActivity.this,
"OnClickListener : " +
"\nSpinner 1 : "+ String.valueOf(spinner1.getSelectedItem()) +
"\nSpinner 2 : "+ String.valueOf(spinner2.getSelectedItem()),
Toast.LENGTH_SHORT).show();
}
});
}
}
CustomOnItemSelectedListener.java
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
I was finally able to do it. I used this tutorial (http://androidopentutorials.com/android-sharedpreferences-tutorial-and-example/)
I modified this code to fit what I wanted
public void onClick(View v) {
text = String.valueOf(spinner1.getSelectedItem()) + String.valueOf(spinner2.getSelectedItem());
sharedPreference.save(context, text);

switch case with two spinners and audio player

In my activity i have two spinners, one image view and two buttons.
depending on first spinner the second spinners should change. and while selecting birds in first spinner the second spinner should show parrot peacock etc. while selecting parrot in second spinner i should get the image of parrot.
till this i am getting.
but now what i want is while i press a button then i should get the voice of parrot.
in this code when i am pressing the button i am getting the same voice for every picture change in second spinner
public class MainActivity extends Activity {
ImageView displayIV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
;
Button b1;
b1=(Button)findViewById(R.id.button1);
Spinner friend = (Spinner) findViewById(R.id.spinner1);
final Spinner subFriend = (Spinner) findViewById(R.id.spinner2);
displayIV=(ImageView)findViewById(R.id.imageView1);
final ArrayList<String> friend_options = new ArrayList<String>();
final ArrayList<String> subfriend_options = new ArrayList<String>();
friend_options.add("Nuz");
friend_options.add("Dur");
friend_options.add("Tara");
friend_options.add("Sama");
ArrayAdapter<String> friendAdapter = new ArrayAdapter<String>(
getApplicationContext(), android.R.layout.simple_spinner_item,
friend_options);
friend.setAdapter(friendAdapter);
ArrayAdapter<String> subFriendAdapter = new ArrayAdapter<String>(
getApplicationContext(),
android.R.layout.simple_spinner_item,subfriend_options);
subFriend.setAdapter(subFriendAdapter);
friend.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View view,
int position, long id) {
String friendName =
friend_options.get(position).toString();
resetFriend(friendName);
// subFriend.setAdapter(null);
}
private void resetFriend(String friendName) {
subfriend_options.removeAll(subfriend_options);
if (friendName.equals("Nuz")) {
subfriend_options.add("Nuz_1");
subfriend_options.add("Nuz_2");
subfriend_options.add("Nuz_3");
subfriend_options.add("Nuz_4");
} else if (friendName.equals("Dur")) {
subfriend_options.add("Dur_1");
subfriend_options.add("Dur_2");
subfriend_options.add("Dur_3");
subfriend_options.add("Dur_4");
} else if (friendName.equals("Tara")) {
subfriend_options.add("Tara_1");
subfriend_options.add("Tara_2");
subfriend_options.add("Tara_3");
subfriend_options.add("Tara_4");
} else {
subfriend_options.add("Sama_1");
subfriend_options.add("Sama_2");
subfriend_options.add("Sama_3");
subfriend_options.add("Sama_4");
}
ArrayAdapter<String> subFriendAdapter = new
ArrayAdapter<String>( getApplicationContext(),
android.R.layout.simple_spinner_item,
subfriend_options);
subFriend.setAdapter(subFriendAdapter);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
subFriend.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
arg0.getItemAtPosition(arg2);
final ImageView im =
(ImageView)findViewById(R.id.imageView1);
String s=((TextView)arg1).getText().toString();
if(s.equals("Tara_1")){
im.setImageDrawable(getResources().getDrawable(R.drawable.crow));
}
if(s.equals("Tara_2"))
im.setImageDrawable(getResources().getDrawable(R.drawable.india1));
if(s.equals("Tara_3"))
im.setImageDrawable(getResources().getDrawable(R.drawable.peacock));
if(s.equals("Tara_4"))
im.setImageDrawable(getResources().getDrawable(R.drawable.robin1));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//MediaPlayer mMediaPlayer = MediaPlayer.create(this,
R.raw.Kalimba);
MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.abc);
mp.start();
}
});
}
#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;
}
}
In the setOnClickListener method of your button, b1, you need to know which image has been selected on the spinner (your description is a little bit confusing so i don't have clear exactly which spinner is going to change the sound that you app has to reproduce).
Anyway, let think that the spinner is "friend_options".
In you setOnClickListener we have to know which item has been selected for the user when click on the button, right? And depending of which item was selected, we will play one specific sound.
So....
Another important poin is that you should create the variable of the mediaplayer outside of the onclickListener, like a class variable:
//Class variable:
public MediaPlayer mp;
In the onCreate method you should initialize the MediaPlayer component:
public void onCreate()
{
MediaPlayer.create(MainActivity.this, R.raw.abc); //Default sound, it is not
//importat because we are going
//to chain the value of the
//file to reproduce in the next
//step.
}
b1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Here we are going to take the item selected:
String itemSelected = spinner.getSelectedItem().toString();
int soundToPlayId=0;
if(itemSelected.equals("Nuz"))
{
soundToPlayId = R.raw.Kalimba ;
}
else if(itemSelected.equals("Dur"))
{
soundToPlayId = R.raw.abc;
}
// etc etc etc --> you should put all the sound associated to all the
// friends
//And now you only have to reproduce if the item was selected properly:
if(soundToPlayId !=0) //if the id is different to 0:
{
mp = MediaPlayer.setDataSource(MainActivity.this, soundToPlayId);
mp.start();
}
}
});
Let see if it is working!!! Ask me if you have any doubt...and if the answer is correct, vote me and check as correct!!! (I need points, thanks!)

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

Spinner delete items

I have developed an application in which i have one edit text value of edit text is entered in spinner on button clicked an the item i select to delete gets deleted but the problem is that when i delete the last item of spinner whole spinner list flushes . i want to delete only selected item(only last item)
My code is as follows :
#Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
///////////////////////////////////////////////////////////////
// grab our UI elements so we can manipulate them (in the case of the
// Spinner)
// or add listeners to them (in the case of the buttons)
m_myDynamicSpinner = (Spinner) findViewById(R.id.dynamicSpinner);
m_addItemText = (EditText) findViewById(R.id.newSpinnerItemText);
Button addButton = (Button) findViewById(R.id.AddBtn);
Button clearButton = (Button) findViewById(R.id.ClearBtn);
// //////////////////////////////////////////////////////////////
// create an arrayAdapter an assign it to the spinner
m_adapterForSpinner = new ArrayAdapter(this,
android.R.layout.simple_spinner_item);
((ArrayAdapter) m_adapterForSpinner)
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
m_myDynamicSpinner.setAdapter(m_adapterForSpinner);
// m_adapterForSpinner.add("dummy item");
// //////////////////////////////////////////////////////////////
// add listener for addButton
addButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
addNewSpinnerItem();
}
});
clearButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
clearSpinnerItems();
}
});
}
// //////////////////////////////////////////////////////////////
// add listener for addButton
private void addNewSpinnerItem() {
Log.v("TAG", "addNewSpinnerItems called");
if (m_addItemText.getText().length() == 0) {// ||(m_addItemText.getText().toString()==
// " ")){
Log.v("In if cndtn", "textHolder is of length 0");
Toast.makeText(getApplicationContext(), "The textView is empty",
Toast.LENGTH_LONG).show();
//m_myDynamicSpinner.clearFocus();
//m_myDynamicSpinner.setFocusable(false);
//m_addItemText.setFocusable(true);
} else {
CharSequence textHolder = "" + m_addItemText.getText();
// else{
Log.v("else", textHolder + "");
// m_adapterForSpinner.add(textHolder);
// }
((ArrayAdapter) m_adapterForSpinner).add(textHolder);
}
m_addItemText.setText("");
}
private void clearSpinnerItems() {
// m_adapterForSpinner.clear();
Log.v("TAG", "clearSpinnerItems called");
m_myDynamicSpinner
.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
// TODO Auto-generated method stub
Log.v("TAG", "Itemseleted to be removed is "
+ m_adapterForSpinner.getItem(pos).toString());
Log.v("Position of item", pos + "");
Object t = m_adapterForSpinner.getItem(pos);
Log.v("Object t ", (String) t);
((ArrayAdapter) m_adapterForSpinner).remove((CharSequence) t);
Log.v("Item removed", t + "");
// m_myDynamicSpinner.setSelected(false);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
// m_adapterForSpinner.add("dummy item");
}
for delete all items use:
mySpinner.setAdapter(null);
if you want to delete a particular item, remove this from m_adapterForSpinner and then:
mySpinner.setAdapter(m_adapterForSpinner);
Remember: methods "remove" and "clear" do not work with ArrayAdapter for Android 2.3.3 and lower. You'll receive error message "Unsupported operation.... bla bla bla". May be they work with Android 4.0 and up, I don't know.
Here is my solution which works even with minSdkVersion="5".
Create Spinner and fill it with test data
This code is in an activity form. Use ArrayList as data source for ArrayAdapter instead of array. It's important because you'll use its "remove" method later
List<String> reportFiles = new ArrayList<String>();
//fill some test data
reportFiles.add("aaaaaaaaaaaaa");
reportFiles.add("bbbbbbbbbbbbb");
reportFiles.add("ccccccccccccc");
//create spinner from corresponding layout xml file
Spinner spnReport = (Spinner) findViewById(R.id.spinner_report);
//create ArrayAdapter
ArrayAdapter reportAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_dropdown_item, reportFiles);
//set adapter to spinner
spnReport.setAdapter(reportAdapter);
//select first item in adapter - is not obligatory
spnReport.setSelection(0);
Remove selected item from Spinner
reportFiles.remove((String)spnReport.getSelectedItem());
//create new ArrayAdapter with modified ArrayList
reportAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_dropdown_item,reportFiles);
//set new array adapter to spinner
spnReport.setAdapter(reportAdapter);
//select first item
spnReport.setSelection(0);
For me the accepted answer throwed an exception so what I did was this.
ArrayAdapter adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_spinner_item, Collections.emptyList());
spinner.setAdapter(adapter);
I had the same problem. Doing this did solve the problem, by emptying the spinner:
mySpinner.setSelection(Adapter.NO_SELECTION);

Categories

Resources