Shared Preference Android Studio

Thread Starter

Lemon_Foam

Joined Sep 18, 2017
39
I had build an mobile app which consist of 2 activity as shown in figure below.It can let user to choose for go to main activity or the second activity

Main activity let user to send text to the second activity.
Second Activity let user to recieve text from main activity.

Can somebody teach me how i can save the text received in the second activity by using shared preference directly. That mean everytime second activity recieved text, it can save the text itself and user dont need to press an save button manually for saving that text

Below shown the layout of my app and code for that 2 activity

App_layout.PNG MainActivity_layout.PNG SecondActivity_layout.PNG




Code:
public class MainActivity extends Activity {

    EditText SendValue;
    Button SendEditTextValue;
    Intent intent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SendEditTextValue = (Button)findViewById(R.id.button1);
        SendValue = (EditText)findViewById(R.id.editText1);

        SendEditTextValue.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                intent = new Intent(getApplicationContext(),SecondActivity.class);
                intent.putExtra("EdiTtEXTvALUE", SendValue.getText().toString());
                startActivity(intent);

            }
        });
    }
}



Code:
public class SecondActivity extends Activity {

    TextView receive;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        receive = (TextView)findViewById(R.id.textView1);
        receive.setText(getIntent().getStringExtra("EdiTtEXTvALUE"));


        this.getSharedPreferences("MyPrefName",   Context.MODE_PRIVATE).edit()
                .putString("EdiTtEXTvALUE",getIntent().getStringExtra("EdiTtEXTvALUE")).apply();

    }


}
 
Top