How to "Save as" via Button programmatically - android

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" />

Related

How to show alert message in an android app

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

EditText.getText() cannot be resolved, making a file protection app

I am making a file protection application that asks users to enter a password, this password is stored and next time to view the file they have to enter the same password.
I am able to ask users to set password, and protect the file, and I am able to ask users to enter password for viewing. the issue I have is with the input field.
The code for setting password is:
public static void protect(final File file, final FileListActivity mContext, final OperationCallback<Void> callback)
{
LinearLayout layout = new LinearLayout(mContext);
layout.setOrientation(LinearLayout.VERTICAL);
final EditText input = new EditText(mContext);
input.setHint(mContext.getString(R.string.enter_new_name));
input.setSingleLine();
layout.addView(input);
final EditText confirm = new EditText(mContext);
confirm.setHint(mContext.getString(R.string.confirm_new_name));
confirm.setSingleLine();
layout.addView(confirm);
new Builder(mContext)
.setTitle(mContext.getString(R.string.rename_dialog_title, file.getName()))
.setView(layout)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String newName = confirm.getText().toString();
String password=input.getText().toString();
try
{
//File parentFolder = file.getParentFile();
if (newName.equals(input.getText().toString())){
pass=newName;
pe=true;
filename=file.getName();
Toast.makeText(mContext,"password match", Toast.LENGTH_LONG).show();
}
else if (!newName.equals(password)) {
pe=false;
Toast.makeText(mContext,"password doesnot match", Toast.LENGTH_LONG).show();
}
else
{
if(callback!=null)
{
callback.onFailure(new Exception());
}
if(mContext!=null)
new Builder(mContext)
.setTitle(mContext.getString(R.string.error))
.setMessage(mContext.getString(R.string.rename_failed, file.getName()))
.show();
}
}
catch (Exception e) {
if(callback!=null)
{
callback.onFailure(e);
}
Log.e(TAG, "Error occured while renaming path", e);
if(mContext!=null)
new Builder(mContext)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(mContext.getString(R.string.error))
.setMessage(mContext.getString(R.string.rename_failed, file.getName()))
.show();
}
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
})
.show();
}
The code for asking users for the password to view the file is:
private void checkpass(final File file,FileListActivity mContext){
if(FileActionsHelper.pe==true && file.getName().equals(FileActionsHelper.filename)){
final EditText input = new EditText(FileListActivity.this);
input.setHint(mContext.getString(R.string.password_add));
input.setSingleLine();
new Builder( mContext)
.setTitle(mContext.getString(R.string.rename_dialog_title, file.getName()))
.setView(input)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
try
{
if ((FileActionsHelper.pass).equals("1")){
openFile(file);
Toast.makeText( FileListActivity.this,"password matched", Toast.LENGTH_LONG).show();
}
else if (!(FileActionsHelper.pass).equals("1")) {
Toast.makeText( FileListActivity.this,"you entered wrong password", Toast.LENGTH_LONG).show();
}
else if (FileActionsHelper.pe!=true){
openFile(file);
}
}
catch (Exception e) {
Log.e(TAG, "Error occured while renaming path", e);
}
}
}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
})
.show();
}
}
the code for opening of file is:
void openFile(File file) {
//if(FileActionsHelper.pe==true && file.getName().equals(FileActionsHelper.filename)){
checkpass(file,FileListActivity.this);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
MimeTypeMap.getFileExtensionFromUrl(uri.toString()));
intent.setDataAndType(uri, type == null ? "*/*" : type);
startActivity((Intent.createChooser(intent,getString(R.string.open_using))));}
//else {
// }
//}
The error i am getting is in the function check pass, at input.getText.toString(); it says getText cannot be resolved into a type or field.
How can I fix this ?

Android java : How to write string text and save it into txt.file [duplicate]

This question already has answers here:
Android Writing Logs to text File
(15 answers)
Closed 8 years ago.
Okay so far i have successfully create the folder. in CreateFolderActivity.java
The following bellow is the create folder code:
btn_cFolder.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
String dateN = edit_date.getText().toString();
new AlertDialog.Builder(DatePickerActivity.this, AlertDialog.THEME_HOLO_DARK)
.setTitle("Create Folder")
.setMessage("Confirm to create " + dateN +" folder ?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Environment.getExternalStorageDirectory();
String dateN = edit_date.getText().toString();
edit_date.setTypeface(edit_date.getTypeface(), Typeface.BOLD_ITALIC);
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/CalendarNote/" + dateN);
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
Toast.makeText(getBaseContext(), "You have successfully created." , Toast.LENGTH_LONG ).show();
Intent w = new Intent(DatePickerActivity.this, SelectTypeActivity.class);
startActivity(w);
} else {
Toast.makeText(getBaseContext(), "You have Failed to create." , Toast.LENGTH_LONG ).show();
}
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(R.drawable.ic_launcher)
.show();
}
});
And also i have successfully to create the txt file.
But now the only problem is the path location I try many of way to connect this two to
save file into the folder. So far i wish the txt file is save like this /CalendarNote/TheDateIPick/hello.txt.
Now i only can save to the same folder as CalendarNote.
The following code is the code i modified but not successful. Please help me.
public void SaveListener() {
imb_savefile = (ImageButton) findViewById(R.id.imb_savefile);
imb_savefile.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
edit_date = (EditText) findViewById(R.id.edit_date);
String t = edit_title.getText().toString();
new AlertDialog.Builder(WriteNoteActivity.this, AlertDialog.THEME_HOLO_DARK)
.setTitle("Save Note")
.setMessage("Confirm to save " + t +"?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String content = edit_content.getText().toString();
String title = edit_title.getText().toString();
String dateN = edit_date.getText().toString();
boolean success = true;
try {
File sdCardDir = Environment.getExternalStorageDirectory();
File targetFile;
targetFile = new File(sdCardDir.getCanonicalPath()
+ "/CalendarNote/"+ dateN);
File file=new File(targetFile + "/"+title+".txt");
if(!targetFile.exists()){
success = targetFile.mkdir();
}
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek(file.length());
raf.write(content.getBytes());
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getBaseContext(), "You have successfully created." , Toast.LENGTH_LONG ).show();
} else {
Toast.makeText(getBaseContext(), "You have Failed to create." , Toast.LENGTH_LONG ).show();
}
//Toast.makeText(getBaseContext(), "Note have successfully saved." , Toast.LENGTH_LONG ).show();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getBaseContext(), "Note Cancelled." , Toast.LENGTH_LONG ).show();
}
})
.setIcon(R.drawable.ic_launcher)
.show();
}
});
}
Yes, it is possible. See this for details: http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

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

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