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()
Related
I want to display an alertDialog inside an OnClickListener. But the alertDialog is not showing up when I use the following code inside the onclickListener.
Any help would be great.
final AlertDialog alertDialog = new AlertDialog.Builder(MyClass.this).create();
alertDialog.setTitle("Info:");
String alert1 = "First Name: " + Fname;
String alert2 = "Surname: " + Sname;
String alert3 = "Id: " + tId;
String alert4 = "Password: " + tPassword;
alertDialog.setMessage(alert1 +"\n"+ alert2 +"\n"+ alert3+"\n" + alert4);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivity(intent);
}
});
alertDialog.show();
}});
add the below code inside the onclicklistner :
AlertDialog.Builder dialog1 = new AlertDialog.Builder(this);
dialog1.setTitle("Info:");
String alert1 = "First Name: " + Fname;
String alert2 = "Surname: " + Sname;
String alert3 = "Id: " + tId;
String alert4 = "Password: " + tPassword;
dialog1.setMessage(alert1 + "\n" + alert2 + "\n" + alert3 + "\n" + alert4);
dialog1.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivity(intent);
}
});
dialog1.show();
Use this it will work
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("ALERTTILESTRING")
.setMessage("alertNameString")
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AppCompatAlertDialogStyle);
builder.setTitle("");
builder.setMessage("");
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do stuff
}
});
builder.setNegativeButton("CLOSE", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
//do stuff
}
});
builder.show();
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();
The app i'm making displays user input before saving it. One of the spinners gets data from a database. When i press the "review" button my app crashes (something about a NullPointException) on this line
final String estStatus = estType[row];
Here is the code.
private void displayReviewDetails() {
// Get what the user entered
Spinner estSpinner = (Spinner) findViewById (R.id.est_spinner);
Spinner spinner = (Spinner) findViewById (R.id.ratingSpinner);
EditText mealCost = (EditText) findViewById (R.id.editTextMealCost);
EditText mealType = (EditText) findViewById (R.id.editTextMealType);
EditText comments = (EditText) findViewById (R.id.editTextComments);
DatePicker rDate = (DatePicker) findViewById (R.id.datePicker1);
// final so we can reference them in the anonymous inner class below
int row = estSpinner.getSelectedItemPosition();
final String estStatus = estType[row];
int row1 = spinner.getSelectedItemPosition();
final String ratingStatus = estRating[row1];
final String strMealCost = mealCost.getText().toString();
final String strMealType = mealType.getText().toString();
final String strComments = comments.getText().toString();
final String rateDate = rDate.getDayOfMonth() + "/"
+ (rDate.getMonth() + 1) + "/" + rDate.getYear();
// Create and display the Alert dialog
new AlertDialog.Builder(this)
.setTitle("Details entered")
.setMessage(
"\n " + estStatus +
"\n " + ratingStatus +
"\n " + strMealCost +
"\n " + strMealType +
"\n " + strComments +
"\n " + rateDate )
.setNeutralButton("Back",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing - it will just close when clicked
}
})
.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// save the details entered if "Save" button clicked
saveReviews(estStatus, ratingStatus, strMealCost, strMealType,
strComments, rateDate);
}
}).show();
You can also use getSelectedItem().toString();
I have have checked every problem here in relation to my own. The codes are totally different in the one I'm using IMHO. I have coded everything up to this point. I've read that in deleting the data in the database is just by passing the position, the problem is the auto-generated id in the database is not the same with the position being passed. All I'm trying to achieve is after deleting the item in list view, the item in the database will also be deleted.
The code from database in getting all the data:
public ArrayList<String> getData() {
String[] columns = new String[] { KEY_ID, KEY_CLIENT_NAME,
KEY_PRODUCT_NAME, KEY_SUPPLIER_PRICE, KEY_BS_PRICE, KEY_QTY,
KEY_TOTAL_AMOUNT };
Cursor c = sql.query(DB_TABLE, columns, null, null, null, null, null);
ArrayList<String> result = new ArrayList<String>();
int id = c.getColumnIndex(KEY_ID);
int cName = c.getColumnIndex(KEY_CLIENT_NAME);
int pName = c.getColumnIndex(KEY_PRODUCT_NAME);
int suppPrice = c.getColumnIndex(KEY_SUPPLIER_PRICE);
int bsPrice = c.getColumnIndex(KEY_BS_PRICE);
int qty = c.getColumnIndex(KEY_QTY);
int totalAmount = c.getColumnIndex(KEY_TOTAL_AMOUNT);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result.add("ID: " + c.getInt(id) + "\n" + "CLIENT NAME: "
+ c.getString(cName) + "\n" + "PRODUCT NAME: "
+ c.getString(pName) + "\n" + "SUPPLIER PRICE: "
+ c.getString(suppPrice) + "\n" + "RETAIL PRICE: "
+ c.getString(bsPrice) + "\n" + "QUANTITIY: "
+ c.getString(qty) + "\n" + "TOTAL: "
+ c.getString(totalAmount) + "\n");
}
return result;
}
The code in retrieving the data:
sql = new SQLDatabase(this);
sql.open();
ArrayList<String> data = sql.getData();
sql.close();
The code the the deletion should be executed:
protected void onListItemClick(View view, int position, long id) {
Log.i("TAG", "onListItemClick id=" + position + id);
AlertDialog.Builder builder = new AlertDialog.Builder( Delete.this);
builder.setMessage("WHAT DO YOU WANT TO DO?");
builder.setNegativeButton("DELETE", new
DialogInterface.OnClickListener() {
#Override public void onClick(DialogInterface dialog, int which) { }
// DELETE CODE HERE
});
builder.setNeutralButton("CANCEL", new
DialogInterface.OnClickListener() {
#Override public void onClick(DialogInterface dialog, int which) { }
// DO NOTHING
});
builder.setCancelable(false); AlertDialog alertdialog =
builder.create(); alertdialog.show();
}
Add Tag to the column you inserted and use same tag value while delete operation in both list and DB.
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();
}
}