I have the following code:
btnSaveTrip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (showLog != null && showLog.getText().toString().length() > 0) {
File folder = new File(Environment.getExternalStorageDirectory() + "/tc");
if (!folder.exists()) {
folder.mkdir();
}
String externalStoragePath = Environment.getExternalStorageDirectory().toString();
final File file = new File(externalStoragePath + "/tc/strip.tcl");
try {
if (file.exists()) {
new AlertDialog.Builder(getActivity())
.setTitle("File Already Exist")
.setMessage("Do you want to overwrite the file?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
outputStream = new FileOutputStream(file);
outputStream.write(showLog.getText().toString().getBytes());
Toast.makeText (getActivity(), file.toString(), Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
}
else {
outputStream = new FileOutputStream(file);
outputStream.write(showLog.getText().toString().getBytes());
Toast.makeText (getActivity(), file.toString(), Toast.LENGTH_SHORT).show();
}
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText (getActivity(), "error in try", Toast.LENGTH_SHORT).show();
}
finally {
if(outputStream!=null) {
try {
outputStream.close();
Toast.makeText (getActivity(), "file closed", Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText (getActivity(), "error in finally catch", Toast.LENGTH_SHORT).show();
}
}
}
}
else {
Toast.makeText (getActivity(), "empty", Toast.LENGTH_SHORT).show();
}
}
});
What I am looking to do is:
When the button is clicked:
1) Check to make the data is not null or empty (Working fine):
if (showLog != null && showLog.getText().toString().length() > 0) {
2) Check to make sure the folder exists, if not create the folder (Working fine):
File folder = new File(Environment.getExternalStorageDirectory() + "/tc");
if (!folder.exists()) {
folder.mkdir();
}
3) Before writing the data to the file, ensure it doesn't already exist. If it does exist, prompt the user to see if it can be overwritten. If the user chooses YES then overwrite the file but if the user chooses NO then add a "1" at the end of the filename and save it. (NOT WORKING and need help)
I am getting an error for the following line:
outputStream = new FileOutputStream(file);
outputStream.write(showLog.getText().toString().getBytes());
Error:
Unhandled exception type FileNotFoundException
--> (Surround with try/catch)
1)
File tcDir = new File(Environment.getExternalStorageDirectory(),"tc");
tcDir.mkdirs();
File file = new File(tcdir, "strip.tcl");
The first line creates a file object called tc in the external storage directoy. The second line creates it on disk, with any missing parents. The third line creates a file object inside that directory
2)You seem to be doing that- you create a file output stream and write to it like you're doing.
3)Before writing the file, cal file.exists(). If it exists, you need to pop up a AlertDialog. If they hit the yes button of the dialog you write a file. If they choose the no button, you do nothing. It would be best to put all of the writing code into a separate function so it can be called in both the dialog click code and in the !exists code here.
In answer to part 3), I've edited your code to work properly for you. Most of the code you had was correctly written there was just a couple of issues. I also moved the code to write a new file into a new method writeFile() in order to avoid replicating code and to make it easier to keep track of what's going on:
btnSaveTrip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (showLog != null && showLog.getText().toString().length() > 0) {
File folder = new File(Environment.getExternalStorageDirectory() + "/TollCulator");
if (!folder.exists()) {
folder.mkdir();
}
String externalStoragePath = Environment.getExternalStorageDirectory().toString();
final File file = new File(externalStoragePath + "/TollCulator/strip.tcl");
if (file.exists()) {
new AlertDialog.Builder(getActivity())
.setTitle("File Already Exist")
.setMessage("Do you want to overwrite the existing file?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
writeFile(file);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
} else {
writeFile(file);
}
} else {
Toast.makeText (getActivity(), "empty", Toast.LENGTH_SHORT).show();
}
}
});
// ...
private void writeFile(File file){
try {
outputStream = new FileOutputStream(file);
outputStream.write(showLog.getText().toString().getBytes());
Toast.makeText (getActivity(), file.toString(), Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(outputStream!=null) {
try {
outputStream.close();
Toast.makeText (getActivity(), "file closed", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText (getActivity(), "error in finally catch", Toast.LENGTH_SHORT).show();
}
}
}
}
Related
The current code works to save the photo but I want to implement the toast code below when the user saves the image already it show image save already. Any ideas how I would do this.
Below is the source code to take the photo:
holder.save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkFolder();
final String path = imagesList.get(position).getPath();
final File file=new File(path);
String destPath = Environment.getExternalStorageDirectory().getAbsolutePath()+Common.APP_DIR;
final File destFile =new File(destPath);
try {
FileUtils.copyFileToDirectory(file, destFile);
} catch (IOException e) {
e.printStackTrace();
}
MediaScannerConnection.scanFile(context, new String[]{destPath + status.getTitle()},
new String[]{"*/*"}, new MediaScannerConnection.MediaScannerConnectionClient() {
#Override
public void onMediaScannerConnected() {
}
#Override
public void onScanCompleted(String path, Uri uri) {
}
});
Toast.makeText(context, "Image Saved Successfully!", Toast.LENGTH_SHORT).show();
}
});
i am trying to select a file from the alert dialog and when i press OK i should display the content of the selected file in a text View by using the method display Content() that take the selected file read it and display the content line by line, but it does not display anything and i think the problem is with the call because i already use the method in another app and it work.
this is the code i have and how i call displayContent()
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("Single Choice List")
.setSingleChoiceItems(files, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
selectionID = which;
}
})
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//display the content of the selected file
displayContent();
Toast.makeText(View_Records.this, "You selected " + files[selectionID], Toast.LENGTH_SHORT).show();
}
})
this is the code for displayContent():
private void displayContent(){
try {
myFilesDirectory = new File(getFilesDir(), "MyFiles");
String fileName = files[selectionID] + ".txt";
File file = new File(myFilesDirectory, fileName);
String text;
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((text = br.readLine()) != null) {
sb.append(text).append("\n");
}
txtViewRecords.setText(sb.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Replace
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("Single Choice List")
.setSingleChoiceItems(files, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
selectionID = which;
}
})
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//display the content of the selected file
displayContent();
Toast.makeText(View_Records.this, "You selected " + files[selectionID], Toast.LENGTH_SHORT).show();
}
})
with calling for another Activity (startActivityForResult()) with dialog style where you will pick a File and return it's path with Intent and then inside onActivityResult() you just use it to open File and then display it's content inside TextView.
Otherwise you can try to use create() first and add onDismissListener(). Like this:
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// do you things with builder
AlertDialog ad = builder.create();
ad.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
// here you open file, read content and put it inside TextView`
}
});
ad.show()
I'm not sure, but this should do the job with AlertDialog without creating Activity for this.
This is for getting all files from directory:
public static ArrayList<File> listFiles(File folder) {
if (folder.isDirectory()) {
ArrayList<File> tempList = new ArrayList<>();
File[] files = folder.listFiles();
for (File inFile : files) {
if (!inFile.isDirectory()) {
tempList.add(inFile);
}
}
/*Collections.sort(tempList, new Comparator<File>() { //you can sort by name
#Override
public int compare(File file1, File file2) {
return file1.getName().compareTo(file2.getName());
}
});*/
return tempList;
}
return null;
}
And you just send myFilesDirectory as a parameter.
Also you can skip checking if(!inFile.isDirectory()) if you are 100% sure that all files are files, not directories and return Array.
And then you just get your file using list.get(selectionID) or array[selectionID] depending what you are going to return from method.
Also method doesn't need to be static. I've got it static for my project needs.
I would like to save/create a file in the directory of my Emulator but i cant do that and i dont understand what is wrong with my code. So everytime i try to run the code it says that android cant create the file in such directory.
Can someone please explain to me how i make it. Here is the code of my Application:
public class MainActivity extends AppCompatActivity {
private int STORAGE_PERMISSION_CODE = 1;
private File csvFile;
SimpleDateFormat TIME;
private static final String CSV_DIRECTORY = "NameOfTheDirectory";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if((ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED)){
Toast.makeText(MainActivity.this, "You have already granted this permission",
Toast.LENGTH_SHORT).show();
}else {
requestStoragePermission();
}
}
public void makeFile(View view) {
File csvDirectory = new File(
Environment.getExternalStorageDirectory().getAbsolutePath() +
File.separator + CSV_DIRECTORY);
if(!csvDirectory.exists()) {
try{
csvDirectory.mkdir();
Log.d("StateMakeFile","Directory created");
} catch(Exception e) {
e.printStackTrace();
Log.d("StateMakeFile","Directory not created");
}
}
File categoryDirectory = new File(
Environment.getExternalStorageDirectory().getAbsolutePath() +
File.separator + CSV_DIRECTORY + File.separator + "NameOfTheCategory");
if(!categoryDirectory.exists()){
try{
categoryDirectory.mkdir();
Log.d("StateMakeFile","CategoryDirectory created");
}catch (Exception e){
e.printStackTrace();
Log.d("StateMakeFile","CategoryDirectory not created");
}
}
TIME = new SimpleDateFormat("yyyyMMdd-hh:mm:ss:SSS", Locale.getDefault());
String uniqueFileName = TIME.format(new Date());
csvFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
File.separator + CSV_DIRECTORY + File.separator + "NameOfTheCategory" +
File.separator + uniqueFileName + ".csv");
if(!csvFile.exists()){
try{
csvFile.createNewFile();
Log.d("StateMakeFile","File created");
}catch (IOException e){
e.printStackTrace();
Log.d("StateMakeFile","File not created");
}
if(csvFile.exists()) {
try{
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(csvFile, true)));
out.write("Something" + "\n");
out.flush();
out.close();
Log.d("StateMakeFile","File was writed with success");
}catch (IOException e){
e.printStackTrace();
Log.d("StateMakeFile","File wasnt writed with success");
}
}
}
}
private void requestStoragePermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
new AlertDialog.Builder(this)
.setTitle("Permission needed")
.setMessage("This permission is needed to save and load files into ssd")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create().show();
} else {
ActivityCompat.requestPermissions(this,
new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == STORAGE_PERMISSION_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission GRANTED", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Permission DENIED", Toast.LENGTH_SHORT).show();
}
}
}
}
I don‘t know if it is in your manifest, but your are working here with
READ_EXTERNAL_STORAGE
Try it with the permission
WRITE_EXTERNAL_STORAGE
Hope this helps you
I want to open a .pdf file in my android app.now i can browse the pdf file and after browsing the file I am getting File Not Found Error when i check the file exist or not. Now after selecting the file my selected file Uri data.getData() is like
content://com.android.externalstorage.documents/document/6333-6131:SHIDHIN.pdf
and the path when i parse using data.getData().getPath().toString() is like
/document/6333-6131:SHIDHIN.pdf Here is my code. Please Help me.
// To Browse the file
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
startActivityForResult(intent, PICK_FILE_REQUEST);
After selecting file
//onActivityResult
public void onActivityResult(final int requestCode, int resultCode, Intent data) {
try {
switch (requestCode) {
case PICK_FILE_REQUEST:
if (resultCode == RESULT_OK) {
try {
Uri fileUri = data.getData();
String path = fileUri.getPath().toString();
File f = new File(path);
if (f.exists()) {
System.out.println("\n**** Uri :> "+fileUri.toString());
System.out.println("\n**** Path :> "+path.toString());
final Intent intent = new Intent(MainActivity.this, ViewPdf.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
startActivity(intent);
} else {
System.out.println("\n**** File Not Exist :> "+path);
}
} catch (Exception e) {
ShowDialog_Ok("Error", "Cannot Open File");
}
}
break;
}
} catch (Exception e) {
}
}
This is not the answer but a workaround.
File file = new File("some_temp_path"); # you can also use app's internal cache to store the file
FileOutputStream fos = new FileOutputStream(file);
InputStream is = context.getContentResolver().openInputStream(uri);
byte[] buffer = new byte[1024];
int len = 0;
try {
len = is.read(buffer);
while (len != -1) {
fos.write(buffer, 0, len);
len = is.read(buffer);
}
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
pass this file's absolute path to your activity.
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
File pdfFile = new File(Environment.getExternalStorageDirectory(), "Case Study.pdf");
try {
if (pdfFile.exists()) {
Uri path = Uri.fromFile(pdfFile);
Intent objIntent = new Intent(Intent.ACTION_VIEW);
objIntent.setDataAndType(path, "application/pdf");
objIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(objIntent);
} else {
Toast.makeText(MainActivity.this, "File NotFound", Toast.LENGTH_SHORT).show();
}
} catch (ActivityNotFoundException e) {
Toast.makeText(MainActivity.this, "No Viewer Application Found", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
I want to add a Yes/No dialog box to my Android app, I tried the solution in this answer but I couldn't manage to make it work with my code, any help please?
This is my code in which I want to write a text from EditText.
public void buttonSelect( View v ) {
View view = null;
String mac1 = "mac1";
String mac2 = "mac2";
TextView tv1, tv2;
tv1 = (TextView) findViewById(R.id.textView1);
tv2 = (TextView) findViewById(R.id.textView2);
switch (v.getId()) {
case (R.id.Write_MAC1):
writeData(view, mac1); //I need to confirm writing the data
break;
case (R.id.Write_MAC2):
writeData(view, mac2); //I need to confirm writing the data
break;
}
}
//---------------------------- Writing MACs addresses Function --------------------------------------------
public void writeData(View view, String macNum)
{
BufferedWriter bufferWriter =null;
try {
FileOutputStream fileOutputStream = openFileOutput(macNum, Context.MODE_PRIVATE);
bufferWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
if (macNum.equals("mac1")){
bufferWriter.write(((EditText)this.findViewById(R.id.editText1)).getText().toString());}
if (macNum.equals("mac2")){
bufferWriter.write(((EditText)this.findViewById(R.id.editText2)).getText().toString());}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
try {
bufferWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Try to use this:
AlertDialog.Builder alertbox = new AlertDialog.Builder(LauncherActivity.this);
alertbox.setTitle("Are you sure?");
alertbox.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(LauncherActivity.this, "You Choose Yes!!", Toast.LENGTH_LONG).show();
}
});
alertbox.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(LauncherActivity.this, "You Choose Nooo!!", Toast.LENGTH_LONG).show();
}
});
alertbox.show();
See this git repo
Also a custom alertdialog example is exist in this repo.