I´m trying to save my values to .csv file with this code.
try {
CSVWriter writer = new CSVWriter(new FileWriter(getFilesDir()+"ECGValues.csv"),',');
// feed in your array (or convert your data to an array)
String[] entries = Values_to_save.toArray(new String[Values_to_save.size()]);
writer.writeNext(entries);
writer.close();
Values_to_save.clear();
Toast.makeText(this,"ECG values saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this,"Error while saving values", Toast.LENGTH_SHORT).show();
Log.e("error", "" + e.getMessage());
Log.e("error",""+ e.getStackTrace());
}
My input data is from
Lead_I_save =String.valueOf(IValue);
Lead_II_save = String.valueOf(IIValue);
Lead_III_save = String.valueOf(IIIValue);
Lead_aVL_save = String.valueOf(aVLValue);
Lead_aVF_save = String.valueOf(aVFValue);
Lead_aVR_save = String.valueOf(aVRValue);
String newLine = String.format("%1$s;%2$s;%3$s;%4$s;%5$s;%6$s;",
Lead_I_save, Lead_II_save, Lead_III_save,
Lead_aVL_save, Lead_aVF_save, Lead_aVR_save);
Values_to_save.add(newLine);
A Toast appears with ECG values saved, but I cannot find the .csv anywhere.
I will welcome any suggestions. Thanks
You used a relative path (only a file name) and then your file lands in the apps private internal memory which is unreachable for other apps. Use a full path to external memory instead.
Related
We have an app that sends MMS messages. The Android MmsManager requires a URI parameter that points to a file. It seems this file needs to be public, or the MmsService gets an Io exception for Permission denied. So in conforming with new scoped storage rules I create a .dat file in the MediaStore DownLoads folder. This works fine, even if storing .dat files in the MediaStore doesn't make sense to me. But after the MMS message is sent, I need to delete this file. I can't see any way of doing this without asking the user for permission, or using android.permission.MANAGE_EXTERNAL_STORAGE. Asking the user for permission to delete files he doesn't even know about is obviously not good. And of course android.permission.MANAGE_EXTERNAL_STORAGE requires permission from Google to use, and seems overkill just to be able to remove a data file that was created by the app. So, is there any way to create a public file that can later be deleted. I am already aware of android:requestLegacyExternalStorage="true" which is a very temporary solution, and Environment.getExternalStoragePublicDirectory which is deprecated. The file is created using code similar to below. pdu is a previously created byte array.
final String fileName = "send." + String.valueOf(Math.abs(mRandom.nextLong())) + ".dat";
ContentResolver contentResolver = mContext.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
Uri contentUri = contentResolver.insert(MediaStore.Files.getContentUri("external"), contentValues);
try {
writer = mContext.getContentResolver().openOutputStream(contentUri);
writer.write(pdu);
} catch (final IOException e) {
Log.e(TAG, "Error writing to output stream in MmsSender. e= ", e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
Log.e(TAG, "IOException writing PDU file in MmsSender, e= " + e);
}
}
}
I implemented a share button in my app. When I want to share, I can select a saved json data from the device and select via which way I want to share it (mail etc.). The problem is, that the data is NOT in the attachements. The problem is likely because I use the internal app storage. Therefore I want to save tje json data into the external storage, what would be better in my case anyway. But I am not really sure how to do that. I am not sure if I should use the Media type of content of the Documents and other files type of content which is provided by android. There is also the Appspecific files type but this looks like it is not applicaple for me, because I need to share the json data wit ha share functin. At the moment my code looks like this:
Save Function, which get's a file name I can choose myself
private void saveState(String name) {
File file = new File(getFilesDir(), name + ".json");
try{
OutputStream out = new FileOutputStream(file);
MyJsonWriter writer = new MyJsonWriter();
writer.writeJsonStream(out, ... //data structure);
out.close();
}catch (Exception e){
Log.e("saveState ERROR", "----------------------------------------------------");
}
}
LoadButtonClick Functin which shows me all files
public void loadStateClick(View view) {
final LinearLayout layout = new LinearLayout(MainActivity.this);
layout.setOrientation(LinearLayout.VERTICAL);
String[] files = MainActivity.this.fileList();
... //more code which is not important here
Load Function
private void loadState(String name) {
File file = new File(getFilesDir(), name);
InputStream in = null;
... //setting my data structure, not important here
try{
in = new FileInputStream(file);
MyJsonReader reader = new MyJsonReader(MainActivity.this);
SaveData savedData = reader.readJsonStream(in);
... // handling data structure, not important here
in.close();
}catch (Exception e){
Log.e("LOAD ERROR", e.toString());
}
}
I need to check whether a file (with unknown extension) is a valid SQLite database.
The db file is stored on the sd card. I need to import the database in my app. But if the user creates a file by the same name as of the database with any extension the file is still accepted by the code as it searches only for the name.
Is there a quick way to check for the validity of sqlite db stored on memory card.
I used this code, but it still accepts arbitrary file with same name as db.
String path = Environment.getExternalStorageDirectory().getPath() + "/FOLDER/DB_FILE";
SQLiteDatabase database;
database = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
if (database == null) {
Toast.makeText(getApplicationContext(), "Error: Incorrect/Corrupted File", Toast.LENGTH_SHORT).show();
return;
} else {Proceed with code here}
A SQLite database file contains a header which provides some useful information.
In particular, every SQlite database file has always in it's first 16 bytes the value: SQLite format 3\0000
So you can check if your file contains that value in its first 16 bytes:
public boolean isValidSQLite(String dbPath) {
File file = new File(dbPath);
if (!file.exists() || !file.canRead()) {
return false;
}
try {
FileReader fr = new FileReader(file);
char[] buffer = new char[16];
fr.read(buffer, 0, 16);
String str = String.valueOf(buffer);
fr.close();
return str.equals("SQLite format 3\u0000");
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
Thanks #Drilon Kurti.
But from my own situation I want to add something.
Sometimes, When trying to open Database, if the file even not valid, an empty database may create with the same name in the app memory, as a result many problems occur, and sometimes, that, for the second time it will direct fall through the memory, which is a database by name and even pass the check as a database file, but not the real one. So, In this situation Drilon Kurti's method also pass true. But finally the database will not open or cant find the required columns. In this case I have checked with a min size with the above answer.
But, in real life, in every situation the following code will not fit, it will fit when you know the min size of the db. In example, when we embedded a db with app, or read an external db which's real size we can determine before opening it, and check it with the size :
public boolean isValidSQLite(String dbPath, int minSizeInMb) {
File file = new File(dbPath);
if (!file.exists() || !file.canRead()) {
return false;
}
boolean isReadable = false ;
try {
FileReader fr = new FileReader(file);
char[] buffer = new char[16];
try {
fr.read(buffer, 0, 16);
} catch (IOException e) {
e.printStackTrace();
}
String str = String.valueOf(buffer);
fr.close();
isReadable = str.equals("SQLite format 3\u0000");
} catch (Exception e) {
e.printStackTrace();
}
if (file.length() > (1024 * 1024 * minSizeInMb) && isReadable) {
return true;
}else {
try {
file.delete();
} catch (Exception e) {
e.printStackTrace();
}
return false ;
}
}
And the database memory path should be:
String DB_PATH;
String DB_NAME;
String packageName = mContext.getPackageName();
DB_PATH = String.format("//data//data//%s//databases//", packageName);
DB_NAME = "Your_Database_tafheemul_quran.db";
String path = DB_PATH + DB_NAME;
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.
So I want to save whatever users write in their EditText to be saved for the next time. This exact same code works for java project but with Android project, it doesnt work.
The code is below.
The PrintWriter out = new PrintWriter("hi"); always gives the FileNotFoundException e.
In java project, this code The PrintWriter out = new PrintWriter("hi"); makes a new file with the name "hi" but android project does not produce a new file instead returns the error. It does not save the String from the EditText to be opened when the app opens up again later.
Does anyone have a solution to this problem?
public void onCreate(blablabla)
{blablabla
try {
FileReader reader = new FileReader ("hi");
Scanner in = new Scanner(reader);
String line = in.nextLine();
mEditText.setText(line);
in.close();
} catch (FileNotFoundException e) {
mEditText.setText("");
Toast.makeText(mContext, "null!!", Toast.LENGTH_SHORT).show();
}
#Override
protected void onDestroy()
{
super.onDestroy();
// The activity is about to be destroyed.
try {
PrintWriter out = new PrintWriter("hi");
out.write(mEditText.toString());
out.close();
} catch (FileNotFoundException e) {
Toast.makeText(mContext, "Can't save", Toast.LENGTH_SHORT).show();
}
}
May be Android permission problem. See http://developer.android.com/guide/topics/manifest/manifest-intro.html#perms
Or better to use SharedPreferences?