I have an Android App calling a PHP script, which returns 0 (FALSE) or 1 (TRUE) - unfortunately as a string. So in my Java Code I have the variable String result which is either "0" or "1". I know (thanks to you guys here) that this string can start with the BOM, so I remove it, if it does.
It is not really necessary but let's say I'd feel better if I had that result as an integer not as a string. The casting from string to int named code seems to work. At least I do not see anything happen.
But when I want to use the casted int like if (code == 1) or display it via Toast, my app crashes.
I can show with Toast that result == "1" and that result.length() == 1 so I do not see how I can possibly fail casting this string to int:
String result = postData("some stuff I send to PHP");
if (result.codePointAt(0) == 65279) // which is the BOM
{result = result.substring(1, result.length());}
int code = Integer.parseInt(result); // <- does not crash here...
// but here...
Toast.makeText(ListView_Confirmation.this, code, Toast.LENGTH_LONG).show();
I also tried using valueOf() and adding .toString() but it just keeps crashing. What am I missing here?
Use the following way to show toast
Toast.makeText(ListView_Confirmation.this, ""+code, Toast.LENGTH_LONG).show();
Toast.makeText requires a String(CharSequence) or an int but this int represents the resource id of the string resource to use (ex: R.string.app_name)
Try instead :
Toast.makeText(ListView_Confirmation.this, String.valueOf(code), Toast.LENGTH_LONG).show();
Use the below
Toast.makeText(ListView_Confirmation.this, String.valueOf(code), Toast.LENGTH_LONG).show();
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#valueOf(int)
public static Toast makeText (Context context, CharSequence text, int duration)
Make a standard toast that just contains a text view.
Parameters
context The context to use. Usually your Application or Activity object.
text The text to show. Can be formatted text.
duration How long to display the message. Either LENGTH_SHORT or LENGTH_LONG
http://developer.android.com/reference/android/widget/Toast.html
So use String valueOf(code) as the second parameter to makeText(params)
Returns the string representation of the integer (code) argument.
According to Toast library Toast.makeText(Context, int, int) uses that integer as Resource ID to Find a String in your resources.
Now since you don't have a resource with the same integer the function throws Resources.NotFoundException .
So to display your int value you have to change it back to text.
Toast.makeText(ListView_Confirmation.this, String.valueOf(code), Toast.LENGTH_LONG).show();
In android Api, the constructor of a toast is :
Toast.makeText(Context context, int resId, int duration)
"resId" is the reference of your String but not a String Object:
example: resId= R.string.helloworld
Related
I have made an application that whenever a user types a particular word it toast a massage now I want to add a feature that if the user has typed the particular word continuously many times in a particular time it will consider it once only and toast the massage ones only.
The code
if ( string.equals("help") ) {
Toast.makeText(getApplicationContext(), "we are here to help", Toast.LENGTH_SHORT).show();
}
Use a global String variable let's name it as lastText and check whether input text is the same as last text.
UPDATE for time tracking
private String lastText = ""; // Global for all class members
private long lastTextTime = 0; // Global
//...
// May be more code goes here
//...
if ( string.equals("help") && !string.equals(lastText) ) {
// Check whether 5 min has elapsed to show the toast message
if(System.currentTimeMillis - lastTextTime > (5*60*1000)) {
Toast.makeText(getApplicationContext(), "we are here to help",
Toast.LENGTH_SHORT).show();
// If the program reach here save this string as a last text for the next check
lastText = string;
lastTextTime = System.currentTimeMillis;
}
}
You can add already typed words to a list, and when the user types a word, you can iterate through this list and check if "word" is already was typed, and then if "false" - show toast.
Alternative solution - you can create a local SQLite database (using Room persistence library), it will allow you to save values even if user restart/exit app, but it will require more coding and fixing nuances
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!
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.
I was implementing the following Java code in Android Studio:
private void display(int number) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText(number);
...
}
This is a part of a larger application.
As you can see, I've passed only an integer value to the quantityTextView.setText(number) method.
When running the app, it crashes as soon as this method is called. Can you tell me why such a thing is happening?
Yes, use String.valueOf(), like this:
private void display(int number) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText(String.valueOf(number));
}
Because setText() accepts only String values or Resource ID of a String (which is infact int).
Check here: setText() Method
You can use String.valueOf(number); as input parameter of setText() or you can refer to String ID in XML with getResources().getString(R.string.number) as input value.
Convert the integer to string before putting it in the TextView:
quantityTextView.setText(Integer.toString(number));
or simply
quantityTextView.setText(number+"");
The reason your code is crashing is that setText(int) expects a resource ID. It's not very well documented, so you'd be forgiven for thinking that you could pass it an integer and have the TextView convert it to text.
You should first convert it to a String, for example with:
String.valueOf(number)
and then it will be alright.
setText() method of TextView accepts CharSequence, not integers. So, you must convert your number to String before.
Try to use this:
quantityTextView.setText(Integer.toString(x));
The reason is that, setText() only expects string or char[].
So either you can perform type casting or you can add quotes with the number
(1). by type casting
String.valueOf(number)
(2). by adding "" with the number
quantityTextView.setText(""+number);
or
quantityTextView.setText(number+"");
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);