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();
Related
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()
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();
i made an EditText that displayed value with multiple line like this...
i want to keep that value in a SQLite database. this is the code i use:
export.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final View export_layout = getLayoutInflater().inflate(R.layout.export_layout, null);
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setView(export_layout);
builder.setTitle("Input new DB");
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
editText1 = (EditText) export_layout.findViewById(R.id.editText1);
String table = editText1.getText().toString();
String val = textStatus.getText().toString();
db.execSQL("create table "+table+"(ANY text)");
db.execSQL("insert into "+table+" values('"+val+"')");
}
});
builder.setNegativeButton("back",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
TextStatus is an EditText where the value is displayed like the image above. editText1 is where the user input the table name.
the problem is when i save the value, the whole value is inserted into one cell. i want the value to be separated per line then inserted into a single cell for each line.
is there any way to do that?
edit:
this is how i set the text in TextStatus:
x = new BroadcastReceiver()
{
#Override
public void onReceive(Context c, Intent intent)
{
results = wifi.getScanResults();
size = results.size();
if (size > 0) {
for (int i=0; i<size; i++){
ScanResult scanresult = wifi.getScanResults().get(i);
String ssid = scanresult.SSID;
int rssi = scanresult.level;
String bssid = scanresult.BSSID;
String rssiString = String.valueOf(rssi);
textStatus.append(ssid + "," + bssid + "," + rssiString + "\n");
}
unregisterReceiver(x); //stops the continuous scan
textStatus.append("------------"+j+"\n");
j++;
}
}
};
Try Scanner:
Scanner scanner = new Scanner(val);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
//Insert the line here
}
Update: This is how it should looks like in your codes
editText1 = (EditText) export_layout.findViewById(R.id.editText1);
String table = editText1.getText().toString();
String val = textStatus.getText().toString();
db.execSQL("create table "+table+"(ANY text)");
Scanner scanner = new Scanner(val);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
db.execSQL("insert into "+table+" values('"+line+"')");
}
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....
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();
}
}