Working with files Android programming - java

I need your help.
So, what i intend to do is to read a value from a file and to increase this value by one, then write it in the same file, i don`t know where is my error.
This is the procedure which i use to do all of this :
And together with the folders :
I really appreciate your help until now, would be really thankful for any advice.
The problem i am facing i can`t find the file on device, the text file should be a permanent file created on the device in order to store some data, even if the app is closed or the phone is switched off.

The problem is that you in android you can't access file like you did with direct path
new File("./data/text2.txt");
You can use the Eniornment class to get the path to data folder than here create the your file and save the values.
For example :
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File path = Environment.getDataDirectory();
File file = new File(path, "text2.txt");
// from here you read and write like you already did.
}
However if you only need to write an Integer you can use SheredPreferences like this:
//get the value
SharedPreferences settings = getSharedPreferences("prefs", 0);
int test = settings.getInt("test", -1);
test++;
SharedPreferences.Editor editor = settings.edit();
editor.putInt("test", test);
editor.apply();

Related

Methods for saving user input like notes (Android Studio/Java programming)?

I am starting to code an app for taking notes, like Evernote or a basic preinstalled memo app, so that I can learn and practice coding.
Currently I save the user input in a .txt file, so that every note would have an own text file in the storage, with the note content.
What are other methods of saving user input in storage (you don't need to explain it, keyword would be appropriate) and what are the advantages or disadvantages of doing so? What can be cons of saving text files like I'm now doing?
Save the content to a file in your app's cache
If the content is plain text (and not too long), you can easily use SharedPreferences to save the content
You can use a database
Note that if the content is rich text, you can format that (for example, using HTML, JSON or XML and save files (like images) in a specified folder and write the location of the files to the formatted text) and then save to a database.
Useful links to get started:
Using databases:
https://developer.android.com/training/data-storage/sqlite
https://developer.android.com/training/data-storage/room
https://www.tutorialspoint.com/android/android_sqlite_database.htm
Rich Text Editors:
https://github.com/chinalwb/Android-Rich-text-Editor
https://github.com/wasabeef/richeditor-android
How to get cache directory?
File cacheDir = this.getCacheDir();
or
File cacheDir = this.getApplicationContext().getCacheDir();
Note that if the content is important, you can create a new folder in the storage (like "My App Name Files") and save the content to that folder.
If you are using EditText:
I name the EditText uinput. Here we go:
private void saveContent() {
String content = uinput.getText().toString();
String name = "Note 1"; // You can create a new EditText for getting name
// Using SharedPreferences (the simple way)
SharedPreferences sp = this.getApplicationContext().getSharedPreferences("notes", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString(name, content);
editor.apply();
}
private Map<String, ?> getAllNotes() {
SharedPreferences sp = this.getApplicationContext().getSharedPreferences("notes", Context.MODE_PRIVATE);
return sp.getAll();
}
private String getNoteContent(String noteName) {
SharedPreferences sp = this.getApplicationContext().getSharedPreferences("notes", Context.MODE_PRIVATE);
return sp.getString(noteName, "Default Value (If not exists)");
}
Don't save other things in SharedPreferences "notes".

android create text file on install

I need help storing data on my Android app. I need to create a text file, but only once. I have tried if(file.exists()) and if (file!=null) but nothing's working.I need this text file to store user data strings between app restarts. This code will create the file onCreate everytime, but I need it to only do it if the file doesnt already exist
private void createFile(String filename){
if(memoryFile != null){
memoryFile = new File(getApplicationContext().getFilesDir(), filename);
}
}
This code will create the file onCreate everytime
No, it will not. It will not create any file. It creates an instance of a File object. That is a Java object that represents a (possible) file on the filesystem. It does not actually create the file. To create the file, write something to it, using a FileOutputStream (and a background thread). To see if the file already exists, call exists() on memoryFile.
Also, note that you do not need getApplicationContext() here. Just use getFilesDir().

Can i store some string value into a text file in R.drawable folder in android

I am making a lock screen application. In my application, i want to store a PIN.. But every time when my activity called from the service, The PIN value is being resetted. So i want to store the value of PIN in some permanent place. Is there any way to store the PIN to a text file in R.drawable ? or is there any better ways ? Please help me
Yeah you don't want to put it in the resource folder. Use SharedPreferences instead.
To save a value:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putString("pin",your_pin).apply();
To read a value:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String pin = prefs.getString("pin","default pin");
Is there any way to store the PIN to a text file in R.drawable
No not possible to write or change files in any folder which bundle with apk.
is there any better ways ?
Use following ways to store data in application:
1. Use SharedPreferences for saving data
2. Create file for saving data in internal directory for your app using getFilesDir()
3. Create file for saving data in internal directory for your app's temporary cache files using getCacheDir()
NOTE : all files created using above methods will delete when application un-install or cache is clear from Application Manager.

What is my directory when writing files in Android?

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_WORLD_READABLE);
fos.write(string.getBytes());
fos.close();
When trying to delete one of those files, this is what I use, but it's returning false.
String tag = v.getTag().toString();
File file = new File(System.getProperty("user.dir")+"/"+tag);
String s = new Boolean (file.exists()).toString();
Toast.makeText(getApplicationContext(), s, 1500).show();
file.delete();
How can I overcome this problem?
Use getFileStreamPath(FILENAME) to find your file. From the docs:
Returns the absolute path on the filesystem where a file created with openFileOutput(String, int) is stored.
Your current working directory.
To help diagnose the problem, use file.getAbsolutePath() to see the full path.
It could also be a permissions problem, if you're trying to delete from another application. If so, you may need to change to MODE_WORLD_WRITEABLE (insecure), or restructure your code so the create and delete are called by the same app.
EDIT: That was mostly incorrect. I didn't realize that openFileOutput didn't use the current working directory.
Use same contents as 'FILENAME' variable in your first snippet in the second snippet while trying to delete.
String RootDir = Environment.getExternalStorageDirectory()
+ File.separator + "Video";
File RootFile = new File(RootDir);
RootFile.mkdir();
FileOutputStream f = new FileOutputStream(new File(RootFile, "Sample.mp4"));
i used this code to save the video files to non-default location. Hope this will be useful to you.By default it is storing in sd card
For each application the Android system creates a "data/data/package of the application" directory.
Files are saved in the "files" folder under this directory
to change the default directory the above code will be used
the default working directory can be displayed using fileobject.getAbsolutePath()

Using a button to export sqlite db to an excel-readable file (perhaps csv)?

I adapted this tutorial (http://www.screaming-penguin.com/node/7749) to an Android app I've built to allow for a button press to export the current database to the user's sdcard. It works flawlessly.
But I'm afraid that users of my app would be unfamiliar with the db file, and I'm looking for a way to convert that to a more user-friendly format. I came across this thread (http://groups.google.com/group/android-beginners/browse_thread/thread/4e53ebca14daecfc), which recommends "querying data from the database and writing the data into a csv file."
I was hoping someone could point me in the right direction to begin figuring out how to do this. I'm finding it hard to track down more information about the specific method.
Or does it make more sense to just explain in a short "about" how to read and access .db files?
Thanks
EDIT: I also have a question about the sqlite export process, which I think I'll just ask here rather than create a new question. Is there a way to modify the code below so that each export would receive either a string representation of the date or just a single numeral appended to it? Right now if you export a second time, it automatically overwrites the old file. Thanks.
protected Boolean doInBackground(final String... args) {
File dbFile = new File(Environment.getDataDirectory() +
"/data/com.example.example/databases/data");
File exportDir = new File(Environment.getExternalStorageDirectory(), "exampledata");
if (exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, dbFile.getName());
try {
file.createNewFile();
this.copyFile(dbFile, file);
return true;
} catch(IOException e) {
Log.e(MyApplication.APP_NAME, e.getMessage(), e);
return false;
}
}
I was hoping someone could point me in the right direction to begin figuring out how to do this.
To read in the data, use rawQuery().
To write the data, use Java I/O. There are also open source CSV libraries for Java that may work on Android.
Is there a way to modify the code below so that each export would receive either a string representation of the date or just a single numeral appended to it?
Use string concatenation to add whatever you want to the filename.
Also, please get rid of:
File dbFile = new File(Environment.getDataDirectory() +
"/data/com.example.example/databases/data");
and replace it with:
File dbFile=getDatabasePath("data");

Categories