0

I need to use string data inside OnReceivedDataMethod into second activity in order to save those string data into file but currently i have empty data into my file

 SharedPreferences sp;
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() { //Defining a Callback which triggers whenever data is read.
    @Override
    public void onReceivedData(byte[] arg0) {

        try {
            data = new String(arg0, "UTF-8");
            data.concat("/n");
             sp = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
            SharedPreferences.Editor et = sp.edit();
            et.putString("key",data);
            et.apply();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
};

In second activity

    protected void onCreate(Bundle savedInstanceState) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    desiredPreference =  sharedPreferences.getString("key","data");
    Toast.makeText(this,"spdata"+desiredPreference,Toast.LENGTH_LONG).show();

}

2 Answers2

3

The Value is null because you used PreferenceManager.getDefaultSharedPreferences(this) which returns preference with this activity name and it's different from the other preference you used in your first activity. Instead, you should call your preference in the same way you called it in your first activity.

SharedPreferences prefs = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String desiredPreference =  sharedPreferences.getString("key","data");

To know more about the difference you can check the documentation and this answer.

Community
  • 1
  • 1
SaNtoRiaN
  • 2,212
  • 2
  • 15
  • 25
0

Do something like this,

For storing

    SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putString("key", data);
    editor.commit();

for Retriving

  SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
  String checkDate = sharedPref.getString("key","");
Akash Dubey
  • 1,508
  • 17
  • 34