EditText dialog input always null (Android) - android

The following code runs in the onClick method for a button and brings up a dialog box. I can enter text and press ok but my String filename, as shown in the Log.d, is always null. I do not understand why.
How do I get the text inputted in the dialog box to save?
My code runs in an activity(no fragment) and String filename and EditText input are both class member variables.
// Get filename from user
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Enter filename");
// EditText to get user input
this.input = new EditText(this);
dialog.setView(input);
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
filename = input.getText().toString();
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// cancelled
}
});
dialog.show();
Log.d(LOG_TAG, "Filename is : " + filename);
I based the code on android prompt user's input using a dialog but my issue is different.

you try to Log the string before you actually input data into it.
try to put the log inside the positive onClick and I think you will see that it does save.
like so:
// Get filename from user
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Enter filename");
// EditText to get user input
this.input = new EditText(this);
dialog.setView(input);
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
filename = input.getText().toString();
Log.d(LOG_TAG, "Filename is : " + filename);
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// cancelled
}
});
dialog.show();

Related

how to show only the incorrect values in the dialogue box one time only

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

How to "Save as" via Button programmatically

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 to show sequential dialog popups?

I'm having some trouble with displaying multiple popups. Right now I have an AlertDialog that pops up with an EditView for the user to put in the name of the file they want to make, which I would then pass into a File object and then a Writer and a new Dialog is supposed to pop up asking the user if they want to launch the music player.
However, as things are now, after I press 'Ok' on the first AlertDialog, absolutely nothing happens. I'm not sure what I'm doing wrong. Any help? Here is my code.
//naming the playlist
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Exporting Playlist");
alert.setMessage("Enter the name of the playlist!");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
name = input.getText().toString() + ".m3u";
popup = true;
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
//after the playlist is named, put songs into file
if (popup){
popup = false;
final File list = new File(mp3folderPath + name);
FileWriter writer;
BufferedWriter write;
ArrayList<String> playlist = new ArrayList<String>();
Log.d("poo", "mAdapter count: "+mAdapter.getCount());
for (int i=0; i < mAdapter.getCount(); i++) {
playlist.add(mAdapter.getItem(i));
}
Log.d("poo", playlist.toString());
//write the songs to the m3u playlist
writer = new FileWriter(list);
write = new BufferedWriter(writer);
for (int i = 0; i<playlist.size(); i++){
String[] name = playlist.get(i).split(" : ");
Log.d("poo", name[0]);
write.append(name[0]+"\n");
}
write.close();
//popup window
CharSequence choices[] = new CharSequence[] {"Launch Music Player", "Quit"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Exported playlist!");
builder.setItems(choices, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
Intent intent = new Intent(MediaStore.INTENT_ACTION_MUSIC_PLAYER);
startActivity(intent);
finish();
}
else {
finish();
}
}
});
builder.show();
}
}
To show sequential popup, the conditions and code for consecutive popup(s) would have to be reachable from one to the other.
AlertDialog1 has to contain the code which would show AlertDialog2...
Try something like this:
//naming the playlist
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Exporting Playlist");
alert.setMessage("Enter the name of the playlist!");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//check if the name is not null
name = input.getText().toString() + ".m3u";
//Now instead of popup = true;
//call func to name the playlist and next dialog
callNextDialog();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
//after the playlist is named, put songs into file
// if (popup){
// popup = false;
// }
public void callNextDialog(){
final File list = new File(mp3folderPath + name);
FileWriter writer;
BufferedWriter write;
ArrayList<String> playlist = new ArrayList<String>();
Log.d("poo", "mAdapter count: "+mAdapter.getCount());
for (int i=0; i < mAdapter.getCount(); i++) {
playlist.add(mAdapter.getItem(i));
}
Log.d("poo", playlist.toString());
//write the songs to the m3u playlist
writer = new FileWriter(list);
write = new BufferedWriter(writer);
for (int i = 0; i<playlist.size(); i++){
String[] name = playlist.get(i).split(" : ");
Log.d("poo", name[0]);
write.append(name[0]+"\n");
write.close();
//popup window
CharSequence choices[] = new CharSequence[] {"Launch Music Player", "Quit"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Exported playlist!");
builder.setItems(choices, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
Intent intent = new Intent(MediaStore.INTENT_ACTION_MUSIC_PLAYER);
startActivity(intent);
finish();
}
else {
finish();
}
}
});
builder.show();
}
}
AlertDialog.show() doesn't wait for the dialog to go away. It returns immediately. That means ALL of the logic of what to do after the user makes a choice has to go in the onClick function of the dialog's positive button.
Basically, everything in your if(popup) code needs to be in the onClick handler

AlertDialog having input field does not show copy for selection

I am showing a file rename dialog with existing name pre-filled in the EditText.
I want to show "Copy Text" option which is not being shown by default when text portion in selected. Please suggest
following is my existing code.
final EditText input = new EditText(this);
input.setText(file.getName());
input.setTextIsSelectable(true);
new AlertDialog.Builder(context)
.setTitle("Edit File Name")
.setView(input)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
String newName = input.getText().toString();
String oldPath = file.getAbsolutePath();
String newPath = oldPath.substring(0,oldPath.lastIndexOf("/"));
file.renameTo(new File(newPath+"/"+newName));
adapter.notifyDataSetChanged();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do nothing.
}
}).show();

Android: How to show a dialog after user clicks "Okay" on a previous dialog

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.

Categories

Resources