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.
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
I'm developing an android app just for fun and practice.
The app consists of a splash screen and 4 activities.
One of the activites is filled with a webView.
I'm not able to get that webView work, when I run the app it shows only a white background.
here is my code :
https://drive.google.com/open?id=1oXHzBauNDy68mEIyI5EeNooIc9GaVPFh
Sorry to link the code in google drive, I wasn't able to properly format the question.
Any help will be appreciated
btw : activity_livechat is not a launcher activity.
First of all, enable JavaScript on your webview
Webview.getsettings().setJavaScriptEnabled(true);
Additionally, it's best to have error received methods in place for your webview so you'll know exactly what is the problem related to.
webView.setWebViewClient(new WebViewClient(){
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(context, "this is my error: " + description, Toast.LENGTH_LONG);
}
});
I have searched and found a lot of different answers for this question, but nothing quite settles it for me. Total android n00b, and I ask for your patience in advance.
I'm having trouble dealing with a FileChooser problem with Android KitKat. As per [here][1], and according to [Steve N][2] i get the impression that this file chooser problem is caused by my android version (4.4.2)
Given that filechooser isn't working, I want to implement a basic dialog. I'm going to check the android version number for the device, and then display a message, citing the current lack of support, if the version number comes back with a 4.4 in front.
At present, i'm just using toast
public boolean checkVersionSupport(){
if (Build.VERSION.RELEASE.equals("4.4.2") {
Toast toast = Toast.makeText(context, androidOS, duration);
toast.show();
}
}
Instead of toast, I'd like a simple, one button dialog box to open, with an OK button, which I will use to redirect the user out of the native app and off to chrome, where the whole file chooser thing seems to be working.
Couple of things that I have found difficult after reading through the android developer materials.
Do I need a layout XML file for the dialog box?
Where do I put the class file for the MyAlertDialogFragment class I am creating? Can it be anywhere in the java folder or does it have to be in a sub folder java/com.myproject... And what impact does that have for importing the class into my java activity file?
Can someone please explain where FragmentAlertDialog comes from in the Android Developer Materials.
public static class MyAlertDialogFragment extends DialogFragment {
public static MyAlertDialogFragment newInstance(int title) {
MyAlertDialogFragment frag = new MyAlertDialogFragment();
Bundle args = new Bundle();
args.putInt("title", title);
frag.setArguments(args);
return frag;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int title = getArguments().getInt("title");
return new AlertDialog.Builder(getActivity())
.setIcon(R.drawable.alert_dialog_icon)
.setTitle(title)
.setPositiveButton(R.string.alert_dialog_ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
((**FragmentAlertDialog**)getActivity()).doPositiveClick();
}
}
)
.setNegativeButton(R.string.alert_dialog_cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
((**FragmentAlertDialog**)getActivity()).doNegativeClick();
}
}
)
.create();
}
}
What's best practice for icons? I see a debate going on about this, but for the simple purpose of having an icon at the top of a dialog, for one single basic usage, what would be the quickest way of getting it done? I'm just copying files into the res folder and referencing them... 48dp? This might be a whole different question.
Do I need a layout XML file for the dialog box?
That honestly depends on which type of Dialog you use.
The AlertDialog does not require a specified layout, all you need is to use AlertDialog.Builder() and set the positive/negative buttons, and how it handles that.
The DialogFragment onCreateDialog() method is the preferred way of using an AlertDialog. It also doesn't require an XML layout, but as such, its layout is still restricted to essentially a Yes/No option: look here for complete example
The DialogFragment onCreateView() method allows you to create a dialog from a specified layout XML. So if you wish to customize the view of the dialog beyond "title, description, yes/no", then yes, you need to specify the XML file for the dialog fragment, look here for an example, although the advice says you should look into ButterKnife and Otto libraries to make it even better.
Where do I put the class file for the MyAlertDialogFragment class I am creating? Can it be anywhere in the java folder or does it have to be in a sub folder java/com.myproject... And what impact does that have for importing the class into my java activity file?
Anywhere inside the project. Although I prefer to put it in something like <projectroot>/presentation/fragments/dialog, package-wise.
Can someone please explain where FragmentAlertDialog comes from in the Android Developer Materials.
FragmentAlertDialog is an assumed Activity from which the MyAlertDialogFragment dialog fragment is shown, and is assumed to have the methods doPositiveClick() and doNegativeClick(). The title int that is provided is most likely a string resource defined in /res/values/strings.xml which is used for localization. For example, R.string.fancy_title_name.
So it's something like this
public class FragmentAlertDialog extends AppCompatActivity {
#Override
public void onCreate(Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_fragment_alert_dialog);
//stuff
}
#Override
public void onPostResume() {
MyAlertDialogFragment madf = MyAlertDialogFragment.newInstance(R.string.something);
madf.show(getSupportFragmentManager(), "alert-dialog-fragment");
}
}
Otherwise, MyAlertDialogFragment just extends from DialogFragment and overrides onCreateDialog to create an AlertDialog inside this DialogFragment.
In case you'd ask, the newInstance() method is so that you would NOT use a parametrized constructor. Fragments should not have parametrized constructors, they ought to receive their data in the setArguments(Bundle) method.
What is the best practice for icons?
Refer to the material design guidelines.
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.