Pedro Igor
Pedro Igor

Reputation: 19

How to use SharedPreferences to save String passed as a parameter to another Activity by Intent?

I have a simple app that in my first Activity (A) insert a string in Edtittext and clicking on the save button, this string is passed to the next Activity (B) by Intent. So far so good, but the problem here is to implement the SharedPreferences. Use the Intent to be the best way to do this, and instantly, by sinal.Apenas need help to save this String Now!

My Activity Segunda:

private Intent grava;

    btSalvarSeg = (Button) findViewById(R.id.SalvarSeg);
    btSalvarSeg.setOnClickListener(new Button.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            grava = new Intent(Segunda.this, Main.class);

            grava.putExtra("Matéria 1", etHrSeg1.getText().toString());
            grava.putExtra("Matéria 2", etHrSeg2.getText().toString());
            grava.putExtra("Matéria 3", etHrSeg3.getText().toString());
            grava.putExtra("Matéria 4", etHrSeg4.getText().toString());
            grava.putExtra("Matéria 5", etHrSeg5.getText().toString());
            grava.putExtra("Matéria 6", etHrSeg6.getText().toString());
            grava.putExtra("Matéria 7", etHrSeg7.getText().toString());

            startActivity(grava);
        }

    });

The next Activity Main:

Intent busca; String Mat 1;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    busca = getIntent();

    Mat1 = busca.getStringExtra("Matéria 1");

    tvMainS1 = (TextView) findViewById(R.id.MainS1);
    tvMainS1.setText(Mat1);// Restaura preferências salvas}}

What I need to do? Please help me, I await answers :)

Upvotes: 0

Views: 625

Answers (2)

Sagar Shah
Sagar Shah

Reputation: 4292

If you want to use SharedPrefrences then you don't need to Pass Values through Intent.

You can easily Set and get Value from Shared Prefrences.

Here You can see the example.

Upvotes: 1

Martin Cazares
Martin Cazares

Reputation: 13705

SharedPreferences can be accessed from anywhere as long as you handle it properly, for example by using the default ones you can do it as follows(from any place of your app as long as you have a reference to the context):

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
Editor editPrefs = prefs.edit();
editPrefs.putBoolean(key, value);
editPrefs.commit();

Hope it Helps!

Regards!

Upvotes: 1

Related Questions