Im doing a function where I record my voice then I save it into the data folder. Managed to work around saving into the data folder. But now my problem is that I need to check whether there is that specific data in the data folder so that I can do some stuff.. This is my code and not sure where went wrong:
individualFile = "y1";
OUTPUT_FILE= mydir + "/" + individualFile;
try{
File file = this.getFileStreamPath("y1");
if(file.exists()){
Log.v("Oh yes the thing is here", OUTPUT_FILE);
Share();
}else{
btn.setVisibility(View.VISIBLE);
}
}
catch(Exception e){
//Error message
}
}
What I need is that to check if the recorded file is already inside the data folder and if it is, then i need to show the Share() else I need to show the button for recording.
Related
I'm trying to access the two files, Spring v2.json and Test.json, in my Android app. However, I will add them using Windows with my phone connected, but when I run my app, the file seems to disappear.
Getting the file
File file = new File(getExternalFilesDir(null), "Spring v2.json");
Check is the file exists
if (file.exists()) {
TransferObserver observer = transferUtility.download(
"easelbucket", // bucket to download from
"sections/" + objectKey, // key for object to be downloaded
file // file to download object to
);
} else {
Toast.makeText(this, "File does not exist", Toast.LENGTH_SHORT).show();
return null;
}
I know that the file stops existing because (1) the if statement enters the else block, and (2) the app crashes when it attempts to use the result of the file.
File file = new File(getExternalFilesDir(null), "/Spring v2.json")
You forget slash before filename.
Also check if
.canRead();
and
.canExecute();
My app involves downloading a few csv files and then choosing one of them to perform some functions. After the user downloads the required files, a spinner must display the files that have been downloaded. On selecting the required file, it must link to another activity where the path of the file chosen is the FileName. Is this possible using a spinner and how do I go about it?
File selected = new File("/storage/emulated/0/Download/");
String item_ext = "";
try {
item_ext = selected.getName().substring(selected.getName().lastIndexOf("."));
} catch (StringIndexOutOfBoundsException e) {
item_ext = "";
}
if(item_ext.equalsIgnoreCase(".csv")) {
Intent txtIntent = new Intent();
txtIntent.setAction(android.content.Intent.ACTION_VIEW);
txtIntent.setDataAndType(Uri.fromFile(selected), "text/csv");
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
try {
startActivity(txtIntent);
} catch(ActivityNotFoundException e) {
txtIntent.setType("text/*");
startActivity(txtIntent);
}
}
Since my application requirement mainly dealt with downloaded files, I linked the app to Downloads folder. By clicking on the file of interest, the path for the file was obtained. This link helped to get the absolute path and was suitably modified for the purpose.
I have an android app that is writing a values to a file that the app also creates. I am able to write to the file and then again read from the file. However, as soon as that activity is finished, it seems that the file is now gone, or loses it's values.
I know you can't browse the files through explorer unless you root your phone and/or run the adb server as a specific user.
Here is my code for writing to the file:
public void savePrices(View view) {
FileOutputStream outputStream;
File getFilesDir = this.getFilesDir();
File filePathOne = new File(getFilesDir, filename);
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
for (int i = 0; i < priceArray.length; i++) {
outputStream.write(String.format("%.2f\n", priceArray[i]).getBytes());
}
Toast.makeText(this, "Prices saved successfully!", Toast.LENGTH_SHORT).show();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Here is my code that reads the file:
public void loadPrices(View view) {
int i = 0;
final InputStream file;
BufferedReader reader;
try{
file = getAssets().open(filename);
reader = new BufferedReader(new InputStreamReader(file));
String line = reader.readLine();
while(line != null){
line = reader.readLine();
priceArray[i] = Double.parseDouble(line);
i++;
}
} catch(IOException ioe){
ioe.printStackTrace();
hamburgerPriceText.setText(String.format("%.2f", priceArray[0]));
hotDogPriceText.setText(String.format("%.2f", priceArray[1]));
chipsPriceText.setText(String.format("%.2f", priceArray[2]));
beerPriceText.setText(String.format("%.2f", priceArray[3]));
popPriceText.setText(String.format("%.2f", priceArray[4]));
Toast.makeText(this, "Prices loaded successfully!", Toast.LENGTH_SHORT).show();
}catch (NumberFormatException e) {
Log.e("Load File", "Could not parse file data: " + e.toString());
}
}
After I call the save method which sets the values in the array and saves the values to the file, I run a clear method that removes all the values on the activity fields and in the array. So when I run the read method and it populates the fields on the activity, I know the values are coming from reading the file. This is the only way that I know that I'm saving and reading from the file successfully.
My question is how do I make it permanent? If I close the activity that saves the values and then immediately run the read method, all the values are 0.
Is there something that I am missing? How can I write to a file so if the activity is closed, or the app is completely closed, I can still retain the values?
Here is my code that reads the file:
There is nothing in that code that reads a file. It is reading some stuff out of the your app's assets. Also, for some reason, it is only updating the UI if you have an exception.
So when I run the read method and it populates the fields on the activity, I know the values are coming from reading the file.
No, they are coming from your app's assets, and you are only populating the fields if you have an IOException.
My question is how do I make it permanent?
Step #1: Actually read from the file. Since you are using openFileOutput() to write to the file, use openFileInput() to read from the file.
Step #2: Update the UI when you successfully read in the data, not in the catch block for the IOException.
I'm making a video downloader app and I've got no problems saving and deleting files downloaded by the app to external storage but any file transfered from my computer cannot be deleted by the app.
This is a real problem as it's one of the key features I want. Here's the code I'm using:
public boolean deleteDataFromStorage(Data toDelete) {
//The file object soon to be deleted
File f = null;
Log.e(TAG, "Deleting " + toDelete.fileName);
// Delete file from storage
try {
// Get file to delete
f = new File(Environment.getExternalStorageDirectory().getCanonicalPath() + DIRECTORY + toDelete.fileName);
} catch (IOException e) {
Log.e(TAG, e.toString());
// Print to stack trace
e.printStackTrace();
}
// Delete file
if(f.delete()) {
return true;
} else {
Log.e(TAG, "Failed to delete " + toDelete.fileName);
return false;
}
}
As the f.delete() function doesn't throw any exceptions I have no idea what the problem is. The only thing I can think of is that the app doesn't have the permission to delete a file created in windows and yet I have downloaded apps from the app store that have no problem deleting transfered files.
Any help would be greatly appreciated.
As per your comment, since f.isFile() and f.exists() returns false, your f is not a file, in other words, you're getting the path wrong.
Print to the logs f.getAbsolutePath(), check what it is, and then it should be easy to fix.
I want to know whether it is possible to write data in /etc folder (or any other folder besides data)? If yes, how to do that?
And if not possible, any way to store a permanent data? For scenario example, an app is uninstalled (or clear data), but a specific file will still remain.
thank you.
i'm not sure about /etc folder, but the stuff saved in /data folder is managed by android automatically itself. So when you uninstall an app, anything related to it is also removed from data folder.
However, to store a file permanently besides Data folder on your SdCard, see the code below:
public static boolean saveOnFile(String msg){
boolean saved = false;
String filename = "yourFileName.extension";
try{
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
File root = new File(Environment.getExternalStorageDirectory(), "/YourFolderOnSdCard/");
//create root folders if they do not exist
if(!root.exists()){
root.mkdirs();
}
//now lets save file in our directory structure
File file = new File(root, filename);
FileWriter fw = new FileWriter(file);
fw.append(msg);
fw.flush();
fw.close();
saved = true;
}
else
Log.e("Save", "Mounted media is not available or is write-protected");
}
catch (Exception e) { Log.e("Save", e.toString()); }
return saved;
}
This Data Storage guide could be useful.