Using Reflection with Android - android

I faced an interesting problem today. I have 4 strings which I need to show on app on random basis. So I simply added the strings to my string.xml and was setting my textview to show the text as
textView.setText(R.string.text_1);
or (if random number was 2)
textView.setText(R.string.text_2);
and so on
I observed that the change is just in last character, so tried using reflection
Class c = Class.forName("com.startpage.mobile.R$string");
Field field = c.getDeclaredField("text_"+num); //num is 1/2/3/4
System.out.println("********** "+field.get(null));
Now the field.get(null) actually return the Id (hexadecimal number in R.java) value instead of string value I would expect.
Is there a way to fetch actual value of string using reflection or this is something in android which I will have to live with?

getResources.getString(resourceId);

R.string.text_2
will always return the hex number. To really get the string value, you have to try the following
MyActivity.this.getResources.getString(R.string.text_2);

You can simply request your resource ID from the resource manager:
Class c = Class.forName("com.startpage.mobile.R$string");
Field field = c.getDeclaredField("text_" + num);
int resId = (int)field.get(null);
String text = this.getResources().getString(resId);
textView.setText(text);

I suggest you to use array of strings and choose random item from it

Related

Two different return types in if else statement in data binding

I am trying to set text in TextView using data binding. I am using if else statement and if the value is true I want to set String to that TextView and in the other case I want to assign id of the String resource. My Code:
android:text="#{object.isTrue ? object.getString : object.getStringId}"
But when I try to do it I get error that Integer cannot be converted to String.
Everything is alright when I try to assign this String resource it directly like this:
android:text="#{object.getStringId}"
Is it somehow possible to use in that if else statement two different return types?
Yes, you can use Context.getString() on the second one, so that both are a String. I think this should work:
android:text="#{object.isTrue ? object.getString : context.getString(object.getStringId)}"
You don't have to import context, it's auto imported.

is it possible to cut text from string like this?

I want to put extra value from intent to other intent. But in other intent, app get all value. Example:
mAddress.setText(" from " + address);
String put_address = mAddress.getText().toString();
editIntent.putExtra("put_address", put_address);
is it possible to cut text "from" and get only address variable ???
you can split a string like
str = "From address#dd.com";
String modified = str.replace;
now splitstr contain your split strings
splitStr[1] contains "address#dd.com"
Can also use
str.substring(str.indexOf(" ")+1);
By the way, you can use jagapathi's answer. In his example he uses regular expression.
Regular expressions can help to parse, find, cut substrings using a particular pattern. In his code he splits string by any space character.
But, imho, the simplest solution is to create a substring using this code:
'put_address.substring(7);'
use one of these solutions:
String input = put_address.trim().substring(5);
*** note: 5 is index of real address first character;
String input = put_address..split(" ")[1];

showing a integer number in edit text field in android

I am trying to do the following :
t1 is an edit text
a and b are two integers
t1.setText(a+b);
but this is not working in android but it works perfectly with javaswing
A simple solution would be:
t1.setText("" + (a+b));
or maybe:
t1.setText((a+b).ToString());
please do like the following
EditText et=(EditText)findViewById("ID of your EDITTEXT");
int c=a+b;
String s=c.toString();
et.setText(s);
This'll work fine :) If it works vote me :)
but this is not working in android but it works perfactly with
javaswing
It will not, because you're actually calling setText(int resId). See here. Calling this method will search a string in xml resources (E.g. strings.xml). Every id of a string (E.g. #strings/hello) will be compared to resId, If resId matches the string's id that string will be displayed to that widget or else you wil get a ResourceNotFoundException
To display the actual integer, convert it first to String
t1.setText(String.valueOf(a+b))
You are doing like this t1.setText(a+b); it search this id (a+b) in resource file like strings.xml that is not available. So it will throws a exception ResourceNotFoundException..
So to set the number in text view you need to convert it into string.
In Android you need to do like this:-
int sum = a + b;
String sumString = String.valueOf(sum);
t1.setText(sumString);
OR
t1.setText((a+b) + "");

How to get string resource name by its value

I want to get a string resource name or ID by passing its value.
Example :
<string name="stringName">stringValue</string>
I want to pass the stringValue and get the stringName or ID (id value)
Based on ID i will do some calculation to get another ID of another String resource
I don't know if that's possible and I think the IDs can change without warning if the R class gets newly generated. You could of course try some reflection magic on this class, but I would recommend against it.
I also have this problem, and can think of 2 possible workarounds:
load all the strings and their names into a table, and look in the
table.
Or cycle through my complete list of names, getting the string resource
for each one, and comparing it to my known string resource.
I am implementing the 2nd one, as my list of string resources is not very big, and I don't have to do this operation very often. Once the name is known, it's possible to get the Resource Id via:
//Get resource id from name
var resourceId = (int) typeof (MyApp_droid.Resource.String).GetField(MyStringName).GetValue(null);
(code is C# because I'm working in Xamarin).

Set values to text identifier by var name. An alternative to getIdentifier

I am trying to set String values for ids defined in xmls. I have defined the set of text which can be assigned to different ids in the layout xml files. Thereby I can also see the int values that are associated with different texts in R.java.
I have stored the variable names that I have given to the texts in my database along with the R.id prefix as they appear in R.java file.
For setting text,
TextView messageone = (TextView)findViewById(R.id.textfield1);
Normal Usage:
String message = "Hi, hello";
messageone.setText(Status);
What i want to implement:
public static final int messagestring is present in R.java
R.id.messagestring is stored in sqlite database in text format
messageone.setText(what_here);
what_here = a way to get the value from "R.id.messagestring" string as obtained from database.
I know public int getIdentifier (String name, String defType, String defPackage)
can be used here. The only change would be stored text in database will change from R.id.messagestring to messagestring. But there is a note discouraging this type of implementation.
It says: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.
Android Docs getIdentifier
I think although this method seems like a longer implementation, can be efficient when the objects dealt with are not text.
There's a getString(int Id) method you can use inside an Activity. It will return a String from a given R.string Id.
String something = getString(R.string.something);
I hope I helped out a bit here, because I'm not entirely sure if I understand your question.

Categories

Resources