I have a Spinner on my Activity with items "hello" and "goodbye" for user to choose. These items, when device is in Spanish, would be "hola" and "adios", as strings are chosen from string-es/ instead from string.
The problem is that I've got many switch cases on my code like this:
switch(spinnerSelectedItem){
case "hello":
case "hola":
//do something
break;
case "goodbye":
case "adios":
//do something else
break;
}
I've tried to create a final String initialized with string resource, but it complains saying "Constant Expression Required"
final String resHello = getResources().getString(R.string.helloText);
final String resGoodbye = getResources().getString(R.string.goodbyeText);
switch(spinnerSelectedItem){
case resHello :
//do something
break;
case resGoodbye :
//do something else
break;
}
This is a simplified version, I have many more items and more than two languages
One solution would be to use strings id instead of value, or use if clauses instead of switch, but I would like to find a "smart" or "clean" way to do this, do you have any idea?
You can use the getIdentifier method of Resources to get the id of the string. eg:
getResources().getIdentifier(resValue, "string", getPackageName())
This will return the id which you can then use in your switch statements and compare.
Related
Smiley Rating bar
Hello,I just getting started with android ,and I am trying to use smiley rating bar,i add it to my project,
my problems is :
1-Get current selection (the choice of the user) i read the instructions on the git,but i didn't understand how can i get the user choice.
2-send that choice or the selection of the user to an email address without opening the email app ( directly send ).
this the git https://github.com/sujithkanna/SmileyRating.
Bind the view from xml in your java class by smileRatingBar = findViewById(R.id.smile_rating_bar_id);
then you need to add listener for it:
smileRatingBar.setOnSmileySelectionListener(new SmileRating.OnSmileySelectionListener() {
#Override
public void onSmileySelected(#BaseRating.Smiley int smiley, boolean reselected) {
// reselected is false when user selects different smiley that previously selected one
// true when the same smiley is selected.
// Except if it first time, then the value will be false.
switch (smiley) {
case SmileRating.BAD:
Log.i(TAG, "Bad");
break;
case SmileRating.GOOD:
Log.i(TAG, "Good");
break;
case SmileRating.GREAT:
Log.i(TAG, "Great");
break;
case SmileRating.OKAY:
Log.i(TAG, "Okay");
break;
case SmileRating.TERRIBLE:
Log.i(TAG, "Terrible");
break;
}
}
});
Your first query i.e. how to know the current selection (the choice of the user) can be known by the following way :
SmileRating smileRating = findViewById(R.id.feedback_rating);
int level = smileRating.getRating();
Where Level will return 0 if NONE selected else will return 1 to 5 ranging where 1 is Terrible while 5 is Great.
im writing a simple app where you can input data to database through app. I have to make conditions for example: you can't put digits in Name field. I know I have to do this in onClick, but I dont really know how. Can you help me?
public void onClick(View v)
{
switch (v.getId()){
case R.id.insertButton:
dm.insert(editName.getText().toString(),
editAge.getText().toString(),
editSurname.getText().toString(),
editSex.getText().toString(),
editPesel.getText().toString());
break;
case R.id.selectAllButton:
showData(dm.selectAll());
break;
case R.id.searchButton:
showData(dm.searchName(editSearch.getText().toString()));
break;
case R.id.deleteButton:
dm.delete(editDelete.getText().toString());
break;
}
}
You can cast the input to String in a try/catch, or set the input type to integer (use android:inputType="number" in your xml)
I know I have to do this in onClick.
onClick is perhaps not the ideal place as the user has already input the data and is therefore after the fact, as such.
Frequently it would be better to not allow unacceptable(sic) input when the user tries to enter such input.
There are alternatives, perhaps the simplest is to restrict the characters that can be input via the XML definition of the EditText e.g. to restrict to letters only then you could use :-
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
To allows spaces you could use (space added between lower and upper case) :-
android:digits="abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ";
However, really you should use a String Resource so you could easily cope with multiple languages (locales).
Therefore you could create a String resource (res/values/strings.xml) such as :-
<string name="alphabet">"abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ"</string>
and then use :-
android:digits="#string/alphabet"
Programatically (alternatively) you could use an InputFilter :-
mAlphaBet = getResources().getString(R.string.alphabet);
// Define the Input Filter
InputFilter inputfilter = new InputFilter() {
public CharSequence filter(CharSequence s,
int start,
int end,
Spanned dest,
int deststart,
int destend) {
for (int i=0; i < end; i++) {
// If not in the alphabet then suppress input
if(!mAlphaBet.contains(String.valueOf(s.charAt(i)))) {
return "";
}
}
// Indicate input is OK
return null;
}
};
// Apply filters (just the 1) to the EditText
editName.setFilters(new InputFilter[]{inputfilter});
mAplhaBet is retrieved from the resources as above, again catering for locales if defined.
I have a simple switch case:
switch (view.getId()){
case R.id.one:
break;
case R.id.two:
break;
}
What I would like to do is write something smart and self sufficient to obtain the text value of the mentioned textviews. For example r.id.one holds text of 1, while r.id.two holds text of 2.
Whenever I press 1 I want to get it's text value.
I know it can be done by the following way:
TextView one = (TextView)findviewbyid(r.id.one);
one.getText();
But with the increase of textviews it will be hard to maintain, as I want to use the obtained value later on.
Thanks advance to all the downvotes, really helpful.
Solution:
switch (view.getId()){
case R.id.one:
String number = (String) ((TextView)view).getText();
break;
case R.id.two:
String number = (String) ((TextView)view).getText();
break;
}
Now number receives the value from the textview. Thanks all.
Instead of a switch, you can try to get the text if the view is any TextView. For instance:
if (view instanceof TextView) {
((TextView) view).getText();
}
Try Butterknife library.
Use something like :
#OnClick({R.id.textviewID1, R.id.textviewID1)
protected void onTextViewClick(TextView textView) {
textView.getText();
}
This allows you to use the same callback function for each textview using just a simple annotation.
And makes the code more readable as well.
I'm using the following code to update an image switcher and corresponding strings when the next button is clicked,but I'm having trouble referencing the strings from the res/strings folder in the GetMyString().
For example one of my strings is named cutString.How do I reference it instead of YOUR_STRING_01? Is there a simple way to do call the string or is there a flaw in this implementation?
btnNext.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
currentIndex++;
// If index reaches maximum reset it
if(currentIndex==messageCount)
currentIndex=0;
imageSwitcher.setImageResource(imageIds[currentIndex]);
tView.setText(getMyString(clicks++));
}
});
//method called to update textview strings.
public String getMyString(int variable){
switch(variable){
case 1:
return YOUR_STRING_01;
break;
case 2:
return YOUR_STRING_02;
break;
case 3:
return YOUR_STRING_03;
break;
}
So I notice that your implementation doesnt necessarily have reference to a context so you will need to do something like this.
//method called to update textview strings.
public String getMyString(final int variable, final Context applicationContext){
switch(variable){
case 1:
return applicationContext.getResources().getString(R.string.something);
break;
case 2:
return applicationContext.getResources().getString(R.string.something2);
break;
case 3:
return applicationContext.getResources().getString(R.string.something3);
break;
}
}
You can access Strings stored in the strings.xml via the getString() function.
Example:
XML file saved at res/values/strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello!</string>
</resources>
This layout XML applies a string to a View:
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
This application code retrieves a string:
String string = getString(R.string.hello);
You can use either getString(int) or getText(int) to retrieve a string. getText(int) will retain any rich text styling applied to the string.
use either String str = getResources().getString(R.string.cutString); or String str = getString(R.string.cutString);
both options are part of Context - http://developer.android.com/reference/android/content/Context.html
You reference your string as any other resource, using R class, i.e.:
R.string.cutString;
To get value, use getString():
String text = getResources().getString(R.string.cutString);
Every class that inherits from the Context class has a method called getString, which you can use to retrieve your value.
Assuming that btnNext is inside your activity you just have to call
getString(R.string.cutString)
and the result should be that value of your string.
See http://developer.android.com/reference/android/content/Context.html#getString(int)
Rather than returning a String from getMyString(), why don't you return the resource ID (R.string.cutString) and then use TextView.setText(int resid) to set the text. Essentially, you should just change the return type of getMyString() to int and the return value from the switch statement to something like this:
public int getMyString(int variable){
switch(variable){
case 1:
return R.string.YOUR_STRING_01;
break;
case 2:
return R.string.YOUR_STRING_02;
break;
case 3:
return R.string.YOUR_STRING_03;
break;
}
This method is called at button click because of assigned name to the
"OnClick property" of the button,what should be the correct code of case in below coding.it giving error that it should be constant expression in case.
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
RadioButton AButton = (RadioButton) findViewById(R.id.radio0);
RadioButton BButton = (RadioButton) findViewById(R.id.radio1);
if (text.getText().length() == 0) {
Toast.makeText(this, "Please enter a valid number",
Toast.LENGTH_LONG).show();
return;
}
You must be using this code in a project that will be marked as library. Is It?
If yes, then you must need to understand that in this case view.getId() value can not be used as constant.
In such projects, you can use if else statements.
The reason behind this is, in the main project if you would have defined a resource with the same id, there would be wrong result returned or initialized.
So, this is to avoid that situation as it would be more difficult to debug.
Use, if - else statement.
Also, I dont remember the ADT version, but after that view ids are not considered as the constants.
Just convert your switch case statement to if statement and it should suffice. For explanation read switch case statement error: case expressions must be constant expression