Search code examples
javaandroidsavesmartphone

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?


Solution

    1. Save the content to a file in your app's cache
    2. If the content is plain text (and not too long), you can easily use SharedPreferences to save the content
    3. 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:

    Rich Text Editors:

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