Saeid Saeid - 3 months ago 46
Android Question

How to use getSharedPreferences in a AppCompatActivity

I have a login class that extends

AppCompatActivity
but when I want to check my data and use
getSharedPreferences()
it has runtime error and will force stop! What should i do?

Here is my code:

package biz.test.internet;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.content.Intent;
import android.preference.PreferenceFragment;
import android.support.v4.content.SharedPreferencesCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.preference.PreferenceManager;
import android.content.Intent;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Random;

public class Login extends AppCompatActivity {
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
}
}


Note that if i disable
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
then run time error will be fixed and if i use
PreferenceActivity
instead of
AppCompatActivity
,
setContentView
method will have error!

I don't know how to use both of them.

Thank you.

Answer

You have to put the call inside your onCreate method.

SharedPreferences sharedpreferences;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);
    sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
}