Android : Get string for its number - java

I want to show sentences for its number.
Getting number with EditText, and sentences are in string.xml
Name of strings are
sen_(number)
ex: sen_1, sen_25
I tried to make the code to String, so I did like this.
(sentence_num is getString of EditText) (sen_1 is "Hello, world!")
String getTxtString = "getText(R.string.sen_" + sentence_num + ")";
TextView scrambled_sen = (TextView)findViewById(R.id.scrambled_sentence);
scrambled_sen.setText(getTxtString);
But it shows getText(R.string.sen_1), not "Hello, world!".
How can I make it show string with its number?
I want to put getTxtString for a java code, not a String.

You could use getResources().getIdentifier() to get the string but a better and non-complicated way is through a switch case or the if else method.
Something like
If(editText value equals something){
return getString(R.string.sen_1);
}
Minimizes the errors that you could cause through the first getIdentifier() method too.

Related

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 get value thats displayed in the Emulator?

I am writing a small android "Hello world" application and i would really like to write a small test case . i have written a small test case , have a look below :
public void testMyFirstTestTextView_labelText() {
final String expected = getContext().getResources().getString(R.string.hello_world);
final String actual = getContext().getText().toString();
assertEquals(expected, actual);
}
the expected variable gets instantiated with the value from strings.xml
but for the actual value , i am struggling to understand what methods or snippet i should write in order to get the value of the displayed string .
so how do i get the value of the text displayed in the emulator:
as of now the below statement is wrong:
final String actual = getContext().getText().toString();
i am really new to android , can somebody help me with this please .
if you check the last peice of code in the snippet :
assertEquals(expected, actual);
it checks(using jUnit i think) weather the value of expected is the same as actual.
once again to repeat my question in the above snippet , how do i get/retrive the value of the displayed text ? I.E. on the below line :
final String actual = getContext().getText().toString();
it should be yourTextViewObject.getText() not getContext().getText()
TextView textView = (TextView)findViewById(R.id.hello_world);//Assuming your id in the xml page is textView1
String actual = textView.getText().toString();
This gets the value of an entry hello_world from strings.xml.
String expected = getContext().getResources().getString(R.string.hello_world);
And This gets the value from the TextView.
String actual = textView.getText().toString();
From the android documentation's example
mFirstTestText = (TextView) mFirstTestActivity
.findViewById(R.id.my_first_test_text_view);
String actual = mFirstTestText.getText().toString();
You have a exactly the same example there at the Set Up Your Test Fixture part. Just analyse the TextView with something like this:
final String actual = label.getText().toString();
final String expected = getContext().getResources().getString(R.string.hello_world);
assertEquals(actual, expected)
If your textView is called label you can use something like this:
String s= label.getText().toString();

How do I convert the content of System.out.print to a String variable in java

I have this line of code:
System.out.print(postalCodeIndex.findClosestBruteForce(latitude, longitude));
It returns output from a text file that was ran through an algorithm. For example the output is can be : "A0E 2Z0 Monkstown Newfoundland NL D [47.150300:-55.299500]". I would like to convert that output to a string so I can use it in a javafx GUI text. Is that posible?
System.out.print accepts a String as a parameter, in fact, anything that you send it will be converted to a String in order for it to be displayed.
Using the following code, you could then put the result of the postalCodeIndex method call into a variable called myString.
String myString = postalCodeIndex.findClosestBruteForce(latitude, longitude).toString();
It might be worth your while remembering that the process in the System.out.print() code sample works as follows:
postalCodeIndex is called FIRST, creating a temporary String in-place because the .toString() method is called on your behalf.
The System.out.print method is only called AFTER the postalCodeIndex method has returned, because System.out.print requires this returned String to enable it to print something to the console.
postalCodeIndex.findClosestBruteForce(latitude, longitude)
this method it self would returning a String or if not you can do like
String str = postalCodeIndex.findClosestBruteForce(latitude, longitude).toString();
Based on the code you've given, the code inside the System.out.print() call will return a PostalCode object. So to get a string you could do something like:
String x = postalCodeIndex.findClosestBruteForce(latitude, longitude).toString();
//use x as String

Android NumberFormatException when parsing EditText

I'm writing an app that takes in an input from the AddBook class, allows it to be displayed in a List, and then allows the user to Search for their book. To this end, I'm creating a temporary EditText, binding it to the box where the user actually enters their search value, then (after ensuring that it is not empty) I compare what they've entered for the ISBN number with the ISBN numbers of each entry in the arrayList of <Book> custom objects, the list being named books.
Problem is, when I try to parse the EditText into an Int, it doesn't seem to work. I first tried using toString() on the EditText, then using Integer.parseInt() on the result of that method, but it hasn't worked out, as the conversion is seemingly unsuccessful;
All of the resources are in place and the code compiles properly, so those aren't the problems here.
EditText myEdTx = (EditText) findViewById(R.id.bookName);
if(myEdTx.getText().equals("")){Toast toast = Toast.makeText(this, "Please enter something for us to work with!", Toast.LENGTH_SHORT);
toast.show();}
else{
//resume here
for(int i=0; i<books.size(); i++)
{
Book tBook = new Book(i, null, null); tBook = books.get(i); String s=myEdTx.toString();
int tInt = Integer.parseInt(s);`
To get the string representation of an EditText's content, use:
String s = myEdTx.getText().toString();
Using toString() directly on the EditText gives you something like:
android.widget.EditText{40d31450 VFED..CL ......I. 0,0-0,0}
...which is clearly not what you want here.
You assume the user inputs a number into the text field, but that is unsafe, as you only get a string text (which theoretically can contain non-numbers as well). When I remember correctly, you can adjust a text field in android where a user only can input numbers, which should suit you more.
NumberFormatException occurs when Integer.parse() is unable to parse a String as integer, so, its better to Handle this exception.
String s = myEdTx.getText().toString();
try {
int tInt = Integer.parseInt(s);
} catch( NumberFormatException ex ) {
//do something if s is not a number, maybe defining a default value.
int tInt = 0;
}
So the current String here you are trying to parse is with white space in the line
and integer class unable to parse that white space. So use following code.
String s=myEdTx.getText().toString();
int tInt = Integer.parseInt(s.trim());
String s = myEdtx.getText().toString().trim();
int iInt = Integer.parseInt(s);

Checking the end of a string in Java multiple times?

So in Java, I know that str.endsWith(suffix) tests if str ends with something. Let's say I have a text with the line "You are old" in it. How would I take the "old" and set it as a variable so I can print it out in the console?
I know I could do:
if(str.endsWith("old")){
String age = "old";
}
But then I'm going to have more options, so then I'd have to do:
if(str.endsWith("option1")){
String age = "option1";
}
if(str.endsWith("option2")){
String age = "option2";
}
...
Is there a more efficient and less verbose way to check the end of strings over writing many, possibly hundreds, of if statements
Format:
setting: option
setting2: option2
setting3: option3 ...
Regardless of what "option" is, I want to set it to a variable.
If you are working with sentences and you want to get the word, do
String word = str.substring(str.lastIndexOf(" "));
You may need a +1 after the lastIndexOf() to leave the space out.
Is that what you are looking for?
Open your file and read the line with the readLine() method. Then to get the last word of the string you can do as it is suggested here
You mean like:
String phrase = "old";
if(str.endsWith(old)){
Is this what you're looking for?
List<String> suffixes = new ArrayList<String>();
suffixes.add("old");
suffixes.add("young");
for(String s: suffixes)
{
if (str.endsWith(s))
{
String age = s;
// .... more of your code here...
}
}
If you're worried about repeating very similar code, the answer is always (99%) to create a function,
So in your case, you could do the following:
public void myNewFunction(String this, String that){
if(this.endsWith(that)){
String this = that;
}
}
...
String str = "age: old";
myNewFunction(str, "old"); //Will change str
myNewFunction(str, "new"); //Will NOT change str
And if that is too much, you can create a class which will do all of this for you. Inside the class, you can keep track of a list of keywords. Then, create a method which will compare a given word with each keyword. That way, you can call the same function on a number of strings, with no additional parameters.
You could use this Java code to solve your problem:
String suffix = "old";
if(str.endsWith(suffix)) {
System.out.println(suffix);
}

Categories

Resources