I am new to Android Studio, so I don't know much about the functions. I am using a spinner which allows me to choose from different languages.
In my MainActivity class, I have the following code:
String lang="eng";
dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object language = parent.getItemAtPosition(pos);
TextView L = (TextView) findViewById(R.id.spinLang);
//for deciding tessdata file
if(language.toString().equals("Bengali"))
lang="ben";
if(language.toString().equals("English"))
lang="eng";
if(language.toString().equals("Gujarati"))
lang="guj";
if(language.toString().equals("Hindi"))
lang="hin";
if(language.toString().equals("Kannada"))
lang="kan";
if(language.toString().equals("Tamil"))
lang="tam";
L.setText("You selected " + language + " and " + lang);
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
My text view shows the display depending on what language I choose from the spinner. However, I believe the change in variable <lang> is limited to only this method.
Outside this method, when I am working with <lang>, it gives the result for <lang="eng"> all of the time.
How can I make the change in <lang> outside this method? Thanks in advance.
Related
I found error in findViewById in static function.
my function is--
public static void onYearSelect() {
Spinner yearSelector;
String yearName;
yearSelector = (Spinner) findViewById(R.id.year_submit);
yearName = yearSelector.getSelectedItem().toString();
}
is there any way to solve this error!
can i store value of Spinner in yearName as String
You need to add view inside function as parameter.
public static void onYearSelect(View view) {
Spinner yearSelector;
yearSelector = (Spinner) view.findViewById(R.id.year_submit);
yearName = yearSelector.getSelectedItem().toString();
}
The view which contains your layout data.
When you call that function add onYearSelect(rootView) here rootView have the layout view.
EDIT 1:
What is View here ?
A View in Android is a widget that displays something. Buttons, listviews, imageviews, etc. are all subclasses of View. When you say "change view" I assume you mean change the layout by using setContentView(). This usually only needs to be done once per activity. An Activity is basically what you are referring to as a screen.
You can read more here.
Set setOnItemSelectedListener on spinner object and inside onItemSelected() you can set value of yearName. Like below,
yearSelector.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String yearName = parentView.getItemAtPosition(position).toString()
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}});
I followed steps in how to change value of textview according to selected item and here is a piece of the code
public void onCreate(Bundle savedInstanceState){.......
final TextView privacyTextView = (TextView) findViewById(R.id.eventPrivacy);
privacySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id3) {
final String selectedItem = parent.getItemAtPosition(position).toString();
privacyTextView.setText(selectedItem);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
list is :
<string-array name="privacy_levels">
<item>Everyone</item>
<item>Friends of Friends</item>
<item>Friends Only</item>
<item>Customize</item>
</string-array>
I have text view with value : privacy when running app it's automatically changed to Everyone -frist one on the list- so what is going wrong ?!!!
Add android:prompt in Spinner xml and set a name like
android:prompt="Privacy";
So first time it will show privacy then user can select from the drop down list.
Try this...!
final String selectedItem = parent.getSelectedItem().toString().trim();
privacyTextView.setText(selectedItem);
If you want to get first item as privacy then you need to add another item in your array as Privacy.
There is a attribute called android:spinnerMode this is used to get the spinner in two modes as dialog or dropdown.
where as the attribute android:prompt is to get the spinner Title or Heading after opening it(in Dialog mode).
Just try to this so you will get selected string:
String name = spinner.getSelectedItem().toString();
I have a spinner which contains dynamic data which is displayed over 2 lines. What I require help with is dislaying only part of the spinners value (ItemArrayName[i]) within the spinner text box.
To calrify in the popup when the spinner is clicked, I require the full text, however when the item has been select I only require the item name.
e.g.
Within the App:
Item Name
Within the spinner selection pop out:
Item Name
Atk = 10, Def = 10
Java Code:
ArrayList<String> ItemArrayList = new ArrayList<String>();
for(int i = 0; i < ItemArrayName.length; i++)
{
ItemArrayList.add(ItemArrayName[i] + "\nAtk = " + String.valueOf(ItemArrayAtk[i]) + ", Def = " + String.valueOf(ItemArrayDef[i]));
}
Spinner spnItem = (Spinner) view.findViewById(R.id.UseItem);
ArrayAdapter<String> adpItem = new ArrayAdapter<String> (context, R.layout.spinnerrow, ItemArrayList);
spnItem.setAdapter(adpItem);
spnItem.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long arg3)
{
//String city = "The item is " + parent.getItemAtPosition(position).toString();
//Toast.makeText(parent.getContext(), city, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
Thanks in advance
How about using a Hashtable to map what you display in the spinner to your more detailed popup string?
EDIT:
Here's a primitive and possibly non compiling modification to your code using a hashtable as described:
// EDIT #1: Create a hashtable to lookup stuff:
final Hashtable<String, String> vals = new Hashtable<String, String>();
for(int i = 0; i < ItemArrayName.length; i++)
{
vals.put(ItemArrayName[i], ItemArrayName[i] + "\nAtk = " + String.valueOf(ItemArrayAtk[i]) + ", Def = " + String.valueOf(ItemArrayDef[i]));
}
Spinner spnItem = (Spinner) view.findViewById(R.id.UseItem);
// EDIT #2: Extract the array of hash keys to show in your list:
ArrayAdapter<String> adpItem = new ArrayAdapter<String> context, R.layout.spinnerrow, vals.keySet().toArray(new String[vals.size()]));
spnItem.setAdapter(adpItem);
spnItem.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long arg3)
{
// EDIT #3: retrieve the full string from the hashtable using "get":
String city = "The item is " + vals.get(parent.getItemAtPosition(position).toString());
//Toast.makeText(parent.getContext(), city, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
Try mapping your short text to your long text.
HashMap<String,String> itemValues = new HashMap<String,String>();
itemValues.add("short text","the full long text that pops up when item is selected");
String longTextToDisplay = itemValues.get(currentSelectedShortText);
Of course this is a simplified example and this could be made more flexible, but this is the basic idea. You're just saying "this short text goes with this long text."
Everyone makes this much harder than it has to be. If the data is displayed in the spinner already, you can grab it from there without having to refer to the backing data.
Assuming you have a LinearLayout containing the two textviews (call them tv1 and tv2) as your row layout for the spinner, and you want the value of tv2, you could do this:
public void onItemSelected(AdapterView<?> parent, View view, int position, long arg3)
{
TextView tvResult = (TextView) view.findViewById(r.id.tv2);
String city = tvResult.getText().toString();
}
EDIT
I misunderstood your question... that I know of there is no way to make the closed spinner box display text different from the actual selection within the spinner using an ArrayAdapter. If there is, I'd be interested in seeing/reading about it.
I can think of a way to do it with a CursorAdapter, but as I said above, I can't think of any way to manage it for an ArrayAdapter.
The one option I can think of would be to find the spinner class in the android source, copy it out and modify it to make your own spinner class that is capable of such a function.
OK, I've read around and see that Java only passes by value, not by reference so I don't know how to accomplish this.
I've 6 Spinners in an Android Activity that are populated with different SQLite queries.
The code to populate each Spinner and set the OnItemSelectedListener is very similiar so I was hoping to refactor to one method and call it 6 times with each Spinner ID and Sqlite query.
How do I get the Spinner onItemSelectedListener to change the right instance member on each different Spinner?
public void fillSpinner(String spinner_name, final String field_name) {
// This finds the Spinner ID passed into the method with spinner_name
// from the Resources file. e.g. spinner1
int resID = getResources().getIdentifier(spinner_name, "id",
getPackageName());
Spinner s = (Spinner) findViewById(resID);
final Cursor cMonth;
// This gets the data to populate the spinner, e.g. if field_name was
// strength = SELECT _id, strength FROM cigars GROUP BY strength
cMonth = dbHelper.fetchSpinnerFilters(field_name);
startManagingCursor(cMonth);
String[] from = new String[] { field_name };
int[] to = new int[] { android.R.id.text1 };
SimpleCursorAdapter months = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item, cMonth, from, to);
months.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(months);
// This is setting the Spinner Item Selected Listener Callback, where
// all the problems happen
s.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Cursor theCursor = (Cursor) parent.getSelectedItem();
// This is the problem area.
object_reference_to_clas_member_of_field_name = theCursor
.getString(theCursor.getColumnIndex(field_name));
}
public void onNothingSelected(AdapterView<?> parent) {
// showToast("Spinner1: unselected");
}
});
}
You call this method like this fillSpinner("spinner1","strength");.
It finds the spinner with id spinner1 and queries the database for the strength field. field_name, which is strength in this example had to be declared a final variable to be used in the onItemSelectedListener or I'd get the error Cannot refer to a non-final variable field_name inside an inner class defined in a different method.
But how do I get the onItemSelectedListener to change the value of a different instance member when each different Spinner is used? This is the all important line of code:
object_reference_to_clas_member_of_field_name = theCursor .getString(theCursor.getColumnIndex(field_name));
I can't use a final String as the variable will obviously change when the user selects a different value. I've read around a good bit and am stumped to a solution. I can just copy and paste this code 6 times and forget about refactoring but I'd really like to know the elegant solution. Post a comment if you don't understand my question, I'm not sure if I explaned myself well.
You can do it, by passing additional class as parameter of fillSpinner method:
A. Create interface
public interface OnSpinnerValueSelected {
void onValueSelected(String selectedValue);
}
B. Change your method a bit:
public void fillSpinner(String spinner_name, final String field_name,
final OnSpinnerValueSelected valueChangeListener) {
// Prepare spinner
s.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Cursor theCursor = (Cursor) parent.getSelectedItem();
valueChangeListener.onValueSelected(theCursor
.getString(theCursor.getColumnIndex(field_name)));
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
C. provide listener:
fillSpinner("spinner1","strength", new OnSpinnerValueSelected() {
public void onValueSelected(String selectedValue) {
yourObject.setField(selectedValue);
}
});
Refactor your listener to a new "class". Initialize with the right arguments/instances as required so that the repeated "code" is reusuable.
Right, this is how I managed it but I'm still open to new suggestions for an accepted answer and I also created a bounty.
I didn't create a new class like panzerschreck suggested so I'm posting this as a new answer to my own question. Bit of a hack but I just created an if..then..else statement in the listener to check what spinner was selected and then set a different instance member.
s.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Cursor theCursor = (Cursor) parent.getSelectedItem();
if (field_name.equalsIgnoreCase("strength")) {
strength=theCursor.getString(theCursor.getColumnIndex(field_name));
} else if (field_name.equalsIgnoreCase("ring")) {
ring_gauge=theCursor.getString(theCursor.getColumnIndex(field_name));
} else if (field_name.equalsIgnoreCase("country")) {
country=theCursor.getString(theCursor.getColumnIndex(field_name));
} else if (field_name.equalsIgnoreCase("wrapper")) {
wrapper=theCursor.getString(theCursor.getColumnIndex(field_name));
} else if (field_name.equalsIgnoreCase("length")) {
length=theCursor.getString(theCursor.getColumnIndex(field_name));
} else if (field_name.equalsIgnoreCase("price")) {
price=theCursor.getString(theCursor.getColumnIndex(field_name));
}
// showToast(category);
}
public void onNothingSelected(AdapterView<?> parent) {
// showToast("Spinner2: unselected");
}
});
Here are the class members
private String strength,ring_gauge,country,wrapper,length,price;
Bit of hack but without Java allowing objects to be really passed by reference, it's all I could do.
In an android website, I found an article about a widget similar to a drop-down list for selecting items. (Following is the link to the site; and it shows all the codes).
http://developer.android.com/resources/tutorials/views/hello-spinner.html
It uses the following code to display a message once you have selected a planet.
Toast.makeText(parent.getContext(), "Planet is Selected", Toast.LENGTH_LONG).show();
But this message "Planet is Selected" is only going to display for about 3 seconds and then it disappears. Can you please tell me how can I make the message stay on the screen for a longer time. Or how can I output the "Planet is Selected" message as a text layout in to the screen(So that it will stay on the screen permanently till I select another item from the list)? How can I use addView(tv) instead of setContentView(tv) Any help would be greatly appreciated.
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
if (parent.getItemAtPosition(pos).toString().equals("Mars"))
{ TextView tv = new TextView(HelloSpinner.this);
tv.setText(parent.getItemAtPosition(pos).toString() + "Planet is Selected");
setContentView(tv); //How can I use addView(tv); here?
//Toast.makeText(parent.getContext(), "Planet Selected", Toast.LENGTH_LONG).show();
}
}
public void onNothingSelected(AdapterView parent)
{
// Do nothing.
} }
If you want it to stay permanently on the screen, why not use a TextView and set your value to that instead of a Toast.
If you have any problems with not being able to use TextView, ie undefined. You should take a look at the textview documentation, as it is very well described there.
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
TextView tv = new TextView(this);
tv.setText(parent.getItemAtPosition(pos).toString());
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
third parameter Toast.LENGTH_LONG is time. so you can set any integer value ( not sure second or millisecond) ,. then on specific event call toast.hide() ;
toast is good choice for show message for some times only . so use textView if possible
create TextView with activity context :
TextView tv = new TextView(ActrivityName.this)
else if not an activity
TextView tv = new TextView(parent.getContext())