I am trying to show an alert message.
But when I click the specific button to show the alert message the app stops unfortunately.
my code for alert message is here...
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Cursor res = myDB.getAllData();
if (res.getCount() == 0) {
showMessage("Error", "Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
buffer.append("EMAIL: " + res.getString(0) + "\n");
buffer.append("full_name : " + res.getString(1) + "\n");
buffer.append("district : " + res.getString(2) + "\n");
buffer.append("phone_num : " + res.getString(3) + "\n");
}
showMessage("Data", buffer.toString());
}
});
}
public void showMessage(String title, String message)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
Try this code :
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("Write your message here.");
builder1.setCancelable(true);
builder1.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder1.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
instead of
AlertDialog.Builder builder = new AlertDialog.Builder(this);
use this
AlertDialog.Builder builder = new AlertDialog.Builder(YourActivity.this); // for activity
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // for fragment
I have tested showMessage method. and it worked without no problem. I guess you must check your database connection ,cursor and buffer. However This code is for showing an alert message:
/**
* #param context
* #param title
* #param message
*
* Caution:Error--> android.view.WindowManager$BadTokenException:
* Unable to add window -- token null is not for an application
*
* --> Instead of getApplicationContext(), just use
* ActivityName.this
*/
public static AlertDialog showDialog(final Context context, String title,
String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(true);
builder.setMessage(message);
builder.setTitle(title);
builder.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder.show();
}
public static void showAlert(final Activity activity, String title,
String message, final boolean finish) {
new AlertDialog.Builder(activity).setTitle(title).setMessage(message)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
if (finish) {
activity.finish();
}
}
}).show();
}
Related
I am taking input from user in the edittext. Now I want to show the desired output in the other text box, but if user inputs wrong values, a dialog box should open mentioning all the incorrect values...box is opening again and again till it detects all the incorrect values. eg-if i add three wrong values in the edit box it is opening box for 3 times.
String s=editText1.getText().toString();
String z[]=s.split("\\s");
editText2.setText("");
String a = "";
String b = " Not valid";
for(int i=0;i<z.length;i++)
{
int j=Integer.parseInt(z[i]);
if(j>=65 && j<=97)
{
editText2.setText(editText2.getText() + "" + String.valueOf((char) j));
}
else {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
a += z[i]+"\t";
alertDialogBuilder.setTitle("Error");
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setMessage(a+b)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
boolean is_open_dialog=false;
for(int i=0;i<z.length;i++)
{
int j=Integer.parseInt(z[i]);
if(j>=65 && j<=97)
{
editText2.setText(editText2.getText() + "" + String.valueOf((char) j));
}
else {
is_open_dialog = true;
a += z[i]+"\t";
}
}
if(is_open_dialog){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Error");
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setMessage(a+b)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
I want when user click on Uninstall Button,there prompt a password dialog. This Dialog is coming only one time.I'm using this code:
public void run() {
Looper.prepare();
while (!exit) {
// get the info from the currently running task
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(MAX_PRIORITY);
String activityName = taskInfo.get(0).topActivity.getClassName();
Log.d("topActivity", "CURRENT Activity ::" + activityName);
if (activityName.equals("com.android.packageinstaller.UninstallerActivity")) {
//Toast.makeText(context, "Uninstall Clicked", Toast.LENGTH_LONG).show();
Intent startIntent = new Intent(this.context, Alert_Dialog.class);
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.context.startActivity(startIntent);
exit = true;
} else if (activityName.equals("com.android.settings.ManageApplications")) {
Toast.makeText(this.context, "Back", Toast.LENGTH_LONG).show();
exit = true;
}
}
Looper.loop();
}//Run
I want whenever user click on Unistall Prompt should come , below is the code in onClick,
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView.findViewById(R.id.edit_text);
alertDialogBuilder
.setCancelable(false)
.setNegativeButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
/** DO THE METHOD HERE WHEN PROCEED IS CLICKED*/
String user_text = (userInput.getText()).toString();
/** CHECK FOR USER'S INPUT **/
if (user_text.equals("abc"))
{
Log.d(user_text, "HELLO THIS IS THE MESSAGE CAUGHT :)");
Toast.makeText(myContext,"PAssword Correct",Toast.LENGTH_LONG).show();
Alert_Dialog.this.finish();
//Search_Tips(user_text);
}
else{
Log.d(user_text,"string is empty");
String message = "The password you have entered is incorrect." + " \n \n" + "Please try again!";
AlertDialog.Builder builder = new AlertDialog.Builder(myContext);
builder.setTitle("Error");
builder.setMessage(message);
builder.setPositiveButton("Cancel", null);
builder.create().show();
Alert_Dialog.this.finish();
}
}
});
// .setPositiveButton("Cancel",
// new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog,int id) {
// Alert_Dialog.this.finish();
//
// }
//
// }
// );
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
Once the dialog calls dismiss(), the view you set for the dialog also would be destroyed.
In your case, this line set the view,
alertDialogBuilder.setView(promptsView);
But when the dialog is closed, the view promptsView is destroyed,
The promptsView should be re-created once again you use it.
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
promptsView = new PromptsView();//new or inflate the view
//....
alertDialogBuilder.setView(promptsView);
I am having a dialog which must execute some code on canceled. I set a negative button but its not executing when dialog is canceled from back button.
here is my code.
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Licence expired");
builder.setCancelable(false);
builder.setMessage("Your licence for " + url
+ " has been expired, Please renew it or select another server");
builder.setPositiveButton("Renew now",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Open url in webview
Intent intent = new Intent(MainActivity.this,
WebActivity.class);
intent.putExtra("ServerDomain", url);
startActivity(intent);
/*
* URL domain; try { domain = new URL(url);
* intent.putExtra("ServerDomain", domain.getHost());
* startActivity(intent); } catch (MalformedURLException
* e) { e.printStackTrace(); }
*/
/*
* String url = "http://www.google.com"; Intent i = new
* Intent(Intent.ACTION_VIEW);
* i.setData(Uri.parse(url)); startActivity(i);
*/
}
});
builder.setNegativeButton("Switch Server",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
showServerList();
}
});
builder.create().show();
Create a cancel listner for dialog.
builder.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
showServerList();
}
});
In my android app, I'm producing a lot of data which I store at the moment in a .txt file simply called "logData". Now my boss wants me to give him the possibility to save it as an extra file, like the Save As Button in various windows programms.
At the moment I have a method for generating a logFile and write first data to it and one for writing all coming data to it. But how can I implement a "Save as" functionality?
Here the code of both methods and the used variables:
private String logData = "logData.txt";
private String logText = "";
private File extStorageDir = Environment.getExternalStorageDirectory();
private File mLogFile = new File(extStorageDir, "DCULogData/logData.txt");
generating:
public void generateLogFileOnSD(String sFilename, String sBody) {
try {
File logFile = new File(extStorageDir, sFilename);
FileWriter writer = new FileWriter(logFile);
writer.append(sBody);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
writing:
public void writeLogFileOnSD(String sFilename, String sBody) {
if (mLogFile.exists()) {
try {
FileOutputStream fOut = new FileOutputStream(mLogFile);
OutputStreamWriter mOutWriter = new OutputStreamWriter(fOut);
mOutWriter.append(sBody);
mOutWriter.close();
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
generateLogFileOnSD(logData, logText);
}
}
EDIT : This is my solution based on Simple Plan's answer. Thanks for this!
I also tested some scenarios with filenames like "/blabla", "m/m/m/m/m/". No failure found until now :)
public Button.OnClickListener saveLogFileOnClickListener = new Button.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(
DiagnosisActivity.this);
builder.setTitle(R.string.save_file_dialog);
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
final EditText input = new EditText(
DiagnosisActivity.this);
input.setSingleLine();
AlertDialog.Builder ad = new Builder(
DiagnosisActivity.this);
ad.setTitle("Enter save as File Name");
ad.setView(input);
ad.setCancelable(true);
ad.setPositiveButton("Save as",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
int len = input.length();
if (len != 0) {
final_filename = input
.getText().toString()
.trim();
generateLogFileOnSD(
"DCULogData/"
+ final_filename
+ ".txt",
ReceiverThread
.getLogText());
Toast.makeText(
getApplicationContext(),
"Saved!",
Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(
getApplicationContext(),
"Enter a proper name",
Toast.LENGTH_LONG)
.show();
}
}
});
ad.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
dialog.cancel();
}
});
AlertDialog alert = ad.create();
alert.show();
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert1 = builder.create();
alert1.show();
}
};
First add Button into your Layout as a text Save as and implement OnClickListner()
String final_filename;
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
annual_crop.setTextColor(Color.BLUE);
AlertDialog.Builder al1 = new Builder(youractivity);
al1.setMessage("Do you want to save a file?");
al1.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
final EditText input = new EditText(
youractivity.this);
input.setSingleLine();
AlertDialog.Builder al = new Builder(
AgriListView.this);
al.setTitle("Enter save as File Name");
al.setView(input);
al.setCancelable(true);
al.setIcon(R.drawable.bt);
al.setPositiveButton(
"Save as",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
int len = input
.length();
if (!(len == 0)) {
final_filename=input.getText().toString.trim();
);
} else {
Toast.makeText(
getApplicationContext(),
"Enter Name Properly",
Toast.LENGTH_LONG)
.show();
}
}
});
al.setNegativeButton(
"Cancel",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
dialog.cancel();
}
});
AlertDialog alert = al.create();
alert.show();
}
});
al1.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
dialog.cancel();
}
});
AlertDialog alert1 = al1.create();
alert1.show();
}
});
}
});
And used final_filename like below:
File folder = new File(Environment.getExternalStorageDirectory(), "DCULogData");
File mLogFile = new File(folder.getPath(), final_filename);
And add permission in your manifest.xml file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
How come the AlertDialog that has the title "Location was saved to file" doesn't show up? It is the one that should be displayed after the user presses Okay on the first dialog.
I think it has something to do with threads, but I'm not sure.
SimpleDateFormat timeStampFormat = new SimpleDateFormat("MMMMM-dd-yyyy");
final EditText input = new EditText(EncounterActivity.this);
input.setWidth(75);
input.setText("Bear-Encounter-GPS-" + timeStampFormat.format(new Date()) + ".txt");
new AlertDialog.Builder(EncounterActivity.this)
.setTitle("Save GPS Location")
.setMessage("Please enter a filename")
.setView(input)
.setIcon(R.drawable.gps)
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()){
File fn = new File(root, input.getText().toString());
FileWriter gpxwriter = new FileWriter(fn);
BufferedWriter out = new BufferedWriter(gpxwriter);
out.write(ll.toUTMRef().toString());
out.close();
AlertDialog.Builder builder = new AlertDialog.Builder(EncounterActivity.this);
builder.setIcon(R.drawable.gps);
builder.setTitle("Location was saved to file");
builder.setMessage("Your GPS coordinates were saved to " + fn.getAbsolutePath())
.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
} catch (IOException e) {
//ProfitBandit.alert(Shipment.this, "Couldn't write the file.");
Log.v("IOException", "Could not write file " + e.getMessage());
}
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do nothing.
}
}).show();
You CAN display an alert dialog from an alert dialog if you use the pattern showDialog(int) getInstanceSomeDialog and onCreateDialog(int) for both dialogs. So in my aboutAlertDialog I have:
builder.setPositiveButton("View EULA", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { //cancels itself?
showDialog(DIALOG_EULA_SHOW);
}
});
which in turn displays an EULA in yet another AlertDialog. OR you could just toss up a Toast as in:
Toast.makeText(Main.this,"Location Saved.", Toast.LENGTH_SHORT).show();
where Main is the activity class.