Toast is not shown android robotium test - android

I want to test "Add new item" activity in my application. When user fills data incorrectly and then press OK button - the toast (issues list) is displayed. My question is: How can I check that toast is not shown?
Thanks!

I know its an old post but just in case anyone comes across this question, this is the a better way:
solo.waitForText(text); // put here the toast text

//wait up to a second for the toast
Date date = new Date();
TextView toast;
long elapsed;
do{
elapsed = new Date().getTime() - date.getTime();
toast = (TextView)solo.getView(android.R.id.message);
}while(elapsed<1000&&toast!=null);
assertEquals(toast.getText().toString(), "Your ticket(s) has been purchased successfully");
This is an extension of the answer given by Aleksandr M in case the Toast takes a while to appear. For example, if the toast is the result of a time consuming operation.

Simply assign a flag variable where you handle the onClick event of your OK Button which issues the Toast. Set that flag to true,and then later check, if the flag is false, the Toast was never shown.

this one is works for me
TextView toast = (TextView) solo.getView(android.R.id.message);
assertEquals("toast is not showing", toast.getText().toString(), solo.getString(R.string.error_invalid_phone));

Related

Android: SharedPreferences default value of a String

I searched through a lot of questions but i didn't find one that answers my problem. So here I go :I made a custom PIN locked Activity for my App that runs as the LAUNCHER activity. This is the code I used in the onCreate() method to check if this is the first run of the app (in order to run the appropriate code and give the user the chance to set up their PIN)
if (sharedPinDatabase.getString("pin", "NO PIN SAVED").equals("")) {
Log.i("SECURITY", "NO PIN SAVED");
tvInstructionsPin.setText(" It appers that you havent saved a PIN. Enter new PIN below.");
}else{}
But whenever I run the App for the first time (or clean all the app data) the App skips this chunk of code and goes straight to the "enter your saved PIN" part(Picture 1).I used Log.i to check what value it is given to the key ("pin") before i enter any PIN with this
Log.i("SECURITY", "PINs dont match Saved one is: " + sharedPinDatabase.getString("pin", "") + "entered is : " + etPinInput.getText().toString());
and what i get from this chunk of code is "PINs dont match Saved one is: entered is :"
And if i press "OK" without typing in any number (leaving the EditText blank)it works and goes to the next Activity.
Also in the settings part of the app i made this (to run at onClick)
SharedPreferences sharedPrefWrite = getContext().getSharedPreferences("PIN_PREFS_DATABASE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPrefWrite.edit();
editor.putString("pin", "").commit();
Intent i = new Intent(getActivity(), LockScreen.class);
startActivity(i);
And for some reason it works(when setting the value of the string to "") and gets me to the desired screen (the one that i made for the first run of the App)
this one (Picture2):
When you put sharedPinDatabase.getString("pin", "NO PIN SAVED").equals("") - if there was no PIN saved before, it will not return "", but it will return "NO PIN SAVED" (as this is default data you provided).
Just change it to sharedPinDatabase.getString("pin", "").equals("") - and it would work.
Small tip (for future).
If you use ""..equals(sharedPinDatabase.getString("pin", "")) instead of sharedPinDatabase.getString("pin", "").equals("") - you will avoid NullPointerException in case when sharedPinDatabase is null.

Android Eclipse - If button isn't pressed within 'x' seconds then

Trying to figure out how to do this, basically my App requires a button to be hit and hit multiple times, it counts how many times you hit it and if you don't hit one within a certain space of time it will display a message.
I just can't figure out how to get the 'If button isn't pressed within 'x' seconds then...' part, I've tried if(imagebutton1.isPressed()) statement but it checks it instantly when the actvity starts, I just want it to check 'X' amount of seconds after the button was last pressed.
ANy help is appreciated thanks.
In your case you would need to record the last time the button was pressed
Then add a updated while statement
In c++
Int presses;
Int timelimit; //the seconds between each press (you can use a chronometer but this is simpler but less accurate (and no decimals)
Int lastpressed; //need chronometer for more accuracy or decimals)
Int ammountpassed; //time since you pressed it
If(imagebutton1.isPressed())
{
Bool Started = Yes;
Presses++;
While(!imagebutton1.isPressed()&&ammountpassed<TimeLimit)
{
Ammountpassed++;
};
};
If (ammountpassed>=timelimit)
{
If (presses>=highscore)
{
DisplayMsg " Number of presses" presses; "! New highscore!";
};
Else(presses<highscore)
{
DisplayMsg "not fast enough! Number of presses" presses; "!" };
};
};
You will have to tweak it a bit to fit your needs ("displaymsg" I for think is the actual function so you might have to change that but there's the logic :)
I recommend hand typing this as I belive I may have made a few error but nothing adding a semi colon or 2 won't fix ;)
Hope it helps :) Good Luck :)
Every time the user hits the button you can post a message on the handler's queue with your text message to be displayed and the appropriate delay time (and remove previous messages). Therefore if the delayed time exceeds without any press the thread will execute the handler's message. Lets say you want to post to the main handler a message to be executed in delay number of milliseconds, then in your activity you would need to hold the reference to the handler and create a Runnable where the necessary text message will be displayed:
Handler mainHandler = new Handler(getMainLooper());
Runnable runnable = new Runnable(...);
In your OnClickListener of the button you would need to execute only:
#Override
public void onClick(View v) {
mainHandler.removeCallbacksAndMessages(null);
mainHandler.postDelayed(runnable, delay);
}

Get Thread sleep duration from App Preferences

I am trying to allow users of my app to change the length of the splash screen. I created an EditTextPreference in my preferences.xml and gave it a default value of 5. The key is "duration". I figured that I could use SharedPreferences and use the getLong method to get the value of the field, and then use it as the parameter for the Thread's sleep method.
Here is my code:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
long dur = prefs.getLong("duration", 5);
final long duration = dur*1000; //convert from seconds to milliseconds
Thread timer = new Thread() {
public void run() {
try{
sleep(duration);
}
catch (InterruptedException e) {
e.printStackTrace();
}
finally {
Intent openMenu = new Intent("com.heh.blah.MENU");
startActivity(openMenu);
}
}
};
timer.start();
This code works perfectly fine as long as the preference isn't changed. However, if I go into the preferences and change the Duration preference (even if I don't change it and just hit "ok" with the default value of 5 in the box OR hit cancel) and close the app, the next time it opens, the screen goes all white for a few seconds, then all black, and then it crashes and I get the "Unfortunately, App has stopped." popup box. Clearing app data allows the app to start up normally again (but with a 5 second splash screen).
UPDATE: Just opening the preferences EVEN WITHOUT CHANGING CLICKING ON OR CHANGING ANYTHING causes it to crash during the next start up.
Any help with this issue would be much appreciated!!!
Thanks,
Max
You would be better off sending a delayed Message to a Handler on the UI thread.

Android Toast Message is not showing

I have Button.When the user click the button, there are some condition, that condition is not satisfy then need to display Toast but not showing Toast Message...
Code: Edited
Button addMe = (Button)findViewById(R.id.addMe);
addMe.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(selectedReason.equals("--Select--")){
Log.i("TAG","-----");
Toast.makeText(getBaseContext(), "Reason can not be blank", Toast.LENGTH_SHORT).show();
}else if(selectedType.equals("--Select--")){
Toast.makeText(getParent(), "Discount type can not be blank", Toast.LENGTH_SHORT).show();
}else{
if(selectedType.equals("Value")){
if(spc_amount.getText().toString().equals("")){
Log.i("TAG","-----");
Toast.makeText(getBaseContext(), "Discount type can not be blank", Toast.LENGTH_SHORT).show();
}else{
if(Double.parseDouble(spc_amount.getText().toString()) > invoiceValue){
Toast.makeText(getBaseContext(), "Amonut can not be grater than invoice", Toast.LENGTH_SHORT).show();
}else{
Discount dis = new Discount();
dis.setCriteriaName(selectedReason);
dis.setDiscountValue(Double.parseDouble(spc_amount.getText().toString()));
spDisList.put(1,dis);
tl.removeAllViews();
loadTableLayout();
}
}
}
}
}
});
I have tried context with getParent() , getApplicationContext() , SpecialDiscountActivity.this & getBaseContext() but not working....
This Toast message coming under the Tab Activity Group
Try:
Toast.makeText(getBaseContext(), "Reason can not be blank", Toast.LENGTH_SHORT).show();
It's the .show() that you've omitted everywhere that causes all your toasts to instatiate, but never execute.
Please excuse me if this isn't the solution to your problem, but I accidentally unchecked the 'Show notification' setting of the application once. It may be an idea go into your device settings/application/manager and check this setting.
I think you are missing .show();
It should be...
Toast.makeText(getBaseContext(), "Amount can not be grater than invoice",
Toast.LENGTH_SHORT).show();
Just restart your device! It solved my problem.
Maybe you are not in the UI thread? Try this: http://developer.android.com/reference/android/app/Activity.html#runOnUiThread%28java.lang.Runnable%29
If Toast is not showing that means either you have not called show() method or you are not on UI thread
Ideally, you should create a helper method to show Toast like this on UI thread
/** Execute Toast on UI thread **/
private fun showToast(message: String) {
Handler(Looper.getMainLooper()).post {
// Code here will run in UI thread
Toast.makeText(
this,
message,
Toast.LENGTH_LONG
).show()
}
}
I did like this
Toast.makeText(SalesActivityGroup.group.getParent(), "Amount can not be
grater than invoice", Toast.LENGTH_SHORT).show();
Just bumped across this issue and was wondering how a simple Toast is not appearing. After few trials it struck me to check the notification setting of the app and Voila.
I switched the notification setting ON and it started showing up. I searched and came across the below link, which talks about the same:
https://code.google.com/p/android/issues/detail?id=35013
There could be two possibilities:
1 - You have not append .show(); at the very end of Toast.makeText(getActivity(), "Hi", Toast.LENGTH_SHORT).
2 - There could be situation you are not passing right context
For that try passing getActivity().getApplicationContext();
which in my case resolved the issue.
Good luck :)
Some times Emulator is hanging so restarting the emulator fixes the issue.
Simply restart your emulator not fixed my problem.
Close emulator
Tools -> Avd Manager
In the device list click on "drop-down icon" under "Action" column.
Cold boot now
Now reinstalling the app it will work.
You can use the context of the Activity
like,
Toast.makeText(ActivityName.this,"Reason can not be blank", Toast.LENGTH_SHORT).show()
if this is not working, please put a log.i(); in your each condition may be its going to the last else and you are not getting the Toast.
In my case it was because I wasn't running from Main thread, this fixed it:
val mainActivity = (tabHostActivity.activityContext() as MainActivity)
mainActivity.lifecycleScope.launch{ //Dispatchers.Main, follows lifecycle
Toast.makeText(mainActivity, "my awesome message", Toast.LENGTH_LONG).show()
}
Just Cold boot your device!
It can solve the problem.
Sometimes there may be an error or nullPointerException in the message that we want to print with Toast message. If this error occured then app will simply ignore the Toast message. I had the same issue. I printed the message in Log and found the error, after that I changed the message in Toast. And it worked as I wanted. Try it!!
Android throttles toats so if you send to many they just stop showing up, instead you can use Snackbar:
Snackbar.make(myView, "This is a snack.", Snackbar.LENGTH_SHORT).show();
Try:
Toast.makeText(v.getContext(), "Reason can not be blank", Toast.LENGTH_SHORT).show();
Complimer checks all the code and if there is a critical error, it ignores even the lines before the error section and therfore you will not see the "Toast".
Simply, comment the lines which error happens in them (you can find the error lines in Logcat)
Now you can see the "Toast" and can analyze your problem.

Android Toast Won't Disappear

I show the toast, it doesn't disappear, even after the app is closed. How do I fix?
#Override
public void onClipStoreLoadedClipsNotification(ClipStoreLoadedClipsNotification notif)
{
final ClipStoreLoadedClipsNotification notification = notif;
runOnUiThread(new Runnable() {
#Override
public void run()
{
Dialogs.DismissAll();
list.onRefreshComplete();
TextView text = (TextView)findViewById(R.id.loadclipstext);
ProgressBar pb = (ProgressBar)findViewById(R.id.loadclipsprogress);
if (notification.moreClipsAvailable)
{
text.setText(context.getString(R.string.loading_clips));
pb.setVisibility(View.VISIBLE);
}
else
{
text.setText(context.getString(R.string.no_clips));
pb.setVisibility(View.INVISIBLE);
int duration = Toast.LENGTH_SHORT;
Toast.makeText(SugarLoafContext.playbackTabContext, "No clips found.", duration).show();
}
SugarLoafContext.currentCamera = notification.camera;
clipList = notification.clips;
refreshListView();
readyToLoadMoreClips = true;
if (!firstClipsLoaded)
firstClipsLoaded = true;
}
});
}
Is it running inside a IntentService???
If it is so, the problem is that the Intent Services in Android run in a different thread than the main one, so the Toast is shown in a different thread than the main one, after the time to show is finished, the Android system is unable to find where is the Toast, so it can´t remove it.
I had the same problem, and now, i recommend everyone NOT to show Toast inside a IntentService, instead try to run one commom Service, or to open an Activity, or try something different if it is completely necessary to show the Toast.
The fact that the Toast doesn´t dissapear when you close the App is that the IntentService is still running, and you have to reboot the system or to uninstall the App for the Intent Service to be close.
The only explanation is that your Toast is called in a loop. You should track the toast .show() and see if it is not called an infinite times.
An other visual way would be to do this
Toast.makeText(SugarLoafContext.playbackTabContext, "No clips found.", duration).show();
Toast.makeText(SugarLoafContext.playbackTabContext, "Do you understand now?", duration).show();
I am sure you will see both toast alternatively during a looong time...
This can also happen if your device has no network connection, and your app does a license check and shows a Toast of results. One of my apps had this problem, as I was displaying a Toast when checking the app was licensed. Without a network connection the Toast telling the user that a license retry was to be done remained, and when I connected the Toast was removed, because the license check could work.

Categories

Resources