android setText with getString using variable name - java

So, searching the internet I found many examples that were not what I need...
Here is my situation:
Imagine that you have a resource that is an array called songs and many 's with each song name..so, imagina you have like 200 song names displayed on a listview..
when you click a song, the app loads another activity with the lyrics for that song...
but HOW do you do that?
Here is how I did it.. I passed the name of the song to this new activity, loaded the resource where the lyrics are...
BUT, at the time I have to setText with the lyrics, I got a problem... should I do a switch with 200 cases? that sounds insane, so, what I did was, I used the same name of the song to the lyrics..so it should load like this:
TextView txtProduct = (TextView) findViewById(R.id.product_label);
Intent i = getIntent();
// getting attached intent data
String[] musicas = getResources().getStringArray(R.array.botafogo_songs);
// this here is where it brings the name of the music to the activity
String product = i.getStringExtra("product");
// displaying selected product name
if (Arrays.asList(musicas).contains(product)) {
//just formating so they have the same name.
String productSplit = product.split("- ")[1];
productSplit.replace(" ", "");
txtProduct.setText(getString(R.string.AbreAlas));
}else{
txtProduct.setText("não contem");
}
Ok, AbreAlas is the name of my resource..it loads fine..
BUT, I cant leave it like this...it should be a variable name...
like: R.string.+productSplit
or something like this..
I can't find the solution nowhere..

You can use getIdentifier():
int resourceName = getResources().getIdentifier(productSplit, "string", getPackageName());
And then:
txtProduct.setText(getString(resourceName));
Don't forget to wrap that in a try and catch.

Related

How Do I Update TextView Result On App Launch

I am pulling data from a Website to my application. I want the TextView to display the result I want from the website immediately as the user launches the app. However html codes make the result look weird some times and I am trying to correct it. I have the codes that will do what I am trying to do. I just can't figure out how to get it to do everything automatically at app launch. It needs to pull the code from the website and if it receives any special symbols within the string I want it to correct it as soon as the app launches. Here is an example...
TextView tv = (TextView) findViewbyId(R.id.my_textview_result);
tv.setText(resultFromWebsite);
The result it pulled: You u0026 Me Forever!
The result I want: You & Me Forever! My app should correct that.
Here is my correction code...
public void symbolTextFilter(TextView myTv) {
String getData = tv.getText().toString();
if (getData.contains("u0026") {
String replace = getData.replace("u0026", "&");
myTv.setText(replace);
}
Now on my onCreate Method
TextView tv = (TextView) findViewbyId(R.id.my_textview_result);
tv.setText(resultFromWebsite);
symbolTextFilter(tv);
It will not make that correction. It will if I put the symbolTextFilter(tv) in a onClickListener button though. I don't want to assign the correction in a button. I want it automatically. My guess is, everything that I have in the onCreate is happening too fast for corrections to be made. How do I fix that? Thanks in advance!
Try this:
tv.setText(symbolTextFilter(resultFromWebsite))
You should use the method symbolTextFilter to handle the string only:
public void symbolTextFilter(String input) {
if (input.contains("u0026") {
return input.replace("u0026", "&");
} else {
return input
}
Nevermind, I got it! I'm not sure where the "\" came from because it wasn't in the original string that it pulled before the correction. I fixed it with this...
public String symbolTextFilter(String input) {
if (input.contains("u0026") {
return input.replace("\\" + "u0026", "&");
} else {
return input
}

Failed to get string from autocompletebubbletext

i'm using autocompletebubbletext library (https://github.com/FrederickRider/AutoCompleteBubbleText) which display the list of items to chose from in a list and allow in same time to chose the items from the editetxt..
My problem is as follow:
after the user choses a number of items(=Multiple inputs) .. i want to display a text as an output when clicked on a button (depending on the items chosen of course) as explained in this picture: (https://i.imgur.com/QQuzFvl.png)..
but i got stucked in getting the string of itemsChosen from the edittext
FIRST: i am not sure which return value to use!!
SECOND: i assumed i should use "checkedIds" and I've tried A lot of solution in internet , i've been trying different ideas all day, from what i have tried: ( Ps: i used a toast to see if the methods did work)
edittext.getText().toString() > nothing appears in Toast
i have tried to turn the setHash to String[]: then turning the String[] to one string like:
content=editText.getCheckeditems();//getcheckeditems returns checkedIds which is = new HashSet<String>()
String[] BLANA= content.toArray(new String[content.size()])
data= TextUtils.join(",",BLANA);
it didnt work, in Toast i got"[]"
For the MainActivity.Java (i have the same as here):
https://github.com/FrederickRider/AutoCompleteBubbleText/blob/master/samplelist/src/main/java/com/mycardboarddreams/autocompletebubbletext/samplelist/SampleActivity.java
For MultiSelectEditText.java (i Have same as here) :
https://github.com/FrederickRider/AutoCompleteBubbleText/blob/master/library/src/main/java/com/mycardboarddreams/autocompletebubbletext/MultiSelectEditText.java
WHAT is the solution? (to get a string so i can use it later)
PS: if there is another way(another library or methode) to get what i want to achieve in the first place , i would love to try it..
EDIT: THIS IS A CODE THAT LOOKS PROMISING BUT DIDN'T WORK!
in MultiSelectEditText.java
public String datachosen(){
String [] blan= checkedIds.toArray(new String[0]);
StringBuilder builder = new StringBuilder();
for (String string : blan) {
if (builder.length() > 0) {
builder.append(" ");
}
builder.append(string);
}
String DATATORETURN = builder.toString();
return DATATORETURN;
}
in MAINACTIVTY.JAVA
MultiSelectEditText editText = (MultiSelectEditText)findViewById(R.id.auto_text_complete);
content=editText.datachosen();
Toast.makeText(DecisionTree.this, content,
Toast.LENGTH_LONG).show(); // TOAST INCLUDED IN A BUTTON OF COURSE
OUTPUT: TOAST SHOWS NOTHING!
Solved it ..
i intialize the edit text before on create ..and defin it later after onCreate()..
and got string with the normal edittext.getText().toString(); method!
Simple but was hard to detect the problem!

How to add pre defined text in getText() from Textview and show the result

I have textview where user are asked to enter some information and that information is uploaded in Firebase Data Structure and then is Displayed on another activity
Here is the code I'm using to getText from Textview
etAuthor = (EditText) findViewById(com.nepalpolice.bookbazaar.R.id.editText1);
String bauthor = etAuthor.getText().toString();
and it does job pretty well.
and it is added to firebase.
But what if I want to add predefined Text like
Author:getText()
Here I have added author.
and This will be upudated on Database as well and will Displayed to user
instead of Consider Author is
J. K. Rowling
It will show
Author:J.K Rowling
Any help is appreciated.
Thanks in advance.
you can concatenate the desired string, in you case:
String bauthor ="Author:"+etAuthor.getText().toString();
String bauthor = "Auther : "+etAuthor.getText().toString(); //use this, '+' use for concatenate
#Bir Nepali, you have to just append while getting the text.
etAuthor = (EditText) findViewById(com.nepalpolice.bookbazaar.R.id.editText1);
String bauthor = "Author:" + etAuthor.getText().toString();
Now you can populate this bauhtor in the view.

Return getString from xml with a string variable?

I am newcomer to programming and I am attempting to create an Android app using Android Studio. I've tried searching but my findings do not appear to be what I am looking for, because they seem to be overly complex. What I've written below is just an example.
I want to be able to return a string from string.xml when user types "whale". The string in this case is information about the whale.
This is my java file, animal is already a string entered from a form.
TextView textview = new TextView(this);
String animalType = "water_" + animal; // This become water_whale if user typed whale
String animalInfo = getString(R.string.animalType); // This doesn't work
textView.setText(animalInfo);
This is my string.xml
<string name="water_fish">Fish is a small bla...</string>
<string name="water_whale">A whale is an enourmous blabla...</string>
<string name="land_giraffe">Africa.</string>
I have probably tunneled on this particular way and I have probably miss something obvious or is there another way to do this?
R.string.anyIdentifer represents an integer value. You can't add your own identifier with it, just the way you can't call any non existent property on any class. If you want to access any resource dynamically with it's name then there is a different approach for that.
Use this
TextView textview = new TextView(this);
String animalType = "water_" + animal;
int animalTypeId = getResources().getIdentifier(animalType, "string", getActivity().getPackageName())
String animalInfo = getResources().getString(animalTypeId);
textView.setText(animalInfo);
String string=getResources().getString(R.string.water_whale);
you can't use getString() method directly.

Grab checkbox name at runtime in android

I am looping through a list of checkboxes upon click of a button. What I am looking to do is grab the name of the checkbox at runtime to strip out an integer value specified within the name. I am not looking to get the value nor the id. So in the strings.xml file, <string name="checkList1">Pain assessment.</string>, I am trying to get checkList1 at run time. I can get the text without a problem. Currently I am looping through the view elements with the code below:
RelativeLayout root = (RelativeLayout)findViewById(R.id.Root);
for (int i = 0; i < root.getChildCount(); i++)
{
View v1 = root.getChildAt(i);
Class c = v1.getClass();
if (c == CheckBox.class)
{
CheckBox thisBox = (CheckBox)v1;
if (thisBox.isChecked())
{
String text = (String)thisBox.ge;
DoDailyCheckListUpdate(thisBox.isChecked(),checkBoxCount);
countItemsFinished++;
}
checkBoxCount++;
}
}
What I am looking for is to somehow get the name of Checkbox thisBox. So when it loops through and hits the Pain Assessment checkbox, I want to be able to pull out checkList1. Without going as far as ripping through the strings.xml file based on the text I find to get the name, I was hoping maybe there was a simpler solution that I maybe overlooking.
Thank You in advance.
CheckBox extends from TextView so to retrieve a text from it is quite simple :
String text = thisBox.getText().toString();
http://developer.android.com/reference/android/widget/CheckBox.html
If you want to retrieve the key name of the string. I suggest you put it into the tag of the object :
thisBox.setTag(getResources().getResourceEntryName(R.string. checkList1);
Retrieve it like that :
String text = (String)thisBox.getTag();
that should do the trick.

Categories

Resources