Android: Passing a variable outside from AlertDialog onClick - android

I want to pass a variable to an outer function when user clicks on "OK" in AlertDialog.
I'm trying this for example but it won't recognize the Variable (Yup).
public final void deleteBookmark(Cursor cur, int pos) {
//fetching info
((Cursor) cur).moveToPosition(pos);
String bookmark_id = ((Cursor) cur).getString(((Cursor) cur).getColumnIndex(Browser.BookmarkColumns._ID));
String bookmark_title = ((Cursor) cur).getString(((Cursor) cur).getColumnIndex(Browser.BookmarkColumns.TITLE));
//asking user to approve delete request
AlertDialog alertDialog = new AlertDialog.Builder(Dmarks.this).create();
alertDialog.setTitle("Delete" + " " + bookmark_title);
alertDialog.setIcon(R.drawable.icon);
alertDialog.setMessage("Are you sure you want to delete this Bookmark?");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
**String Yup = "yes";**
} });
alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Context context = getApplicationContext();
Toast.makeText(context, "canceled" , Toast.LENGTH_SHORT).show();
} });
alertDialog.show();
**if (Yup == "yes")** {
//deleting if user approved
getContentResolver().delete(Browser.BOOKMARKS_URI, "_id = " + bookmark_id, null);
//notifying user for deletion
Context context = getApplicationContext();
Toast.makeText(context, bookmark_title + " " + "deleted" , Toast.LENGTH_SHORT).show();
}
}
I know the code is a bit messed up but it's only for the sake of understanding.
Appreciate the help!

Yup is not being recognized because you create the string in the onClick method, and it gets recycled when onClick is done.
I recommend just getting rid of Yup, because even if you fix this, you'll have problems. The dialog will pop up, but by the time the user selects, the application will already have gone through the if statement, so Yup never has a chance to equal "Yes". In other words, the dialog box doesn't pause your code and wait for the user input before going through "if (Yup == "yes"). Also, the if statement should look like this: if (Yup.equals("yes")), otherwise, it will return false everytime.
I would make your code look like this:
public final void deleteBookmark(Cursor cur, int pos) {
//fetching info
((Cursor) cur).moveToPosition(pos);
final String bookmark_id = ((Cursor) cur).getString(((Cursor) cur).getColumnIndex(Browser.BookmarkColumns._ID));
final String bookmark_title = ((Cursor) cur).getString(((Cursor) cur).getColumnIndex(Browser.BookmarkColumns.TITLE));
//asking user to approve delete request
AlertDialog alertDialog = new AlertDialog.Builder(Dmarks.this).create();
alertDialog.setTitle("Delete" + " " + bookmark_title);
alertDialog.setIcon(R.drawable.icon);
alertDialog.setMessage("Are you sure you want to delete this Bookmark?");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//deleting if user approved
getContentResolver().delete(Browser.BOOKMARKS_URI, "_id = " + bookmark_id, null);
//notifying user for deletion
Context context = getApplicationContext();
Toast.makeText(context, bookmark_title + " " + "deleted" , Toast.LENGTH_SHORT).show();
} });
alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Context context = getApplicationContext();
Toast.makeText(context, "canceled" , Toast.LENGTH_SHORT).show();
} });
alertDialog.show();
}
}

Related

AlertDialog not loading

I have a ListView and i have put an onClickListener to it. When i click it, it is supposed to run an AlertDialog but it does not seem to work. The AlertDialog is supposed to display a few strings which are in the ListView. here is the code I am using.
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
PopUpAlert(id);
}
});
private void PopUpAlert(final long id) {
Cursor cursor = dbHelper.getAllReviewRows(id);
if (cursor.moveToFirst()) {
//Preparing variables to use in message from Establishment record in Database
final String SName = cursor.getString(dbHelper.COL_REV_STATION_NAME);
String Date = cursor.getString(SQL.COL_DATE);
String SFacility = cursor.getString(SQL.COL_REV_FACILITY);
String Rating = cursor.getString(SQL.COL_RATING);
String Comment = cursor.getString(SQL.COL_COMMENTS);
// building a drill down information message and displaying it in an Alert Dialog
new AlertDialog.Builder(this)
.setTitle("Facilities Review App")
.setMessage("You Selected:\n"
+ "Station Name: " + SName + "\n" + "Date: " + Date
+ "\n" + "Facility: " + SFacility + "\n" + "Rating: " + Rating
+ "\n" + "Comment: " + Comment)
.setPositiveButton("Add Image", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// calling method to add a review for that particular establishment
addImage(SName);
}
})
.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// calling method to delete that particular establishment
}
});
}
}
you didn't call show() on your AlertDialog:
new AlertDialog.Builder(this)
.setTitle("Facilities Review App")
.setMessage("...")
.setPositiveButton(..)
.setNegativeButton(..)
.show();
Here you can find the documentation for AlertDialog.Builder.show()

Update Listview after deleting database item

Ive been trying to get my listview to update after removing an item. Here's what I have so far:
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
String str = null;
public void onItemClick(AdapterView<?> arg0, final View view, int arg2, long arg3) {
//TextView txtview = (TextView)view.findViewById(R.id.txtview);
final String item = ((TextView) view.findViewById(R.id.txtview)).getText().toString();
str = item;
final long arr = arg3;
final String arg22 = longToString(arg3);
//Creating an Alert Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(Home.this);
builder.setMessage("Are you sure you want to delete the hike " + str + " ?");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SQLiteDatabase db1=openOrCreateDatabase("hikeManager", MODE_PRIVATE, null);
DatabaseHandler db = new DatabaseHandler(Home.this);
String table = "hikes";
Cursor c = db1.rawQuery("select id from "+ table + " where name='"+item+"'", null);
int dhike = c.getColumnIndex("name") + 1;
try {
Hike hike = db.getHike(arr + 1);
db.deleteHike(hike);
Log.d("DLT", "Deleted hike at index " + arr);
//db.updateList(adapter, myList, listItems);
adapter.remove(arg22);
adapter.notifyDataSetChanged();
//updateData();
db.close();
} catch (CursorIndexOutOfBoundsException e) {
Log.d("DLT", "Failed to delete: " + e.getMessage());
db.close();
}
//db.updateList(adapter, myList, listItems);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
I Have quite a bit of unused code in there, as I have tried a few different methods to get this to work, but have failed so far. Here is updateData:
private void updateData() {
// Get all of the notes from the database and create the item list
DatabaseHandler db = new DatabaseHandler(this);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.txtview, listItems);
final ListView myList = (ListView) findViewById(R.id.cardListView);
int num = db.getHikesCount();
for (int i=1; i<num+1; ++i){
Hike name = db.getHike(i);
String nam = name.getName();
listItems.add(nam);
}
myList.setAdapter(adapter);
db.close();
}
The updateData does have some unintended consequences when I use it to update the view after adding an item to a non-empty list, but it works for now. The item is successfully deleted, since I can close the app and reload it and the item will be gone. I just cant seem to get it to update properly for me.
Just use
adapter.notifyDataSetChanged();

Alert Dialogue box in android

In my code i want to close alert dialog immediately and start activities, when i select options mentioned in if- elseIf statements. I do not want ok and cancel buttons . My code work fine (statements inside if statements work but alert dialogue still there ). Thanks for help
final AlertDialog.Builder builder =
new AlertDialog.Builder(arg0.getContext());
builder.setTitle("Favourities Management");
// TODO Auto-generated method stub
int selected = 0;
builder.setSingleChoiceItems(values, selected, new DialogInterface.OnClickListener() {
#
Override
public void onClick(DialogInterface dialog, int which) {
if (values[which] == "Select Benificiary") {
Intent registerUser = new Intent(FinalUtilityBillPayment.this, ListViewBeneficiaryBillPayment.class);
FinalUtilityBillPayment.this.startActivity(registerUser);
startActivityForResult(registerUser, 1);
} else if (values[which] == "Add Benificiary") {
try {
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
mydb.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE + " (ID INTEGER PRIMARY KEY, ReferenceNo TEXT, Mobile Text);");
mydb.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error in creating table", Toast.LENGTH_LONG).show();
}
try {
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
mydb.execSQL("INSERT INTO " + TABLE + "(ReferenceNo, Mobile) VALUES('" + ref.getText().toString() + "','" + mob.getText().toString() + "')");
mydb.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error in inserting into table", Toast.LENGTH_LONG).show();
}
} else if (values[which] == "Delete Benificiary") {
Intent registerUser = new Intent(FinalUtilityBillPayment.this, ListViewDeleteBeneficiaryBillPayment.class);
//startActivityForResult(registerUser, 1);
FinalUtilityBillPayment.this.startActivity(registerUser);
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
My sugestion is;
final AlertDialog.Builder builder = new AlertDialog.Builder(arg0.getContext());
builder.setTitle("Favourities Management");
// TODO Auto-generated method stub
int selected = 0;
builder.setSingleChoiceItems(values,
selected,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(values[which]=="Select Benificiary"){
selectBenificiary();
//see more about "dialog.dismiss()" in http://developer.android.com/reference/android/app/Dialog.html#dismiss()
dialog.dismiss();
} else if (values[which]=="Add Benificiary"){
addBenificiary();
//see more about "dialog.dismiss()" in http://developer.android.com/reference/android/app/Dialog.html#dismiss()
dialog.dismiss();
} else if (values[which]=="Delete Benificiary"){
deleteBenificiary();
//see more about "dialog.dismiss()" in http://developer.android.com/reference/android/app/Dialog.html#dismiss()
dialog.dismiss();
}
}
});
AlertDialog alert = builder.create();
alert.show();
//Add parameter case necessary
public void selectBenificiary(){
Intent registerUser = new Intent(FinalUtilityBillPayment.this,ListViewBeneficiaryBillPayment.class);
// FinalUtilityBillPayment.this.startActivity(registerUser);
startActivityForResult(registerUser, 1);
}
//Add parameter case necessary
public void addBenificiary(){
try{
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
mydb.execSQL("CREATE TABLE IF NOT EXISTS "+ TABLE +" (ID INTEGER PRIMARY KEY, ReferenceNo TEXT, Mobile Text);");
mydb.close();
}catch(Exception e){
Toast.makeText(getApplicationContext(), "Error in creating table", Toast.LENGTH_LONG).show();
}
try{
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
mydb.execSQL("INSERT INTO " + TABLE + "(ReferenceNo, Mobile) VALUES('"+ref.getText().toString() +"','"+ mob.getText().toString() +"')");
mydb.close();
}catch(Exception e){
Toast.makeText(getApplicationContext(), "Error in inserting into table", Toast.LENGTH_LONG).show();
}
}
//Add parameter case necessary
public void deleteBenificiary(){
Intent registerUser = new Intent(FinalUtilityBillPayment.this, ListViewDeleteBeneficiaryBillPayment.class);
//startActivityForResult(registerUser, 1);
FinalUtilityBillPayment.this.startActivity(registerUser);
}
Try this... in that onClick() you can see the DialogInterface dialog that dialog name.
use this dialog.cancel(); before calling the other activity
dialog.cancel();
Intent registerUser = new Intent(FinalUtilityBillPayment.this,ListViewBeneficiaryBillPayment.class);
//FinalUtilityBillPayment.this.startActivity(registerUser);
startActivityForResult(registerUser, 1);
call .dismiss() for closiong it, also use simple Dialog to get the possibility of setting custom layout for it
Dialog alert = new Dialog(context);
alert.setContentView(layoutResID);
You have to dismiss the alert dialogue. Try this:
Dialogue.dismiss();

Delete From sqlite not working

Hello I’m making a budget application that will allow you to look at expeances entered and if need be delete them I can call the method run thro it and it wont have a issue but when I check to see if it worked it hasnt I’ve tried but cant figure out why this doesn’t work. I use a alert dialog to confirm that they want to delete.
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
this);
// set title
alertDialogBuilder.setTitle("DELETE "+position);
// set dialog message
alertDialogBuilder
.setMessage("Are you sure you whant to delete Expeance "+position)
.setCancelable(false)
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
String[] po = position.split(" ");
String date = po[0];
date = date +".tar.gz";
entry.open();
entry.deleteByDate(date);
entry.close();
recreate();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
and here is the code for the method
public SQLiteDatabase deleteByDate(String date2)
{
// TODO Auto-generated method stub
ourDatabase.delete(DATABASE_TABLE2, KEY_DATE + " =?", new String[] { date2 });
ourDatabase.delete(DATABASE_TABLE4, KEY_DATE + " =?", new String[] { date2 });
return ourDatabase;
}
use Pattern.compile for replacing "/" with "-" as instead of date.replace("/", "_"):
Pattern p = Pattern.compile("/");
String date = po[0];
Matcher matcher = p.matcher(date);
date = matcher.replaceAll("_");
date = date +".tar.gz";
//your code here....

How to display an alertdialog on top of other alertdialog? And when one in foreground is closed, then the one in background should be visible

This is my code to edit/update which I am doing throgh a custom alertdialog which contains the data fetched frm database. Now when the inputs provided are incorrect I want to show other alertdialog on top of this providing some message to user. When the user dismisses this message alertdialog, the previous one which is used for update should be visible. How can I do that?
public class CountryEdit extends ListActivity{
private Long mRowId;
private CountryDbAdapter mDbHelper;
public static final String PROVIDER_NAME = "assignment2.demos.MyCountriesCP";
public static final String uriString = "content://"+ PROVIDER_NAME +"/countries";
public static final Uri CONTENT_URI = Uri.parse(uriString);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ContentResolver contentResolver = getContentResolver();
Cursor c = contentResolver.query(CONTENT_URI, null, null, null, getIntent().getExtras().getString("SORT_ORDER"));
String[] from = new String[] { "year", "country" };
int[] to = new int[] { R.id.year, R.id.country };
SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.country_row,
c, from, to);
setListAdapter(sca);
mRowId = savedInstanceState != null ? savedInstanceState.getLong(assignment2.demos.MyCountriesActivity.KEY_ROWID)
: null;
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(assignment2.demos.MyCountriesActivity.KEY_ROWID)
: null;
}
populateFields();
}
private void populateFields() {
LayoutInflater inflater=LayoutInflater.from(this);
final View addView=inflater.inflate(R.layout.add_country, null);
Cursor c = getContentResolver().query(CONTENT_URI.buildUpon().
appendPath(String.valueOf(mRowId)).build(), null, null, null, null);
/* Read alert input */
final EditText editCountry =(EditText)addView.findViewById(R.id.editCountry);
final EditText editYear =(EditText)addView.findViewById(R.id.editYear);
editCountry.setText(c.getString(c.getColumnIndex("country")));
editYear.setText(c.getString(c.getColumnIndex("year")));
new AlertDialog.Builder(this)
.setTitle("Edit country/year")
.setView(addView)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int whichButton) {
String country = editCountry.getText().toString();
if(country.trim().length()>0 && editYear.getText().toString().trim().length()>0){
int year = Integer.parseInt(editYear.getText().toString());
ContentValues updateValues = new ContentValues();
updateValues.put(mDbHelper.COUNTRY, country);
updateValues.put(mDbHelper.YEAR, year);
getContentResolver().update(
CONTENT_URI.buildUpon().appendPath(String.valueOf(mRowId)).build(), updateValues, null, null);
finish();
}
else{
new AlertDialog.Builder(CountryEdit.this)
.setTitle("Invalid Inputs!")
.setMessage("You need to enter Country AND Year.")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
finish();
}
}).show();
// Toast.makeText(CountryEdit.this,
// "You need to enter Country AND Year.", Toast.LENGTH_LONG).show();
//finish();
}
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int whichButton) {
// ignore, just dismiss
finish();
}
})
.show();
}
}
The first alert dialog is dismissing itself when the second is about to show (when the click listener finishes). You can't avoid that.
There's a dirty hack where you can override the click listener created by the builder like this:
create().getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener( ... }
But I don't recommend to do that if you don't know what you're doing (it might break the internet ;-).
You would have to dismiss the dialog yourself. If you don't do that it will never close, the user will see it forever and would have to kill your app to get it started again.

Categories

Resources