Adding a Cancel Button to a CustomAlertDialog - java

I am just a themer, not a programmer, any help/guidance is appreciated.
I am trying to add a Cancel button to this code:
public class gobuuf extends Activity {
/** Called when the activity is first created. */
class CustomAlertDialog extends AlertDialog {
public CustomAlertDialog(Context context) {
super(context);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
boolean ret = super.onKeyDown(keyCode, event);
finish();
return ret;
}
public void setCancel(int buttonNegative, String string, Object object) {
// TODO Auto-generated method stub
}
}
private CustomAlertDialog mDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (isExistSkin("com.gau.go.launcherex")) {
startGOLauncher("com.gau.go.launcherex");
finish();
return;
}
mDialog = new CustomAlertDialog(this);
mDialog.setTitle(R.string.dialogtitle);
mDialog.setMessage(getResources().getString(R.string.dialogcontent));
mDialog.setCancel(DialogInterface.BUTTON_NEGATIVE, getResources().getString(R.string.dialognothanks), null);
mDialog.setButton(DialogInterface.BUTTON_POSITIVE, getResources().getString(R.string.dialogok),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String marketuriString = "market://search?q=pname:com.gau.go.launcherex";
Intent EMarketintent = new Intent(Intent.ACTION_VIEW, Uri.parse(marketuriString));
EMarketintent.setPackage("com.android.vending");
EMarketintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(marketuriString));
try {
startActivity(EMarketintent);
} catch (ActivityNotFoundException e) {
String link = "http://61.145.124.93/soft/3GHeart/com.gau.go.launcherex.apk";
Uri browserUri = Uri.parse(link);
Intent browserIntent = new Intent(Intent.ACTION_VIEW, browserUri);
browserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
startActivity(browserIntent);
} catch (ActivityNotFoundException e2) {
// TODO: handle exception
e2.printStackTrace();
}
} catch (Exception e3) {
// TODO: handle exception
e3.printStackTrace();
}
finish();
}
});
mDialog.show();
}
#Override
protected void onDestroy() {
super.onDestroy();
android.os.Process.killProcess(android.os.Process.myPid());
}
private boolean isExistSkin(String packageName) {
try {
createPackageContext(packageName,
Context.CONTEXT_IGNORE_SECURITY);
} catch (NameNotFoundException e) {
return false;
}
return true;
}
private void startGOLauncher(String packageName){
PackageManager packageMgr = this.getPackageManager();
Intent launchIntent = packageMgr.getLaunchIntentForPackage(packageName);
if (null != launchIntent){
try
{
this.startActivity(launchIntent);
}
catch(ActivityNotFoundException e)
{
}
}
}
}
I have added the corresponding string, but don't know what else to do: add an onclicklistener, I know I need some kind of action coded somewhere finish(); or .cancel something. Thanks for any help, again.
I should say, I've been playing around with this bit you see:
mDialog.setCancel(DialogInterface.BUTTON_NEGATIVE,getResources().getString(R.string.dialognothanks), null);

I am not sure if this is exactly what you are looking for, but you can do something like this... this one just closes the dialog.
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
For a very good tutorial on creating dialogs, I would recommend using : http://developer.android.com/guide/topics/ui/dialogs.html. This should be very helpful.

It's now working and performing how I wanted it to by doing this:
1) I removed:
public void setCancel(int buttonNegative, String string, Object object) {
// TODO Auto-generated method stub
}
and
mDialog.setCancel(DialogInterface.BUTTON_NEGATIVE, getResources().getString(R.string.dialognothanks), null);
2) and added:
mDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getResources().getString(R.string.dialognothanks),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mDialog.cancel();
finish();
}
});
just before the
mDialog.show();
Trial and Error FTW. Maybe I should learn Java and Android from the ground up to save me the time later.
Now I have to learn how to make the Cancel button not only finish(); but also start another activity.

I figured out how to start an activity by following the answer on this page:
Android: How to start an Activity from an alert dialog
So my code now looks like:
mDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getResources().getString(R.string.dialognothanks),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getBaseContext(), AboutActivityOverview.class);
startActivity(i);
}
});

Related

System services not available to Activities before onCreate() while opening a Dialog from RecyclerView

I'm having this error out of the blue and have no idea what's causing it or where it has come from.
Basically I've got a RecyclerView that gets populated with products. When a product is selected, I've got a custom Dialog that pops up where the user can increase product quantity or remove the product. This all works, however if I click the same product a second time it crashes the app with the following error:
System services not available to Activities before onCreate()
This is my RecyclerView.Adapter with the onBindViewHolder()
public class OrderAdapter extends RecyclerView.Adapter<OrderAdapter.MyViewHolder>{
#Override
public void onBindViewHolder(#NonNull OrderAdapter.MyViewHolder holder, int position) {
final Item Item = ItemList.get(position);
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog = new Dialog(context,R.style.Custom_Theme_Dialog);
//Code breaks on this line
dialog.setContentView(R.layout.dialog_cart_edit);
cartProdDesc = dialog.findViewById(R.id.lblcartProdDesc);
cartQuantity = dialog.findViewById(R.id.edit_quantity);
btnDone = dialog.findViewById(R.id.btn_dialog_done);
btnRemove = dialog.findViewById(R.id.btn_dialog_remove);
addQuantity = dialog.findViewById(R.id.addition_action);
minusQuantity = dialog.findViewById(R.id.minus_action);
cartProdDesc.setText(cartItem.getProductDescription());
cartPackSize.setText(cartItem.getPackSize());
addQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
quantity = Integer.parseInt(cartQuantity.getText().toString());
} catch (NumberFormatException nf) {
Log.e("Number Exception","Number Is Blank");
quantity = 0;
} catch (Exception e){
Log.e("ERROR",e.toString());
}
cartQuantity.setText(String.valueOf(++quantity));
}
});
minusQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
quantity = Integer.parseInt(cartQuantity.getText().toString());
} catch (NumberFormatException nf) {
Log.e("Number Exception","Number Is Blank");
quantity = 0;
} catch (Exception e){
Log.e("ERROR",e.toString());
}
cartQuantity.setText(String.valueOf(--quantity));
}
});
btnDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(cartQuantity.getText().toString().isEmpty() || cartQuantity.getText().toString().equals("0") || cartQuantity.getText().toString().contains("-")){
cartQuantity.setError("Enter a valid quantity");
} else {
newQuantity = cartQuantity.getText().toString();
db.updateCartItem(new CartItem(cartItem.getId(),cartItem.getProductCode(),cartItem.getBarcode(),cartItem.getNappiCode(),cartItem.getProductDescription(),cartItem.getPackSize(),newQuantity));
updateDataSet();
notifyDataSetChanged();
dialog.dismiss();
}
}
});
btnRemove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogInterface.OnClickListener dialogClickListner = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
db.deleteCartItem(cartItem.getId());
updateDataSet();
dialog.dismiss();
break;
case DialogInterface.BUTTON_NEGATIVE:
dialog.dismiss();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Are you sure you want to remove " + cartItem.getProductDescription()).setPositiveButton("Yes",dialogClickListner).setNegativeButton("No",dialogClickListner).show();
}
});
dialog.show();
}
});
}
}
I've got a private Dialog dialog; declaration further up on the Activity in case anyone was wondering.
The code breaks on the dialog = new Dialog(context,R.style.Custom_Theme_Dialog); however if I comment out the dialog.show() at the end I have no issues, apart from the dialog not showing, but that tells me that the problem isn't with the assigning of the dialog, or am I wrong on this train of thought ?
This is a line of code in my OrderActivity where I'm calling the adapter, I'm sending the context from here.
OrderAdapter = new OrderAdapter(this,ItemList);
This is my constructor where I'm assigning Context
public OrderAdapter(Context context, List<CartItem> cartItemList){
this.context = context;
this.cartItemList = cartItemList;
}
Depending on where that Context is coming from exactly, it might have already been "destroyed" by the time onClick() is called (well not really, because the Dialog is holding an implicit reference to it). In this case this is also a memory leak.
I'd suggest you to change the following:
#Override
public void onClick(View view) {
dialog = new Dialog(context, R.style.Custom_Theme_Dialog);
To this:
#Override
public void onClick(View view) {
dialog = new Dialog(view.getContext(), R.style.Custom_Theme_Dialog);
This way you'll always reference the Context the corresponding View is associated with.

How to use AsyncTask method outside

I am checking server available or not with AsyncTask class and its working fine with below code
class AsyncServerOnlineCheck extends AsyncTask {
boolean isReachable;
#Override
protected Object doInBackground(Object[] objects) {
isReachable = NetworkCheck.isReachable(SplashsActivity.this);
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
if (isReachable) {
new DownloadLatestData().execute();
Toast.makeText(SplashsActivity.this, "Server is online", Toast.LENGTH_SHORT).show();
} else {
if (database.isDataBaseCreated()) {
Toast.makeText(SplashsActivity.this, "Server is offline", Toast.LENGTH_SHORT).show();
Intent i = new Intent(SplashsActivity.this, MainActivity.class);
startActivity(i);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
finish();
} else {
connectionerror();
}
}
}
}
Now I want use isReachable condition in other method called connectionerror. Both is in same activity. connectionerror is like below
public void connectionerror() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(SplashsActivity.this);
alertDialog.setTitle("Error!");
alertDialog.setMessage("Connection Lost ! Try Again");
alertDialog.setPositiveButton("Retry",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (downloadLatestDataStatus != null) {
downloadLatestDataStatus.clear();
}
if (NetworkCheck.isInternetAvailable(SplashsActivity.this)) {
new DownloadLatestData().execute();
} else {
connectionerror();
}
}
});
alertDialog.show();
}
You can see one condition in connectionerror method like below
if (NetworkCheck.isInternetAvailable(SplashsActivity.this)) {
new DownloadLatestData().execute();
}
instead this condition for network check, I want use isReachable from AsyncTask....How can I do it ?
I have got solved via hire freelancer for fix it. He have done like below in alert dialogue
new AsyncServerOnlineCheck().execute();
Thanks all friends !!

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();
}

How to show ProgressDialog after AlertDialog

I am having trouble with an alert dialog that I cannot hide.
when the user press a button I show a dialog that is created with this code :
new AlertDialog.Builder(this)
.setTitle(R.string.enterPassword)
.setView(textEntryView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String password = pwdText.getText().toString();
dialog.dismiss();
processUserAction(password,targetUri);
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.
create();
There are some heavy operations performed in the 'processUserAction' method, and inside it I am using an AysncTask that displays a ProgressDialog.
The problem I am having is that the dialog prompting for the password never goes of the screen (I have tried with dismiss(), cancel()).
I guess it stays there until the onClick method is finished.
So, my question is how to close that AlertDialog, so I can show the ProgressDialog?
Another approach I have been trying is to set a DismissListener in the AlertDialog and calling the heavy operations from there, but I have had no luck ( it didn't get called ).
EDIT: Adding AsyncTask code
public class BkgCryptOperations extends AsyncTask<File,Void,Integer>{
#Override
protected Integer doInBackground(File... files) {
if (files!=null && files.length > 0){
File source = files[0];
File target = files[1];
return cryptAction.process(source,password, target);
}
return Constants.RetCodeKO;
}
CryptAction cryptAction;
String password;
ProgressDialog progressDialog;
public BkgCryptOperations (CryptAction cryptAction,String password,ProgressDialog progressDialog){
this.cryptAction=cryptAction;
this.password=password;
this.progressDialog=progressDialog;
}
#Override
protected void onPreExecute() {
if (progressDialog!=null){
progressDialog.show();
}
}
protected void onPostExecute(Integer i) {
if (progressDialog!=null){
progressDialog.dismiss();
}
}
}
Thanks in advance
Here is a excample how I do it:
public void daten_remove_on_click(View button) {
// Nachfragen
if (spinadapter.getCount() > 0) {
AlertDialog Result = new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle(getString(R.string.dialog_data_remove_titel))
.setMessage(getString(R.string.dialog_data_remove_text))
.setNegativeButton(getString(R.string.dialog_no),
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialogInterface, int i) {
// Nicht löschen
dialogInterface.cancel();
}
})
.setPositiveButton(getString(R.string.dialog_yes),
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialogInterface, int i) {
String _quellenName = myCursor.getString(1);
deleteQuellenRecord(_quellenName);
zuletztGelöscht = _quellenName;
}
}).show();
} else {
// Keine Daten mehr vorhanden
Toast toast = Toast.makeText(Daten.this,
getString(R.string.dialog_data_remove_empty),
Toast.LENGTH_SHORT);
toast.show();
}
}
Here is the code of deleteQuellenRecord:
private void deleteQuellenRecord(String _quellenName) {
String DialogTitel = getString(R.string.daten_delete_titel);
String DialogText = getString(R.string.daten_delete_text);
// Dialogdefinition Prograssbar
dialog = new ProgressDialog(this) {
#Override
public boolean onSearchRequested() {
return false;
}
};
dialog.setCancelable(false);
dialog.setTitle(DialogTitel);
dialog.setIcon(R.drawable.icon);
dialog.setMessage(DialogText);
// set the progress to be horizontal
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// reset the bar to the default value of 0
dialog.setProgress(0);
// set the maximum value
dialog.setMax(4);
// display the progressbar
increment = 1;
dialog.show();
// Thread starten
new Thread(new MyDeleteDataThread(_quellenName)) {
#Override
public void run() {
try {
// Datensatz löschen
myDB.execSQL("DELETE ... ');");
progressHandler
.sendMessage(progressHandler.obtainMessage());
myDB.execSQL("DELETE ...);");
// active the update handler
progressHandler
.sendMessage(progressHandler.obtainMessage());
myDB.execSQL("DELETE ...;");
// active the update handler
progressHandler
.sendMessage(progressHandler.obtainMessage());
// Einstellung speichern
try {
settings.edit().putString("LetzteQuelle", "-1")
.commit();
} catch (Exception ex) {
settings.edit().putString("LetzteQuelle", "").commit();
}
} catch (Exception ex) {
// Wait dialog beenden
dialog.dismiss();
Log.e("Glutenfrei Viewer",
"Error in activity MAIN - remove data", ex); // log
// the
// error
}
// Wait dialog beenden
dialog.dismiss();
}
}.start();
this.onCreate(null);
}
Wiht Async Task I do it this way:
private class RunningAlternativSearch extends
AsyncTask<Integer, Integer, Void> {
final ProgressDialog dialog = new ProgressDialog(SearchResult.this) {
#Override
public boolean onSearchRequested() {
return false;
}
};
#Override
protected void onPreExecute() {
alternativeSucheBeendet = false;
String DialogTitel = getString(R.string.daten_wait_titel);
DialogText = getString(R.string.dialog_alternativ_text);
DialogZweiteChance = getString(R.string.dialog_zweite_chance);
DialogDritteChance = getString(R.string.dialog_dritte_chance);
sucheNach = getString(R.string.dialog_suche_nach);
dialog.setCancelable(true);
dialog.setTitle(DialogTitel);
dialog.setIcon(R.drawable.icon);
dialog.setMessage(DialogText);
dialog.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface arg0) {
// TODO Auto-generated method stub
cancleBarcodeWorker();
if (alternativeSucheBeendet==false){
// Activity nur beenden wenn die Suche
// nicht beendet wurde, also vom User abgebrochen
Toast toast = Toast.makeText(SearchResult.this, SearchResult.this
.getString(R.string.toast_suche_abgebrochen),
Toast.LENGTH_LONG);
toast.show();
myDB.close();
SearchResult.this.finish();
}
}
});
dialog.show();
}
...
Can you show the code for processUserAction(..)? There is no need to include the dismiss.
I did something very similar and had no problems...
Here's the code:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Export data.\nContinue?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String file = getObra().getNome();
d = new ProgressDialog(MenuActivity.this);
d.setTitle("Exporting...");
d.setMessage("please wait...");
d.setIndeterminate(true);
d.setCancelable(false);
d.show();
export(file);
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
In export(file) I open the thread:
private void export(final String file) {
new Thread() {
public void run() {
try {
ExportData ede = new ExportData(
getApplicationContext(), getPmo().getId(),
file);
ede.export();
handlerMessage("Done!!");
} catch (Exception e) {
handlerMessage(e.getMessage());
System.out.println("ERROR!!!" + e.getMessage());
}
}
}.start();
}
In handlerMessage I dismiss the progressDialog and show the final message.
Hope it helps you.
You could create a listener outside of the AlertDialog, to abstract out the logic within the OnClickListener for the positive button. That way, the listener can be notified, and the AlertDialog will be dismissed immediately. Then, whatever processing of the user's input from the AlertDialog can take place independently of the AlertDialog. I'm not sure if this is the best way to accomplish this or not, but it's worked well for me in the past.
As far as I can tell, I don't see any obvious problems with your AsyncTask code.
public interface IPasswordListener {
public void onReceivePassword(String password);
}
IPasswordListener m_passwordListener = new IPasswordListener {
#Override
public void onReceivePassword(String password) {
processUserAction(password,targetUri);
}
}
public void showPasswordDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.enterPassword);
builder.setView(textEntryView);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
m_passwordListener.onReceivePassword(pwdText.getText().toString());
dialog.dismiss();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
builder.show();
}

Application alarm causing a weird error until I press the back button

I have an alarm in my application that notifies me every 10 minutes. It works fine but each time when the alarm notifies me, my application name will show as a box in the middle of the screen, and I can't press anything until I press the back button. It's really weird!
Here is my code:
// Alert Code
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Confirmation");
alertDialog.setMessage("Are you sure you want to send this report?");
run(gotDataS);
// Timer Code
pendingIntent = PendingIntent.getService(CreateNewForm_3.this, 0,
new Intent(NewForm_3.this, MyAlarmService.class), 0);
Send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
alertDialog.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Toast.makeText(NewForm_3.this, "Sent", 0)
.show();
long firstTime = SystemClock.elapsedRealtime();
am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
firstTime + 10 * 1000, 30 * 1000, pendingIntent);
// firstTime Will be the current_time + ( 10 * 60 * 1000) =)
// 10* 1000 will be (10 * 60 * 1000)
new Handler().postDelayed(new Runnable() {
public void run() {
bCancel.performClick();
}
}, (30 * 1000));
// ( 30 * 1000) will be firstTime + ( 2- duration)
Intent toRecentCases = new Intent(CreateNewForm_3.this,
LMPActivity.class);
startActivity(toRecentCases);
}
});
alertDialog.setButton2("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// Here you can add functions
}
});
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.show();
}
});
bCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
am.cancel(pendingIntent);
}
});
//For Notification -3-
final AlertDialog alertDialog3 = new AlertDialog.Builder(this).create();
alertDialog3.setTitle("Confirmation");
alertDialog3.setMessage("Are you sure you want to quite?");
// Press cancel button it will move user to actvity p
Cancelb.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
alertDialog3.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Intent toRecentCases = new Intent(NewForm_3.this,
LMPActivity.class);
startActivity(toRecentCases);
}
});
alertDialog3.setButton2("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// Doing nothing!
}
});
alertDialog3.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog3.show();
}
});
}
This is Showing Dialog Activity
public class ShowingDialog extends Activity {
boolean b;
String CancelMsg;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//For Notification -1-
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Confirmation");
alertDialog.setMessage("Do you really want it?");
// For Notification -2-
final AlertDialog alertDialog2 = new AlertDialog.Builder(this).create();
alertDialog2.setTitle("Confirmation");
alertDialog2.setMessage("Are you sure you want it?");
alertDialog.setButton("yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent= new Intent(ShowingDialog.this,MyPage.class);
startActivity(intent);
;
}
});
alertDialog.setButton2("no",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
alertDialog2.setButton("yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Here you can add functions
// Sending a Message to server that the plaintiff found the case
// For Sending SMS with cancel Request
// Getting Case_ID + putting it inside CancelMsg
CancelMsg = "Case_ID cancel";
if (!b) {
try {
sendSMS("5556", CancelMsg);
Toast.makeText(ShowingDialog.this, "Sent", Toast.LENGTH_LONG)
.show();
} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(ShowingDialog.this, e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}
});
alertDialog2.setButton2("no", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Here you can add functions
// Do nothing
}
});
alertDialog2.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog2.show();
}
});
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.show();
}
public void sendSMS(String number, String msg) throws Exception {
if (!b) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(number, null, msg, null, null);
}
b = true;
}
}
In Manifest :
<activity
android:name=".ShowingDialog"
android:theme="#android:style/Theme.Dialog" />
It doesn't appear that you're overloading the back statement, so when you hit the back button you're traveling back up your Back Stack. The Android documentation has more information on this:
Tasks and Back Stack

Categories

Resources