Search code examples
androidfileinputstream

Android - read internal data


I'm trying to make app, and I need to save string, just like TinyDB in AppInventor. So, I found there http://developer.android.com/guide/topics/data/data-storage.html#filesInternal that what I'm looking for is saving data to internal storage, but I don't know how to read it. They say:

To read a file from internal storage:

  1. Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream.

  2. Read bytes from the file with read().

  3. Then close the stream with close()

But I don't know how, my code never works. So I googled how to read from internal storage, and no code worked. Can you please tell me, how to read text from internal storage? :)

This is the code:

    EditText tagbox = (EditText)findViewById(R.id.editText1);
    String tag = tagbox.toString();
    Context context = getApplicationContext();


    FileInputStream fis = context.openFileInput( tag );
    InputStreamReader in = new InputStreamReader(fis);
    BufferedReader br = new BufferedReader(in);
    String data = br.readLine();

        Toast.makeText(getApplicationContext(), data, Toast.LENGTH_LONG).show();

Ok, so I found the solution. The easiest way to store data ,like TinyDB in AppInventor, is using SharedPreferences:

 SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

 Edtior editor = preferences.edit();

To store data:

editor.putString("key", "value");

To read data:

String value = preferences.getString("key");

Solution

  • Ok, so I found the solution. The easiest way to store data ,like TinyDB in AppInventor, is using SharedPreferences:

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    
    Edtior editor = preferences.edit();
    

    To store data:

    editor.putString("key", "value");
    

    To read data:

    String value = preferences.getString("key");