I'm developing a game via Andengine for Android. I have MainActivity class and GameScene class. I use Toast messages in GameActivity. And it is working.
Toast.makeText(this, " Hello World", Toast.LENGTH_SHORT).show();
So I wanna use Toast messages in GameScene class. But it doesn't work. Here is the code:
Toast.makeText(activity, " Hello World", Toast.LENGTH_SHORT).show();
I have to use "activity" instead of "this". But it doesn't work
why?
EDITED:
when I use second one, an error occurs.
LogCat:
http://s29.postimg.org/k8faj9mdj/Capture.png
You're trying to display a Toast in a background thread. You should do all your UI operations on the main UI thread.
The exception RuntimeException: Can't create handler inside thread that has not called Looper.prepare() can be a little cryptic for beginners but essentially it tells you that you're in a wrong thread.
To solve it, wrap the toast to e.g. runOnUiThread():
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(...).show();
}
});
There could be two reasons for your code to not work. It's ether your activity parameter is null or...
Short time after you showing the toast the activity is die, in that case it will kill the toast as well, to avoid this you can call activity.getApplicationContext() like in #Mehmet Seçkin answer.
use one of the following
Toast.makeText(getApplicationContext(), " Hello World", Toast.LENGTH_SHORT).show();
Toast.makeText(getBaseContext(),"please Create your Account First", Toast.LENGTH_SHORT).show();
Toast.makeText(GameActivity.this,"please Create your Account First", Toast.LENGTH_SHORT).show();
Use:
Toast.makeText(getApplicationContext(), " Hello World", Toast.LENGTH_SHORT).show();
or
Toast.makeText(activity.this, " Hello World", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "text", Toast.LENGTH_SHORT).show();
try this.
Since you asked why; i think you're giving an activity reference as a context to the Toast message, this is why it isn't working.
If you're trying to show a Toast message from outside of an activity, you could try :
Toast.makeText(activity.getApplicationContext(), " Hello World", Toast.LENGTH_SHORT).show();
or from the GameActivity
Toast.makeText(GameActivity.this, " Hello World", Toast.LENGTH_SHORT).show();
or from the MainActivity
Toast.makeText(MainActivity.this, " Hello World", Toast.LENGTH_SHORT).show();
Since You are calling it from the class. you need to get the context from the activity through the class constructor or else you need to use GetApplicationcontext().
Make sure the app you are testing has notifications turned on. That was my story and why toasts weren't working either. I had gone looking for a straight answer and it just happens that toasts are considered part of the notifications. Interesting stuff, I had no clue.
If you think your code is correct, try to close your emulator tab then open AVD manager, next wipe data, then restart. Or you can delete the current AVD and add a new one.
Related
I have a Unity Scene built with Cardboard SDK and exported as a library for Android. The library is used to play videos in cardboard mode on the android app. it's not the whole app, but a part in it. The rest of the android app is built with Kotlin and Java.
I have implemented that and all the functions work as expected, but, exiting the scene crashes the android.
We tried various ways to clear player prefs and even clear memory before closing the scene. But on android it always crashes. I have two android phones with android 9 and 10 for testing.
In the android app, I have made it such that as soon as the app crashes, I try to recover. My crash is that some lateinit var variables are destroyed. Their value becomes null and recovering the previous activity crashes it. So right after I exit the unity scene, I load the dereferenced variables back into memory and everything works again.
Note: I have tried using Application.Quit(); in unity, but it just closes the whole app. On the other hand, I only want to close the running scene
In unity [I call a function goBack in android part to close the app]:
public void GoToHome()
{
Pause();
Stop();
Resources.UnloadUnusedAssets();
PlayerPrefs.DeleteAll();
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
jo.Call("goBack");
}
In App:
public void goBack()
{
UnityPlayer.currentActivity.finish();
finish();
loadDerereferencedVars();
}
This goes perfectly on android 9. On the other phone with android 10, after I close the scene, the app continues to function, but, there comes a message
When I click close app, the app continues to work.
I have checked the logs and there is a null pointer dereference cause for the crash in Unity Main >...
If you'd like to see the Unity Crash Log from LogCat in Android Studio
So, since the app is still running, I thought, it would be better to just hide the crash report and just let the user not know about this crash, but still report it.
I tried enclosing my app in Application and added a method to catch uncaughtException.
here is my application class:
public class MyApp extends Application {
private static final String TAG = "MyAPP";
#Override
public void onCreate() {
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler(
new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException (Thread thread, Throwable e) {
handleUncaughtException (thread, e);
}
});
}
/**
* Handles Uncaught Exceptions
*/
private void handleUncaughtException (Thread thread, Throwable e) {
// The following shows what I'd like, though it won't work like this.
Toast.makeText(getApplicationContext(), "Looks like I am having a bad day!", Toast.LENGTH_LONG).show();
Log.e("UncaughtException", "I found an exception!");
// Add some code logic if needed based on your requirement
}
}
Again, this works perfectly in Android 9 and I also got the error reported. However in the phone with android 10, I just get the crash report like the image above and no error is reported.
I want to know why the crash handling is not working and how can I fix it?
I would not finish the Activity you came from, instead just open a new intent (on UnityActivity). When you end this intent the app will come back to the last active Activity.
I will give you my script as an example:
public void sendJobToUnity(String fileName, boolean isNewJob){
//creates a new job. It exists inside the JobSelector Activity
isUnityLoaded = true;
//this is what you are looking for part1
Intent i = new Intent(JobSelector.this, MainUnityActivity.class); //same as (CurrentActivity.this, UnityActivity.this)
//those are how I send some data across the app. just ignore it
//i.putExtra("jobName", fileName);
//i.putExtra("isNewJob",isNewJob);
//i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivityForResult(i, 1); //this is what you are looking for part2
}
For closing it, in the MainUnityActivity Activity I have an override that Unity sends to Android in order to Unload the activity (not quit it completely cause you cannot load it again if you do it) like this:
#Override
protected void receiveJobAndUnloadUnity(String data){
saveCurrentJob(data); //saves the job it receives from Unity
mUnityPlayer.unload(); //this is what you are looking for part3
}
If you want to unload Unity from android you can put "mUnityPlayer.unload();" wherever you want, provided you have started the Activity the way I've shown you.
Note that "mUnityPlayer" is a default Unity variable and cannot be renamed
This question already has answers here:
what is the activity name in anonymous class
(4 answers)
Closed 4 years ago.
I want to know what 'this' means in the below Toast command:
Toast.makeText(MainActivity.this, "msg" ,Toast.Length_long ).show();
If possible could you please explain the whole command.
In general when you use construct SomeClass.this that means that you are referring to the specific (frequently 'outer' class). In example you can have a code like:
class Apple {
void outherMethod() {
}
class AppleType {
void innerMethod(){}
void method(){
Apple.this.outerMethod();
this.innerMethod();
}
}
}
Additionally, in this specific case on Android it means that you are using the activity's Context which is provided via MainActivity class.
So the whole command should be read as:
Create Toast widget inside context provided by MainActivity
It should display some text: "msg"
It should be visible for specific time defined by the constant: Toast.Length_long
finally, via show() method display it on device.
'this' means itself.
Toast.makeText(MainActivity.this, "msg" ,Toast.Length_long ).show();
Call the toast method, and the required parameters are 'context', 'toast message' and 'toast duration'.
Finally .show() means make toast to show.
its clear and you can use it like this
Toast toast =Toast.makeText(this, "msg", duration);
toast.show();
this: context
"msg": your message
duration: Toast.LENGTH_SHORT or Toast.LENGTH_LONG
and you can change position by setting gravity
toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);
this will show toast center screen
This is an extremely simple issue I am facing. Basically, I am requesting run-time permissions—but I also want to show a toast at the same time as the permission request:
Relevent Code:
if ((ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{
Manifest.permission.RECORD_AUDIO,
Manifest.permission.WRITE_EXTERNAL_STORAGE}, 4);
Toast.makeText(MainActivity.this, "You must enable BOTH", Toast.LENGTH_LONG).show();
The problem is, the toast quickly disappears (within maybe less than 0.5 second), as soon as the permission dialog appears.
Is this a bug on Android? Or is there some work around that I'm missing?
Toasts don't display permanently. The entire concept of a Toast is that it pops up then fades away. If you want something more permanent, you'll have to implement it yourself.
It's default dialog for permission in android so no solution for this.ya but if you make your custom dialog then you can show it where you want.
Toast message is displayed for short duration of 2 sec or for long duration of 3.5 sec and it cannot be changed.
If you wish to display the toast message for longer time then you need to display it continuously.
for (int i=0; i < 5; i++){
Toast.makeText(this, "Your toast message", Toast.LENGTH_SHORT).show();
}
It will display your toast for 10 seconds.
Hope it helps :)
Try to make the context as
Toast.makeText(getApplicationContext(),"YOUR TEXT",Toast.LENGTH_LONG).show();
I'm working on an android app while learning to code in Java and I'm building a note taking app currently and am trying to convert what used to be a toast message to a snackbar message. Below is what I currently have along with the toast message that used to be there that is now commented out. I'm getting stuck on the method it says to call, any help would be greatly appreciated!
private void deleteNote() {
getContentResolver().delete(NotesProvider.CONTENT_URI,
noteFilter, null);
Snackbar.make(this, getString(R.string.note_deleted), Snackbar.LENGTH_LONG).show();
// Toast.makeText(this, getString(R.string.note_deleted),
// Toast.LENGTH_SHORT).show();
setResult(RESULT_OK);
finish();
}
The error android studio gives me is it cannot resolve the method "make".
The make function takes a view as the first parameter.
public static Snackbar make(View view, int resId, int duration)
If you need it in the bottom of your activity pass findViewById(android.R.id.content) as the first parameter.
I have an android app that simply just toggles a value in the settings. For this app when clicked I DON'T want to show a layout, just a Toast and then kill itself. I have this already:
public class Test extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
Toast.makeText(this, "MESSAGE", Toast.LENGTH_LONG).show();
android.os.Process.killProcess(android.os.Process.myPid());
}
}
Is there a possibility to disable the layout at all?
It sounds like a Service will be much more appropriate in this case.
Services run in the background, but can still perform some limited UI tasks such as showing Toasts.
Activities are not designed to be used without a UI.
Simple, just comment out one line looks like:
//setContentView(R.layout.activity_main);
oh, to kill self, you may simply call finish by the end of onCreate.