android spinner is trigger by magic - android

I have a Spinner in my application which is installed and configured as follow:
final Spinner left = getLeftShiftSpinner(); //simple gets the Spinner by Id
left.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
left.setSelection(0);
try {
Log.d("test", "SHIFT_LEFT");
String s = content.shiftLeft(i);
content.clear();
updateScreen(s);
} catch (ScreenContent.WrongSyntaxException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
When I compile everything and the app starts on my device I get the Output "SHIFT_LEFT" from the Log.d(...) but I DID NOT click on anything at all. The application simply started and then by doing nothing the onItemSelectedListener is triggered?? Does anyone know why??

When the view is first inflated/activity loaded the spinner selects the first item in its list, triggering on the onItemSelected listener.
EDIT: example using boolean variable to ignore first trigger
boolean isInitTrigger = true;
final Spinner left = getLeftShiftSpinner(); // simple gets the Spinner by Id
left.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(isInitTrigger){
isInitTrigger = false;
return;
}
left.setSelection(0);
try {
Log.d("test", "SHIFT_LEFT");
String s = content.shiftLeft(i);
content.clear();
updateScreen(s);
} catch (ScreenContent.WrongSyntaxException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});

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();
}
}
});

onItemSelected method help - loading an Intent

I have tried Googling but couldn't get an answer specific to my problem.
I am trying to launch an activity when a item is clicked. The code is below:
public class ListOfCircuits extends Activity
{
String[] raceTrackList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.list_of_circuits);
raceTrackList = getResources().getStringArray(R.array.tracklist_array);
Spinner s1 = (Spinner) findViewById(R.id.circuitListSpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, raceTrackList);
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int arg2, long arg3)
{
int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(),
"You have selected: " + raceTrackList[index],
Toast.LENGTH_SHORT).show();
String intentString;
String circuitChosen = raceTrackList[index].toString();
intentString = ("net.learn2develop." + circuitChosen);
startActivity(new Intent(intentString));
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
}
});
}
However at the moment it loads straight into the activity at the top of the list (TopGear). How do you get around this so that a user can see the list and select it i.e. not start an intent immediately - use an if statement?
Thanks.
This happens because the method is called the first time the Activity loads. There should be a better way to handle this but you could simply set a boolean flag
public class ListOfCircuits extends Activity
{
String[] raceTrackList;
boolean go = false;
#Override
protected void onCreate(Bundle savedInstanceState)
{
then set it to true the first time it is called and check it there
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int arg2, long arg3)
{
if (go)
{
// your code
intentString = ("net.learn2develop." + circuitChosen);
startActivity(new Intent(intentString));
}
else
{ go = true; }
}
CodeMagic think I have it working like a boss now:
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int arg2, long arg3)
{
if(go)
{
int index = arg0.getSelectedItemPosition();
if(index == 0)
{
Toast.makeText(getBaseContext(),
"Please select a race crcuit.",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(),
"You have selected: " + raceTrackList[index],
Toast.LENGTH_SHORT).show();
String intentString;
String circuitChosen = raceTrackList[index].toString();
intentString = ("net.learn2develop." + circuitChosen);
startActivity(new Intent(intentString));
}
}
else
{
go = true;
}
}
I only load Intents that I want (race circuits) and if a user selects "Choose from below:" only one relevant Toast gets displayed.
Thanks.
The answer to my answer was:
Add the Boolean as codeMagic suggested and amend my array to:
<string-array name="tracklist_array">
<item>Choose from below:</item>
<item>TopGear</item>
<item>Snetterton</item>
<item>Silverstone</item>
<item>Donnington</item>
</string-array>
From
<string-array name="tracklist_array">
<item>TopGear</item>
<item>Snetterton</item>
<item>Silverstone</item>
<item>Donnington</item>
</string-array>
And the final code is for Java - see below.
Thanks again.

Spinner OnItemSelectedListener Issue

I have problem with spinner control. I am trying to set spinner items dynamically. Initially I have one item in spinner.
When I try to register the spinner.setOnItemSelect Listener, it immediately call onItemSelected method of it. However I don't want to call this method as soon as my activity get started.
So for this I put a following condition.
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
Spinner spinner;
String[] str_arr = {"aaaaaaaa"};
private int mSpinnerCount=0;
private int mSpinnerInitializedCount=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner);
spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, str_arr));
spinner.setOnItemSelectedListener(this);
mSpinnerCount=1;
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
if (mSpinnerInitializedCount < mSpinnerCount) {
mSpinnerInitializedCount++;
}
else {
Intent intent = new Intent(this, NextActivity.class);
startActivity(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
But when I try to select an item on spinner it gives following warning in logcat,
09-03 13:02:02.528: W/InputManagerService(59): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#450fafb8
I get the idea that until and unless Item of spinner won't change this method won't be called.
But I have one value in spinner, so how to get the focus, any idea?
Try this to what i said in comment...
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
if (position > 0) {
//Your actions
}
else {
// Nothing or can show a toast to say user to select a value...
}
}
Try like this
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
if (position != 0) {
//put your actions here
}
else {
// nothing here or toast
}
}
I think the below code are not right because you implements OnItemSelectedListener
spinner.setOnItemSelectedListener(this);
You get this warning when you try to open already opened window, or try to do something like onFocus on already focused view.
Here you already have the item selected in the Spinner

Deleting last item from spinner deletes the entire list

I am trying to use a spinner control that will enable the user to delete any list element.
I have an 'add' button to add elements to the list, and a 'delete' button that removes the currently-displayed item from the list.
It works as expected except when the user deletes the last item in the list. At that point, all of the list's items are deleted.
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 (for 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);
// 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() {
if (m_addItemText.getText().length() == 0) {
Toast.makeText(getApplicationContext(), "The textView is empty", Toast.LENGTH_LONG).show();
} else {
CharSequence textHolder = "" + m_addItemText.getText();
((ArrayAdapter) m_adapterForSpinner).add(textHolder);
}
m_addItemText.setText("");
}
private void clearSpinnerItems() {
m_myDynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object t = m_adapterForSpinner.getItem(pos);
((ArrayAdapter) m_adapterForSpinner).remove((CharSequence) t);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO
}
});
}
Does anyone have any ideas or suggestions on how to make this work?
The problem with your code is that the deletion is inside the onItemSelected callback, which gets called every time you are deleting an entry, thus deleting recursively until you effectively do not have any more entries to select. If you add a log inside that method:
Log.d("Spinner", "Count: " + m_adapterForSpinner.getCount());
you will see what I mean. I'm sure you can come up with more elegant code, but a quick and dirty hack is to set up a boolean flag to stop the recursion after the first deletion. See the snippet below and add the commented lines to your own code:
public class SpinnerTest extends Activity {
Spinner m_myDynamicSpinner;
EditText m_addItemText;
ArrayAdapter m_adapterForSpinner;
public static boolean cleared = false; // <--- set up a static boolean here
#Override
public void onCreate(Bundle savedInstanceState) {
// all your code unchanged
clearButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
cleared=false; // <--- nope, we did not clear the value yet
clearSpinnerItems();
}
});
}
// code unchanged
private void clearSpinnerItems() {
m_myDynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object t = m_adapterForSpinner.getItem(pos);
Log.d("Spinner", "Count: " + m_adapterForSpinner.getCount());
if (!cleared) // <--- did I do it already?
((ArrayAdapter) m_adapterForSpinner).remove((CharSequence) t);
Log.d("Spinner", "Count: " + m_adapterForSpinner.getCount());
cleared=true; // I did it!
}
// code unchanged
i cann't understand your question.any way you can get the position of the selected item by using getSelectedItemPosition() method.

Gridview Button Adapter context menu

I have a phrasebook, with the ability to save the sample to SD. I use a Gridview set up with the following code in place for the button adapter:
public View getView(int position, View convertView, ViewGroup parent) {
try {
final Sample sample = board.getSamples().get(position);
if (sample != null) {
Button button = new Button(context);
button.setText(sample.getName());
button.setTextColor(Color.WHITE);
button.setTextSize(12);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
context.play(sample);
}
});
// TODO Implement this correctly.
button.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View v) {
return context.saveToSD(sample);
}
});
return button;
}
} catch (IndexOutOfBoundsException e) {
Log.e(getClass().getCanonicalName(), "No sample at position "
+ position);
}
return null;
}
I am looking to integrate a context menu here on a Long press, to give the option of where to save the sample. I don't seem to be able to register the button for the context menu within this method (ie registerForContextMenu(button), as it gives me errors.
I am a bit stumped here, any pointers would be a great help.
Thanks
I take it that this is an old post but I came across it today as I was looking for an answer on the same topic. Like the question here I have a grid of items and wanted to show a context menu on long click.
I am not using a contextmenu but instead I am using an AlertDialog.
gridview.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id)
{
showOptionsMenu(position);
return true;
}
});
public void showOptionsMenu(int position)
{
new AlertDialog.Builder(this)
.setTitle("test").setCancelable(true).setItems(R.array.myOptions,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i) {
//take actions here according to what the user has selected
}
}
)
.show();
}
Hope this helps.

Categories

Resources