Wednesday, February 20, 2019

Java write data

In any class, choose a textView to set text.
Copy the code lines to below findViewByid.
String write="This is example text";
try {
FileOutputStream fos = openFileOutput("text.txt", Context.MODE_APPEND);
OutputStreamWriter osw = new OutputStreamWriter(fos);
     osw.append(write);
     osw.flush();
     osw.close();
      } catch (FileNotFoundException e) {            
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }  
Here we write a String to file name text.txt, to make sure the data has write, we read that file and set text to textView.
String read="";
try {
          String FILE_NAME = "text.txt";          
          FileInputStream fIS = openFileInput(FILE_NAME);              
          byte[] arrayData = new byte[fIS.available()];
          if((fIS.read(arrayData))!= -1){
          String fileContent = new String(arrayData);
          read=fileContent;
          tv.setText(read);
          }   
          fIS.close();             
          } catch (Exception e) {
              
               //Log.e("Error", e.toString());
          }
Run to see text has read success.
If you quit and reopen class many times, you will see many string add to textView, because file text.txt always there and programme continue to write many times.

Java Saving and Retrieving Preferences

We want to save data and retry after.
First, save data, use this lines.
final String MYPREFS = "mySave";
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS,mode);
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putBoolean("isTrue", true);
editor.putFloat("lastFloat", 1f);
editor.putInt("Number", 2);
editor.putString("textEntryValue", "My String");
editor.commit();
To get data saved, use this lines, key value must be the same with key value saved.
final String MYPREFS = "mySave";
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS,mode);
boolean isTrue = mySharedPreferences.getBoolean("isTrue",false);
float mfloat = mySharedPreferences.getFloat("lastFloat", 0f);
int number = mySharedPreferences.getInt("Number", 1);

String stringPreference = mySharedPreferences.getString("textEntryValue","");

Or we can do shortly.
final SharedPreferences.Editor edit = prefs.edit();
 edit.putInt("vi"100);
 edit.commit();  
To get data.
SharedPreferences prefs;
prefs=PreferenceManager.getDefaultSharedPreferences(this);
int so = prefs.getInt("vi", 0);