Why does onItemSelected not fire straight after setSelection? - android

Why does onItemSelected not fire straight after setSelection on transportMode but only after the populateEditData method has finished?
I need onItemSelected to fire because I dynamically change the dataset for transport company in onItemSelected based on the value selected for transportMode
protected void onCreate(Bundle savedInstanceState)
{
transportMode = (Spinner) findViewById(R.id.spnrTransportMode);
transportModeAdapter = new CustomSpinnerAdapter(this, R.id.txtvTransporModeSpinner, R.layout.custom_spinner_row_item_mode, getResources().getStringArray(R.array.transport_mode_array), "mode");
transportMode.setAdapter(transportModeAdapter);
transportMode.setOnItemSelectedListener(this);
transportCompany = (Spinner) findViewById(R.id.spnrTransportCompany);
transportCompanyAdapter = new CustomSpinnerAdapter(this, R.id.txtvTransportCompany, R.layout.custom_spinner_row_item_company, getResources().getStringArray(R.array.transport_bus_companies_array), "company");
transportCompany.setAdapter(transportCompanyAdapter);
....
if(useActivityForEdit)
populateEditData();
}
public void populateEditData(int modeIndex, int companyIndex)
{
//Two spinners transportMode has onItemSelected listener
transportMode.setSelection(modeIndex);
//On item selected should trigger here then complete before setting transport company selection
transportCompany.setSelection(companyIndex);
}
public void onItemSelected(AdapterView<?> arg0, View view, int selectedIndex, long arg3)
{
//dynamically changes data of transportCompany adapter
if(transportMode.getSelectedItem().toString().equalsIgnoreCase("bus"))
{
transportCompanyAdapter = new CustomSpinnerAdapter(this, R.id.txtvContent, R.layout.custom_spinner_row_item_company, getResources().getStringArray(R.array.transport_bus_companies_array), "company");
transportCompany.setAdapter(transportCompanyAdapter);
transportCompany.setClickable(true);
}
else if(transportMode.getSelectedItem().toString().equalsIgnoreCase("train"))
{
transportCompanyAdapter = new CustomSpinnerAdapter(this, R.id.txtvContent, R.layout.custom_spinner_row_item_company, getResources().getStringArray(R.array.transport_train_companies_array), "company");
transportCompany.setAdapter(transportCompanyAdapter);
transportCompany.setClickable(true);
}
else if(transportMode.getSelectedItem().toString().equalsIgnoreCase("tram"))
{
transportCompanyAdapter = new CustomSpinnerAdapter(this, R.id.txtvContent, R.layout.custom_spinner_row_item_company, getResources().getStringArray(R.array.transport_tram_companies_array), "company");
transportCompany.setAdapter(transportCompanyAdapter);
transportCompany.setClickable(true);
}
}

Try adding transportCompany.setAdapter(transportCompanyAdapter); after transportCompany.setSelection(companyIndex);
and adding transportMode.setAdapter(transportModeAdapter); after transportMode.setSelection(modeIndex);

Related

how can get spinner values when I used if else then pass value to setonClick?

how can get spinner values when I used if else then pass value to setonClick?
in my code, I used this methods to set spinner values
DatabaseReference chk_sub = FirebaseDatabase.getInstance()......
chk_sub.addValueEventListener(new ValueEventListener() {
if(xxxxxx){
List<String> sub = new ArrayList<>();
sub.add(0, getApplicationContext().getResources().getString(R.string.choose_sub));
sub.add("USA");
sub.add("CA");
ArrayAdapter<String> dataSpinnerAdapter;
dataSpinnerAdapter = new ArrayAdapter(getApplication(), android.R.layout.simple_spinner_item, sub);
dataSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataSpinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(parent.getItemAtPosition(position).equals(getApplicationContext().getResources().getString(R.string.choose_sub))){
//do nothing
} else {
spinner_item = parent.getItemAtPosition(position).toString();
//Toast.makeText(parent.getContext(),"Selected : "+item, Toast.LENGTH_SHORT).show();
}
}
}
and I hope I can get spinner sub value because I need to judge
post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if( -- how can get spinner value in here? --){
//
}else {
Toast.makeText(getApplication(), getApplicationContext().getResources().getString(R.string.must_upload), Toast.LENGTH_SHORT).show();
}
}
});
If you just want selected spinner item to be used in if(condition=spinner value) on click event of post i.e., post.onClick(), just get the spinner selected item
your code will look like this
post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(spinner.getSelectedItem().equals("your compare value")){
// do whatever you want
}else {
Toast.makeText(getApplication(), getApplicationContext().getResources().getString(R.string.must_upload), Toast.LENGTH_SHORT).show();
}
}
});

How the spinner items not be kept selected as it is while rerunning the app

Hello I want to Know that how can i keep the spinner items selected throughout the activity so that if i come back form other activity to the activity that is consisting of spinner its still remain selected as it is.
The above statement that i have used that has been solved after this there is an another issue that whenever i restart my app its the selected portion remains as it is i want to know what i can do so that the spinner does not show what i have selected before
I have a code of spinner which i want to keep it selected throughout all the activities ,
daySelection = (Spinner)findViewById(R.id.daypreferance);
//String[] dayName = new String[]{
// "sunday", "monday", "tuesday"
//};
MyClass[] dayName ={
new MyClass("sunday", ""),
new MyClass("monday", "2"),
new MyClass("tuesday", "3")
};
ArrayAdapter<MyClass> adapter = new ArrayAdapter<MyClass>(this , R.layout.spinner_items ,R.id.spinneritem,dayName);
adapter.setDropDownViewResource(R.layout.spinner_items);
hotelSelection.setAdapter(adapter);
daySelection.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
preferDay= parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
public void onPause() {
super.onPause();
daySelection = (Spinner)findViewById(R.id.daypreferance);
SharedPreferences prefs = getSharedPreferences("prefs_name", Context.MODE_PRIVATE);
prefs.edit().putInt("spinner_indx", daySelection.getSelectedItemPosition()).apply();
}
public void onResume() {
super.onResume();
daySelection = (Spinner)findViewById(R.id.daypreferance);
SharedPreferences prefs = getSharedPreferences("prefs_name", Context.MODE_PRIVATE);
int spinnerIndx = prefs.getInt("spinner_indx", 0);
daySelection.setSelection(spinnerIndx);
}
I need to add the code that whenever I restart my app its the selected portion remains as it is I want to know what I can do so that the spinner does not show what I have selected before
try dis and let me know if any error....
daySelection = (Spinner)findViewById(R.id.daypreferance);
//String[] dayName = new String[]{
// "sunday", "monday", "tuesday"
//};
MyClass[] dayName ={
new MyClass("sunday", ""),
new MyClass("monday", "2"),
new MyClass("tuesday", "3")
};
ArrayAdapter<MyClass> adapter = new ArrayAdapter<MyClass>(this , R.layout.spinner_items ,R.id.spinneritem,dayName);
adapter.setDropDownViewResource(R.layout.spinner_items);
hotelSelection.setAdapter(adapter);
daySelection.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//check if preferDay has some valur rhen set on spinner
if(preferDay!=null)
{
daySelection.setSelection(Integer.parseInt(preferDay));
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
you can save state of activity and then set those values after came back
check this stack over flow question and this one
Save the state of the spinner in the onPause() method.
#Override
public void onPause() {
super.onPause();
Spinner spinner = (Spinner)findViewById(R.id.daypreferance);
SharedPreferences prefs = getSharedPreferences("prefs_name", Context.MODE_PRIVATE);
prefs.edit().putInt("spinner_indx", spinner.getSelectedItemPosition()).apply();
}
Restore the state of the spinner in the onResume() method.
#Override
public void onResume() {
super.onResume();
Spinner spinner = (Spinner)findViewById(R.id.daypreferance);
SharedPreferences prefs = getSharedPreferences("prefs_name", Context.MODE_PRIVATE);
int spinnerIndx = prefs.getInt("spinner_indx", 0);
spinner.setSelection(spinnerIndx);
}

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!)

Passing values to Activities with putExtra()

I am trying to pass a value on my ListView to my second activity using Intents. I am not sure how to pass the text value to the second activity my Intent leads to. Right now my Intent is able to connect to the second activity on tap but it doesn't pass the string of the tapped value.
I feel that I need to pass something into my launchEditItem() but I am not sure what. These are the two functions I am dealing with right now.
private void launchEditItem() {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", ); // list item into edit text
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
launchEditItem();
}
});
}
I'm not sure what value to place into the i.putExtra(), but I think I need to pass an argument into the launchEditItem().
This is what is currently in my second Activity:
public class EditItemActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_item);
Intent i = getIntent();
String ItemToEdit = i.getStringExtra("itemOnList");
// place into EditText using ItemToEdit
}
I'm also not sure how to place this String value (ItemToEdit) into an EditText box. I'm new to android dev so I'm learning as much as I can thank you!
* EDIT *
I guess I'm a bit too vague in my question. Here is the entire code of the small app I am working on
public class ToDoActivity extends Activity {
private ArrayList<String> todoItems;
private ArrayAdapter<String> todoAdapter; // declare array adapter which will translate the piece of data to teh view
private ListView lvItems; // attach to list view
private EditText etNewItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_do);
etNewItem = (EditText) findViewById(R.id.etNewItem);
lvItems = (ListView) findViewById(R.id.lvItems); // now we have access to ListView
//populateArrayItems(); // call function
readItems(); // read items from file
todoAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems); //create adapter
lvItems.setAdapter(todoAdapter); // populate listview using the adapter
//todoAdapter.add("item 4");
setupListViewListener();
setupEditItemListener();
}
private void launchEditItem() {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", ); // list item into edit text
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
launchEditItem();
}
});
}
private void setupListViewListener() {
lvItems.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View item, int pos, long id) {
todoItems.remove(pos);
todoAdapter.notifyDataSetChanged(); // has adapter look back at the array list and refresh it's data and repopulate the view
writeItems();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.to_do, menu);
return true;
}
public void onAddedItem(View v) {
String itemText = etNewItem.getText().toString();
todoAdapter.add(itemText); // add to adapter
etNewItem.setText(""); //clear edit text
writeItems(); //each time to add item, you want to write to file to memorize
}
private void readItems() {
File filesDir = getFilesDir(); //return path where files can be created for android
File todoFile = new File(filesDir, "todo.txt");
try {
todoItems = new ArrayList<String>(FileUtils.readLines(todoFile)); //populate with read
}catch (IOException e) { // if files doesn't exist
todoItems = new ArrayList<String>();
}
}
private void writeItems() {
File filesDir = getFilesDir(); //return path where files can be created for android
File todoFile = new File(filesDir, "todo.txt");
try {
FileUtils.writeLines(todoFile, todoItems); // pass todoItems to todoFile
} catch (IOException e) {
e.printStackTrace();
}
}
}
String[] link_list;
int currenttrack=0;
link_list=new String[]{
"W-TE_Ys4iwM",//1
"oozgmH3ZP14",//2
"o_v9MY_FMcw",//3
"36mCEZzzQ3o",//4
}
First activity
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
currenttrack=arg2;
Intent videoIntent=new Intent(MainActivity.this,VideoView.class);
videoIntent.putExtra("filename", link_list[currenttrack]);
startActivity(videoIntent);
}
});
In your Second Activity
// getting intent data
// get intent data
Intent i = getIntent();
Bundle extras = i.getExtras();
filename = extras.getString("filename");
Log.e("File Name", filename);
and your done :)
In your current Activity, create a new Intent:
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("new_variable_name","value");
startActivity(i);
Then in the new Activity, retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("new_variable_name");
}
I am not sure if i understood where is the value. Well if the value is in EditText do something like:
private void launchEditItem(String text) {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", text); // list item into edit text
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
EditText editView = (EditText) item.findById(R.id.ItemToEdit);
String text = editView != null ? editView.getText().toString() : "";
launchEditItem(text);
}
});
}
1 - I have some doubt with:
i.putExtra("itemOnList", );
You'd better pass a value:
i.putExtra("itemOnList", "something");
2 - To valorize a control, you must obtain a reference to it first. Something like:
EditText edt =
(EditText) findViewById(R.id.activity_edit_item_my_EditText); // or whatever id you assigned to it (it MUST HAVE AN ID)
Do it AFTER setContentView().
Then you can set it's text like:
edt.setText(ItemToEdit); // Now it should contain "something"
Just as simple as that
[EDIT]
If you aren't sure what to pass so is to pass in the "tapped" value in the ListView into the putExtra, modify your listview click handler code:
list.setOnItemClickListener
(
new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
// TODO Auto-generated method stub
Intent videoIntent = new Intent(MainActivity.this, VideoView.class);
videoIntent.putExtra("filename", (((TextView) v).getText().toString());
startActivity(videoIntent);
}
}
);
It should work immediately.
01: Current Activity
String pass_value ="value";
Intent intent = new Intent(getApplicationContext(),NewActivity.class);
intent.putExtra("var_name",pass_value);
startActivity(intent);
02: New Activity
String value = getIntent().getExtras().getString("var_name");

Problem with reassigning spinner value

I trying to get a value off a spinner and then pass it onto another java file. I have a spinner in which has a number of values. I change this value, convert it to a string, then on the click of a button I use and intent to pass this information onto the other java file to do stuff with.
The problem I am having is that once I initially set the spinner value even though I change the spinner the value that is passed on is not changed.
Even if I change the spinner the position value that is passed on to LiquidFlowResults is still possize = 0 as originally assigned.
/** initially setting spinner value */
int possize = 0;
String pipeSizeString = Integer.toString(possize);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button calculateButton = (Button) findViewById(R.id.button1);
calculateButton.setOnClickListener(mEnableListener);
Spinner spinnerPipeSize = (Spinner) findViewById(R.id.spinnerPipeSize);
ArrayAdapter<CharSequence> adapterpipesize = ArrayAdapter.createFromResource(this, R.array.pipesize_array, android.R.layout.simple_spinner_item);
adapterpipesize.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerPipeSize.setAdapter(adapterpipesize);
spinnerPipeSize.setOnItemSelectedListener(new PipeSizeOnItemSelectedListener());
/** Listening for spinner position */
public class PipeSizeOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int possize, long id) {
String pipeSizeString = Integer.toString(possize);
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
}
/** passing on information on click of button */
private OnClickListener mEnableListener = new OnClickListener() {
public void onClick(View view)
{
Intent intent = new Intent(LiquidFlow.this, LiquidFlowResults.class);
Bundle sizeposition = new Bundle();
sizeposition.putString("pipeSizeStringPositionMoved", pipeSizeString);
intent.putExtras(sizeposition);
startActivity(intent);
}
};
There is no need for PipeSizeOnItemSelectedListener. You can just call getSelectedItemPosition in OnClickListener.

Categories

Resources