back button alert box(Android Studio) - java

In my first class, I have this piece of code:
public void onBackPressed() {
new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle(R.string.ALERTA1)
.setMessage(R.string.ALERTA2)
.setPositiveButton(R.string.ALERTA3, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton(R.string.ALERTA4, null)
.show();
}
This will make an alert box when the back button is pressed, but this works in every class, I only want it to work in this one.
UPDATE:
public void onBackPressed() {
finish();
}
In every class.

Put this in your other classes:
public void onBackPressed() {
super.onBackPressed();
return;
}
That might work.

Related

Calling the same method from different activities

I have searched for an answer to this issue and while there are many similar topics, none of the solutions suit my needs. I have this code in MainActivity and it works there but I need to call the same 'addPlayer' method in another activity.
I have also tried creating a new java class called 'AddPlayer.java' to call in both activities via buttons in each but I can't find a way to call it. Perhaps its in the way I've defined the .java class?
public class AddPlayer extends AppCompatActivity {
public void addPlayer (View view) {
// followed by same content as method in MainActivity - edited to correct contexts
MainActivity code
public class MainActivity extends AppCompatActivity {
public void addPlayer (View view) {
final ParseObject players = new ParseObject("Players");
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final AlertDialog.Builder builderInBuilder = new AlertDialog.Builder(this);
final EditText nameInput = new EditText(this);
nameInput.setInputType(InputType.TYPE_CLASS_TEXT);
final EditText nickInput = new EditText(this);
nickInput.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setTitle("New Player Details")
.setMessage("Enter new player name...")
.setIcon(android.R.drawable.gallery_thumb)
.setView(nameInput)
.setPositiveButton("Add Player", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
builderInBuilder.setTitle("New Player Details")
.setMessage("Enter player Nickname...")
.setIcon(android.R.drawable.gallery_thumb)
.setView(nickInput)
.setPositiveButton("Add Nickname", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
players.add("nickname", nickInput.getText().toString());
players.add("username", nameInput.getText().toString());
players.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e != null) {
Toast.makeText(MainActivity.this, "Player could not be added.\n" + e.getMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Player added successfully.", Toast.LENGTH_SHORT).show();
}
}
});
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Add New Player cancelled.", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
})
.show();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Add New Player cancelled.", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
})
.show();
}
I get no errors calling the method in MainActivity, I am just unsure of how best to call this method from 2 activities and the syntax required to call the separate java class - which has the correct package assignment.
I was expecting to be able to use
AddPlayer.addPlayer(); // or something similar
Perhaps the best way is just to have this code in both locations? Seems inefficient though...
create class todo the task and call it
class AddPlayer{
public void player(Context ctx,View view){
//do your work here
}
}
then call that method like this
AddPlayer addp = new AddPlayer ();
addp.player(context,view);
I think the concept is like that, if you don't want to create a new instance to call the method, you can declare the method as static

How to check Alert Dialog visibility?

I want to check alert dialog is visible or not. In most post I saw that they used isShowing, but seems like its not describable now.
When user click info textview, I pause music. If user close alert dialog, music will be play again.
info_Button.setClickable(true);
info_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaControl.pause();
AlertDialog.Builder playstopbutton_builder = new AlertDialog.Builder(exercise_arm_triceps_execute.this);
playstopbutton_builder.setTitle("WARNING").setMessage("Please get warm before exercising!");
playstopbutton_builder.create().show();
playstopbutton_builder.setCancelable(false);
//if alert dialog is visible keep music paused
//else if mediaControl.start();
}
});
since you have made Cancelable false, you might need to use
for positive button say like a okay
playstopbutton_builder.setPositiveButton(positiveBtnText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//resume ur media player here
}
})
for negative button say like a cancel
playstopbutton_builder.setNegativeButton(negativeBtnText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//resume ur media player here
}
})
so it would look like this
info_Button.setClickable(true);
info_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaControl.pause();
AlertDialog.Builder playstopbutton_builder = new AlertDialog.Builder(exercise_arm_triceps_execute.this);
playstopbutton_builder.setTitle("WARNING").setMessage("Please get warm before exercising!");
playstopbutton_builder.create().show();
playstopbutton_builder.setCancelable(false);
playstopbutton_builder.setPositiveButton(positiveBtnText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//resume ur media player here
}
});
playstopbutton_builder.setNegativeButton(negativeBtnText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//resume ur media player here
}
});
}
});
You need to check dialog show or not change you code like this.
info_Button.setClickable(true);
info_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaControl.pause();
AlertDialog.Builder playstopbutton_builder = new AlertDialog.Builder(exercise_arm_triceps_execute.this);
playstopbutton_builder.setTitle("WARNING").setMessage("Please get warm before exercising!");
playstopbutton_builder.create();
playstopbutton_builder.setCancelable(false);
//if alert dialog is visible keep music paused
//else if mediaControl.start();
if(!playstopbutton_builder.isShowing()){
//if its visibility is not showing then show here
playstopbutton_builder.show();
}else{
//do something here... if already showing
}
}
});
You may want to add an OnDismissListener to the playstopbutton_builder:
playstopbutton_builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
mediaControl.start();
}
});
This way, when the user dismisses the Alert Dialog, the music will start to play again.
EDIT: if the OnDismissListener approach is not desired, maybe something like this would be better:
public void infoClickHandler(View v) {
mediaControl.pause();
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setMessage("restart the music?");
b.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mediaControl.start();
}
});
b.show();
}
EDIT 2: On the other hand, if the dialog cannot have positive or negative buttons, and you do not want to set cancellable to false, this seems to work:
public void infoClickHandler(View v) {
mediaControl.pause();
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setMessage("restart the music?");
b.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
if (!mediaControl.isPlaying()) {
mediaControl.start();
}
}
});
b.show();
}
The OnDismissListener will be called when the user clicks outside of the dialog box.

Execution doesn't wait to Alertdialog.dismiss()

I'm developing an Android application and I have this question:
How can I do to make execution waits until user has selected an option from an AlertDialog?
This is my code:
if (mPerson== null)
{
mPerson = new Person();
AlertDialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.dialog_message_select))
.setTitle(getString(R.string.dialog_title_attention));
builder.setPositiveButton(R.string.male, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
mPerson.setGender(Gender.male);
dialog.dismiss();
}
});
builder.setNegativeButton(R.string.female, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int arg1)
{
mPerson.setGender(Gender.female);
dialog.dismiss();
}
});
dialog = builder.create();
dialog.show();
}
// TODO: Show data.
getWidgetsRefereces();
customizeLayout();
loadSpinnerValues();
After dialog.dismiss() I have to execute this:
// TODO: Show data.
getWidgetsRefereces();
customizeLayout();
loadSpinnerValues();
Do the following:
AlertDialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.dialog_message_select))
.setTitle(getString(R.string.dialog_title_attention));
builder.setPositiveButton(R.string.male, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
mPerson.setGender(Gender.male);
dialog.dismiss();
postSelection();
}
});
builder.setNegativeButton(R.string.female, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int arg1)
{
mPerson.setGender(Gender.female);
dialog.dismiss();
postSelection();
}
});
dialog = builder.create();
dialog.show();
}
Call this method once the selection is complete.
public void postSelection(){
getWidgetsRefereces();
customizeLayout();
loadSpinnerValues();
}
Think in terms of event based execution. If you want some code to execute when you press a button, then wire it to do so. Place the code in question in a method that you can call whenever you want.
Generally, when you are programming on Android, you need to adhere to the event based nature of the platform. Traditional procedural sequential thinking will lead you to dead ends.
You have to customize your dialog interface like this .
You should use onDismissListener on dialog interface.Dont make it anonymous.
private class MyDialogInterfaceMethod implements DialogInterface.OnClickListener,DialogInterface.OnDismissListener
{
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//when user click a button
}
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
//put your code here
}
}
Than use it on your alert dialog like this
builder.setNegativeButton("CANCEL",new MyDialogInterfaceMethod ());

ANDROID onBackPressed doesnt work for the activity

I implemented the onBackPressed for my activity where it will check the internet connection but when i click the back button in my tablet, it does nothing. I dont understand what is the cause of it. Can help?
Below is my code
if (!cd.isConnectingToInternet()) {
AlertDialog.Builder splash = new AlertDialog.Builder(this);
splash.setIcon(R.drawable.ic_fail)
.setTitle("No Internet Connection")
.setMessage(
"Please check your internet connection and try again.")
.setCancelable(false)
.setPositiveButton("Try again",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
Intent splash = new Intent(
getApplicationContext(),
SplashActivity.class);
startActivity(splash);
finish();
}
})
.setNegativeButton("Wifi Setting",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
startActivity(new Intent(
android.provider.Settings.ACTION_WIFI_SETTINGS));
dialog.cancel();
}
});
AlertDialog alert = splash.create();
alert.show();
} else {
Thread timer = new Thread() {
public void run() {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent login = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(login);
finish();
}
}
};
timer.start();
}
}
public void onRestart() {
super.onRestart();
Intent splash = new Intent(getApplicationContext(),
SplashActivity.class);
startActivity(splash);
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
just try this code...
#Override
public void onBackPressed()
{
moveTaskToBack(true);
}
comment, and check
//super.onBackPressed();
- finish() is the proper way to close the Activity.
- But still if its doesn't, due to some reason use System.exit(0) after finish().. this will surely work.... I know its crude...but works...
///////////////////////////// Edited Part///////////////////////////////////////
- override the method onKeyDown() of Activity.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
this.finish();
}
return true;
}
try this instead. I think it will Work for you.
#Override
public void onBackPressed() {
//super.onBackPressed();
// finish your Activity
ActivityName.this.finish();
return;
}
Try This:
#Override
public void onBackPressed() {
yourclassname.this.finish();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
getParent().finish();
}

Android: Prompt user to save changes when Back button is pressed

I have an activity that contains several user editable items (an EditText field, RatingBar, etc). I'd like to prompt the user if the back/home button is pressed and changes have been made that have not yet been saved. After reading through the android documentation, it seems like this piece of code should go in the onPause method. I've tried putting an AlertDialog in the onPause however the dialog gets shown and then immediately tears down because nothing is there to block the pause from completing.
This is what I've come up with so far:
#Override
protected void onPause() {
super.onPause();
AlertDialog ad = new AlertDialog.Builder(this).setMessage(
R.string.rating_exit_message).setTitle(
R.string.rating_exit_title).setCancelable(false)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// User selects OK, save changes to db
}
}).setNeutralButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// User selects Cancel, discard all changes
}
}).show();
}
Am I on the right track or is there another way to accomplish what I'm trying to do here? Any help would be great!
You're not quite on the right track; what you should be doing is overriding onKeyDown() and listening for the back key, then overriding the default behavior:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
// do something on back.
return true;
}
return super.onKeyDown(keyCode, event);
}
If you're only supporting Android 2.0 and higher, they've added an onBackPressed() you can use instead:
#Override
public void onBackPressed() {
// do something on back.
return;
}
This answer is essentially ripped from this blog post. Read it if you need long presses, compatibility support, support for virtual hard keys, or raw solutions like onPreIme() etc.
What do you think about this approach ..
private void exit(){
this.finish();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setTitle("Message");
alertbox.setMessage("Quit ??? ");
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
exit();
}
});
alertbox.setNeutralButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
});
alertbox.show();
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
Here is some sample code:
#Override
public void onBackPressed() {
if (isDirty) {
new AlertDialog.Builder(this)
.setTitle("You have made some changes.")
.setMessage("Would you like to save before exiting?")
//.setNegativeButton(android.R.string.no, null)
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
MyActivity.super.onBackPressed();
}
})
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
if (Save())
MyActivity.super.onBackPressed();
}
}).create().show();
}
else {
MyActivity.super.onBackPressed();
}
}
I am doing the same thing that you do. I have one activity with a customer information (EditText for name, last name, email, ..., you know, EditText everywhere) and I used AsyncTask for that, and it works wonderfully.
#Override
public void onBackPressed()
{
// start async task for save changes.
new GuardandoContactoHilo().execute()
}
public void VolverAtras()
{
super.onBackPressed();
}
public class GuardandoContactoHilo extends AsyncTask< Void, Void, Void>
{
private ProgressDialog saving;
#Override
protected void onPreExecute()
{
super.onPreExecute();
saving = new ProgressDialog(cont);
saving.setProgressStyle(ProgressDialog.STYLE_SPINNER);
saving.setMessage("Saving customer ...");
saving.show();
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
saving.dismiss();
VolverAtras(); // go back !!
}
#Override
synchronized protected Void doInBackground(Void... arg0)
{
// do what you want to do before come back ! for example, save data ;)
return null;
}
}

Categories

Resources