-1

I want to save user entered login values to save in sharedpreferences and retrieve it in another page. But the problem is when I go to data retrieving page app is crashing. Please help me.

LoginActivity.java

 SharedPreferences loginData = getSharedPreferences("userInfo", 
 Context.MODE_PRIVATE);
 SharedPreferences.Editor editor = loginData.edit();
 editor.putString("password", passwordbox.getText().toString());
 editor.putString("userName", usernamebox.getText().toString());

 editor.apply();

Data Retrieving page

public class messagewebview extends AppCompatActivity {
    TextView testing_name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_messagewebview);
        SharedPreferences loginData = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        String name = loginData.getString("userName", "");
        String pw = loginData.getString("password","");
        String msg = "Saved User Name: " + name + "\nSaved Password: " + pw;
        testing_name.setText(msg);

    }
}
Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43
  • Loads of examples on SO already. Heres an answer that should help. https://stackoverflow.com/a/12074219/940834 . Do you have a stack trace as to the crash, so we can see why its crashing? your code looks correct, except that `testing_name` is probably null.. You need to load it from the layout – IAmGroot Mar 22 '19 at 21:06

2 Answers2

0

testing_name is not initialized.

morten.c
  • 3,414
  • 5
  • 40
  • 45
Sandeep Polamuri
  • 609
  • 4
  • 10
0

Your variable "testing_name" is not initialized. A variable must be initialized before you start using it.

Do following changes in your code.

    public class messagewebview extends AppCompatActivity { 

        TextView testing_name; 

        @Override protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_messagewebview);
          // Provide a appropriate view id
          testing_name = findViewById(R.id.testing_name);
          SharedPreferences loginData = getSharedPreferences("userInfo", Context.MODE_PRIVATE); 
          String name = loginData.getString("userName", ""); 
          String pw = loginData.getString("password","");
           String msg = "Saved User Name: " + name + "\nSaved Password: " + pw;
            testing_name.setText(msg);

        }

        }
Amrat Singh
  • 331
  • 2
  • 13