Reputation: 17
i want to set the gravity of toast in the center of the layout but when i add the gravity and run my app my app restarts and then crasehes. i have tried the toast both ways by taking the object and with out object here is code of my. the error is also attached
@Override
public void onBackPressed() {
new AlertDialog.Builder(MainActivity.this)
.setTitle("Exit")
.setIcon(R.drawable.ic_baseline_warning_24)
.setMessage("Sure? Your Want to Exit.")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finishAffinity();
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).setNeutralButton("Other", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast toast = Toast.makeText(MainActivity.this, "Click yes for exit.", Toast.LENGTH_SHORT)
.setGravity(Gravity.CENTER, 0,0);
toast.show();
}
}).show();
the error is copied from the run tab
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.androiddevelopment, PID: 3210
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Toast.setGravity(int, int, int)' on a null object reference
at com.example.androiddevelopment.MainActivity$3.onClick(MainActivity.java:52)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:177)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
i have tried this too but issue did not solved
@Override
public void onBackPressed() {
new AlertDialog.Builder(MainActivity.this)
.setTitle("Exit")
.setIcon(R.drawable.ic_baseline_warning_24)
.setMessage("Are you sure you want to exit")
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finishAffinity();
}
}).setNeutralButton("Help", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast toast = Toast.makeText(MainActivity.this, "This is an \"Android Studio\" learning app", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0,0);
toast.show();
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
Upvotes: 0
Views: 168
Reputation: 363637
Use:
public void onClick(DialogInterface dialog, int which) {
Toast toast = Toast.makeText(MainActivityJava.this, "Click yes for exit.", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0,0);
toast.show();
}
Upvotes: 1