Toast location does not update if that toast is already showing - android

My question, in particular, is in reference to the refreshing of toasts that have already been created.
For example i have a toast that has been created:
Toast myToast;
// ...
protected void onCreate(Bundle savedInstanceState) {
// ...
myToast = Toast.makeText(getApplicationContext(), "Welcome", Toast.LENGTH_SHORT);
And i update it differently upon two actions:
if (answerGiven != correctAnswer) {
myToast.setText("Wrong");
View view = myToast.getView();
TextView text = (TextView) view.findViewById(android.R.id.message);
text.setTextColor(Color.RED);
text.setTextSize(32);
myToast.setGravity(Gravity.CENTER, 0, 0);
} else {
View view = myToast.getView();
TextView text = (TextView) view.findViewById(android.R.id.message);
text.setTextColor(Color.BLACK);
text.setTextSize(32);
myToast.setText("+" + bonus);
myToast.setGravity(Gravity.TOP|Gravity.RIGHT, 20, 20);
}
myToast.show();
Both actions work fine! BUT if i tap quickly on the screen and activate the second action BEFORE the toast has disappeared the gravity is not changed even though the message updates.
For example: if i choose the wrong answer, and the "wrong" message shows in the middle of the screen:
and then i immediately choose the write answer the bonus message appears in the middle of the screen (even though i tell it to set setGravity(Gravity.TOP|Gravity.RIGHT, 20, 20);)
(note: if i wait until the "Wrong" message disappears and then click the correct answer the bonus message shows in the top left corner as expected)
What i want it to do is to always put the bonus message at the top left. Even if the user clicks to fast. So i am asking: Is there a way that the previous toast can be cancelled so the new message is shown in the correct location. Or is there something i should do (such as refresh my activity) so that the message displays in the correct location.

I have written a below sample code and that's working.Please have a look at that
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btnAddData;
private TextView tv;
private EditText et;
private boolean check;
Toast myToast;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myToast = Toast.makeText(getApplicationContext(), "Welcome", Toast.LENGTH_SHORT);
btnAddData = findViewById(R.id.btn_add_record);
btnAddData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (check) {
if (myToast.getView().isShown())
myToast.cancel();
check = false;
myToast = Toast.makeText(getApplicationContext(), "Welcome", Toast.LENGTH_SHORT);
myToast.setGravity(Gravity.CENTER, 0, 0);
myToast.show();
} else {
if (myToast.getView().isShown())
myToast.cancel();
check = true;
myToast = Toast.makeText(getApplicationContext(), "Welcome", Toast.LENGTH_SHORT);
myToast.setGravity(Gravity.TOP | Gravity.RIGHT, 20, 20);
myToast.show();
}
}
});
}
You need to make a button in xml and test that and let me know if you are facing any problem. Further you can adjust according to your need.

You should cancel the current toast before showing new toast message.
if (myToast != null) {
myToast.cancel();
}
// your code ...

You should Use
Toast.cancel()
Close the view if it's showing, or don't show it if it isn't showing yet. You do not normally have to call this. Normally view will disappear on its own after the appropriate duration.
Try this
if (myToast!= null) {
myToast.cancel();
}
if (answerGiven != correctAnswer) {
myToast.setText("Wrong");
myToast.setGravity(Gravity.CENTER, 0, 0);
} else {
myToast.setText("+" + bonus);
myToast.setGravity(Gravity.TOP|Gravity.RIGHT, 20, 20);
}

Related

Android - automatically scroll within AlertDialog TextView

I am using an AlertDialog to track a logFile which is updating in real time, and need to automatically scroll to the bottom of the view whenever an extra line is added.
I am able to cast the AlertDialog to a TextView (and e.g. using this TextView alter the text size) but any methods involving scrolling don't work.
Code:
LogFileView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
String logFile = "/data/data/com.test/test.log";
String logFileOutput = getFileOutput(logFile);
final AlertDialog dialog = new AlertDialog.Builder(getActivity()).setMessage(logFileOutput).show();
TextView textView = dialog.findViewById(android.R.id.message);
textView.setTextSize(8);
textView.scrollTo(0, textView.getLineCount());
} catch (IOException e) {
e.printStackTrace();
}
}
});
textView.setTextSize(8); will alter the text size on display
textView.scrollTo(0, textView.getLineCount()); will do nothing, and the alert dialog, despite having a scrollbar available, will remain focussed on the first line
Update 1:
I see there are a few requests for the dialog creation code/errors in the console output.
Firstly, I am not actually using a separate layout/class to create the dialog. It is applying the default layout associated with (android.R.id.message) to an instance of android.app.AlertDialog and is only constructed within the onClick method for the onClickListener in the code above.
Based on the feedback I've received so far, the code I've most recently attempted to use looks as follows:
LogFileView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
String logFile = "/data/data/com.test/test.log";
String logFileOutput = getFileOutput(logFile);
final AlertDialog dialog = new AlertDialog.Builder(getActivity()).setMessage(logFileOutput).show();
TextView textView = dialog.findViewById(android.R.id.message);
textView.setTextSize(8);
//textView.scrollTo(0, textView.getLineCount());
textView.setMovementMethod(new ScrollingMovementMethod());
textView.post(new Runnable() {
#Override
public void run() {
textView.scrollTo(0, textView.getLineCount());
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
});
Secondly, there is nothing appearing in the console when the scroll attempt is made - this simply gets ignored at runtime.
The default layout seemed like it would be fine for my purpose, given it appears like a blank TextView with a scrollbar attached, but I think it may be a sensible next step to use a new custom layout and add a ScrollView and see what happens
Use below code. I Tested & verified.
textView.movementMethod = ScrollingMovementMethod() // Add this
textView.text = "your text"
textView.post {
val scrollAmount = textView.layout.getLineTop(textView.lineCount) - textView.height
textView.scrollTo(0, textView.lineCount)
}
Edit:
Equivalent to java:
textView.setMovementMethod(new ScrollingMovementMethod());
textView.setText("your text");
textView.post(new Runnable() {
#Override
public void run() {
int scrollAmount = textView.getLayout().getLineTop(textView.getLineCount()) - textView.getHeight();
textView.scrollTo(0, scrollAmount);
}
});
Try to wrap it with post instead of calling directly to scrollTo,
something like this:
textView.post(new Runnable() {
#Override
public void run() {
textView.scrollTo(0, textView.getLineCount());
}
});

Checking empty of EditText and send Toast - / avoid saving empty data to SQLite

Sorry taking your time, am asked a question in a very wrong way.
So what I doing now, a small notepad program where the title and content saved of the note to the SQLite database.
This part working as should, but I don't have any input check and the app saving the note with empty title and content.
there is my current code for this :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dba = new DatabaseHandler(MainActivity.this);
title = (EditText) findViewById(R.id.titleEditText);
content = (EditText) findViewById(R.id.wishEditText);
saveButton = (Button) findViewById(R.id.saveButton);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveToDB();
}
});
}
private void saveToDB() {
MyNote wish = new MyNote();
wish.setTitle(title.getText().toString().trim());
wish.setContent(content.getText().toString().trim());
dba.addWishes(wish);
dba.close();
//clear
title.setText("");
content.setText("");
Intent i = new Intent(MainActivity.this, DisplayNotesActivity.class);
startActivity(i);
How can I implement a basic input checking and avoid the saving of empty notes?
my first idea was to check the emptiness of the input and drop a toast message, tried several solutions from not, but not worked me.
many thanks
C
You have to be sure you're using the same EditText variable which in this case I think is title.
EditText title = (EditText) findViewById(R.id.titleEditText);
if(title.getText().toString().isEmpty()) {
Toast.makeText(MainActivity.this, "Input Text Is Empty.. Please Enter Some Text", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, title.getText().toString(), Toast.LENGTH_SHORT).show();
}
}
});
U need to specyfi your question.
But from what i undestood u don't know how check editText is empty and don't know why can't write into text box.
First easy method is just check length of string if it bigger than 0 that's meen it's not empty
EditText title = (EditText) findViewById(R.id.IDEDITTEXT);
if(String.valueOf(title.getText()).length()>0){
//do something
}else{
//do something
}
And about second (i thing question) is check your xml file (layout) does your editText is enabled and not is textViev.
Btw your code is hard to read like your question:)
EditText title = (EditText) findViewById(R.id.titleEditText);
if(title.getText().toString().length()<=0) {
Toast.makeText(MainActivity.this, "Input Text Is Empty.. Please Enter Some Text", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, title.getText().toString(), Toast.LENGTH_SHORT).show();
}
}
});
try this code...

Blank TextView occasionally on LG G2 (Android 4.4.2)

I'm writing a simple application where a Japanese character is displayed in the middle of the screen as a TextView with 4 buttons(home, shuffle, sound, and next) on the bottom. When the next button is pressed, the next character will be displayed in the TextView.
The application works perfectly on the eclipse simulator and my Samsung Galaxy S2 (Android 4.0.4). However, on my LG G2 (Android 4.4.2), every now and then (maybe once every 30 chars), I get a blank TextView when I click the next button.
I did the following experiments:
1) I added some debugging code to dump the value of the character on a Toast before and after the call to setText(), and the correct value is displayed on the Toast.
2) I pressed the 'sound' button when the TextView is blank and verified that the sound button is associated with the correct character.
3) I added one second delay right after the call to setText() to see if I was overwriting the TextView after setting the right character. In which case, I expected the correct character to be set in the TextView first, and then it becomes blank after the one second delay. However, I saw the blank TextView as soon as I clicked the next button.
So, I think, maybe prematurely, setText() is clearing the TextView somehow.
Does anybody know what the problem might be?
Part of my code looks like this:
public class KatakanaFragment extends Fragment {
private ImageButton    mNextButton;
private TextView mCharTextView;
private void updateChar() {
int strId;
Katakana[] activeKatakana;
activeKatakana = KatakanaTable.getActiveChars();
if ((activeKatakana == null) || (activeKatakana.length == 0)) {
Toast.makeText(getActivity(), "No Char Selected", Toast.LENGTH_SHORT).show();
return;
}
if (activeKatakana.length <= KatakanaTable.sCurrentIndex) {
Toast.makeText(getActivity(), "Current Index Too Big", Toast.LENGTH_SHORT).show();
return;
}
strId = activeKatakana[KatakanaTable.sCurrentIndex].getCharId();
mCharTextView.setTextSize(getResources().getDimension(R.dimen.textsize));
mCharTextView.setText(strId);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_katakana, parent, false);
mCharTextView = (TextView)v.findViewById(R.id.char_text_view);
mNextButton = (ImageButton)v.findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (KatakanaTable.getActiveChars().length == 0) {
Intent i = new Intent(getActivity(), MainActivity.class);
startActivity(i);
return;
}
KatakanaTable.sCurrentIndex = (KatakanaTable.sCurrentIndex + 1) % KatakanaTable.getActiveChars().length;
updateChar();
}
});
updateChar();
return v;
}
}

If Condition not working in my command

Where Is The problem can anybody help me my if statement is not working as i want it to have checked my edittext is visible or invisible in android.
Now i have to check the condition is.,
If my edittext is visible means how can i insert the data.
If my edittext is gone means how can i insert on another data.
This is my code for if i have to check the checkbox means the edittext is invisible otherwise the edittext is visible .:
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.selling1);
b=(Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
DecimalFormat tw = new DecimalFormat("0.00");
EditText a= (EditText)findViewById(R.id.y);
EditText b= (EditText)findViewById(R.id.a);
Float x=Float.parseFloat(a.getText().toString());
Float y=Float.parseFloat(b.getText().toString());
if((a.getText().toString().equals(""))){
Toast t= Toast.makeText(getApplicationContext(), "10000 is there", Toast.LENGTH_LONG);
t.setGravity(Gravity.CENTER, 02, 10);
t.show();
}else{
Float z=(x*y)/(100+y);
Float p=x-z;
EditText c= (EditText)findViewById(R.id.c);
c.setText(tw.format(z));
EditText d= (EditText)findViewById(R.id.e);
d.setText(tw.format(p));
}
print a.getText().toString() and see what it is returning, if it is empty try this
if("".equals(a.getText().toString())){
Toast t= Toast.makeText(getApplicationContext(), "10000 is there", Toast.LENGTH_LONG);
t.setGravity(Gravity.CENTER, 02, 10);
t.show();
}
If you want to check visibility of EditText the don't compare its text. Follow this instead:
if (a.getVisibility() == View.VISIBLE){
//Perform your action of inserting
}
Hope you understand why to choose this. Say, user entered something in EditText. Then you made that EditText invisible. At this time its text is not cleared. So you still get that text.
Hope this helps.

Toast and onOnclick, toast k won't show

Does anyone know why this program won't show the toast message?
public class Main extends Activity implements OnClickListener{
/** Called when the activity is first created. */
ImageButton x = (ImageButton) findViewById(R.id.imageButton1);
ImageButton i = (ImageButton) findViewById(R.id.imageButton2);
ImageButton question = (ImageButton) findViewById(R.id.imageButton3);
I have crated some ImageButons and other elements and created onClick function
public void onClick(View v) {
if(v.getId() == R.id.button1) // this works
{
Intent intent = new Intent(this, Second.class);
intent.putExtra("thetext", et1.getText().toString());
intent.putExtra("thesize", et2.getText().toString());
startActivity(intent);
}
if(v.getId() == R.id.imageButton2) // this wont work
{
Toast toastI = Toast.makeText(this, "Testing", 5000);
toastI.setGravity(Gravity.CENTER, 0, 0);
toastI.show();
}
When i Click on ImageButton i(after i run program) the toast won't display?
Hope you have set the onclickListener on imagebuttons..
i.setOnClickListener(this);
try this
Toast.makeText(getApplication(), "Testing", 5000).show();
try using switch case instead of if and use Main.this or getApplicationContext() instead of this as:
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
Intent intent = new Intent(Main, Second.class);
intent.putExtra("thetext", et1.getText().toString());
intent.putExtra("thesize", et2.getText().toString());
startActivity(intent);
break;
case R.id.imageButton3:
Toast toastI = Toast.makeText(Main.this, "Testing", 5000);
toastI.setGravity(Gravity.CENTER, 0, 0);
toastI.show();
break;
}
}
I think your problem is putting 5000 on the length of the toast. LENGTH_LONG and LENGTH_SHORT have values 1 and 0 so they are used as flags. So I don't know what Would happen if you put 5000 (probably nothing). Also on the java doc they say you should put or or the other. So use one or the other.
public static Toast makeText (Context context, CharSequence text, int
duration) Since: API Level 1 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
static Toast makeText(Context context, int resId, int duration)
The problem is that you are passing 5000 as the third parameter to the method. int duration is not the number of seconds (or milli-seconds) the Toast will appear to the user. The Toast class requires that you pass only two possible values (which makes sense, because otherwise developers would totally abuse the lengths of toast messages and the applications on the Android market would be totally inconsistent in how they display messages to the user). The two values are:
Toast.LENGTH_SHORT
Constant Value: 0 (0x00000000)
or
Toast.LENGTH_LONG`
Constant Value: 1 (0x00000001)
To fix the issue, change the method call to,
Toast.makeText(this, "Testing", Toast.LENGTH_LONG).show();
Also, remember to set your onClickListener on your ImageButtons (just a shot in the dark).
First implements View.OnClickListener interface and add listener to each imagebutton like this :
x.setOnClickListener(this);
for the toast message the code mjst be like this :
Toast.makeText(Main.this,"put your message here",Toast.LENGTH_LONG).show();

Categories

Resources