Chiranjeev Jain
Chiranjeev Jain

Reputation: 99

How do I save and display String using SharedPreference?

I have the following code but the application force closes before even opening. I have an EditText, a Button and a TextView. Clicking the Button should save the String from EditText to SharedPreference and the SharedPreference String should be displayed in the TextView. What am I doing wrong here.

package com.jainchiranjeev.arduinoremote.newcomponents;

import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {

    EditText edittext;
    Button confirm;
    TextView text;

    public static final String Name = "MyPrefs";
    SharedPreferences.Editor editor = getSharedPreferences(Name, MODE_WORLD_WRITEABLE).edit();

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

        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editor.putString("name", String.valueOf(edittext.getText()));
                editor.commit();
            }
        });

        SharedPreferences prefs = getSharedPreferences(Name, MODE_WORLD_READABLE);
        String restoredText = prefs.getString("name","Your name appears here");
        text.setText(restoredText);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Upvotes: 0

Views: 543

Answers (2)

Chad Bingham
Chad Bingham

Reputation: 33856

Initialize your prefs after the class is initialized. You need the context. Also, use the same prefs for the editor and writer:

SharedPreferences prefs = getSharedPreferences(Name, Context.MODE_PRIVATE);
//to write:
prefs.edit().putString("key", "value_to_save").apply();
//to read
String read = prefs.getString("key", "value_default");

Upvotes: 1

Rodolfo Abarca
Rodolfo Abarca

Reputation: 595

Get the shared Preferences in the onCreateMethod and dont initialize the editor as a field of the class.

SharedPreferences.Editor editor = context.getSharedPreferences(
            PREFERENCES_NAME, Context.MODE_MULTI_PROCESS | Context.MODE_PRIVATE).edit();
    editor.putString(setting, value);
    editor.apply();

also take this trainning http://developer.android.com/training/basics/data-storage/shared-preferences.html

Upvotes: 1

Related Questions