引起原因:java.lang.NullPointerException:SharedPreference错误

时间:2018-09-23 10:48:41

标签: android nullpointerexception sharedpreferences

我是Android新手。我使用名为“ MyPref”的共享首选项来存储和检索值。代码逻辑为“ MyPref”存储用户ID,用户类型(客户,驱动程序)。在我的SplashActivity中,我编写了以下代码。如果用户ID不为null,并且用户类型等于客户或驱动程序,则活动应进行相应导航。但出现以下错误:请帮助

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

SplashActivity:

public class SplashActivity extends AppCompatActivity {
    SharedPreferences pref;
    SharedPreferences.Editor editor;
    Context context;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        pref = context.getSharedPreferences("MyPref", 0);
        editor = pref.edit();
        String userid=pref.getString("userid","");
        Log.e("userid",userid);
        if(userid!=null)
        {
            String usertype=pref.getString("usertype1","");
            if(usertype.equals("customer"))
            {
                Intent customer=new Intent(SplashActivity.this, HomeFragment.class);
                startActivity(customer);
            }
            else
            {
                Intent driver=new Intent(SplashActivity.this, DriverDashboardFragment.class);
                startActivity(driver);
            }
        }
        else
        {
            Intent walk=new Intent(SplashActivity.this,WalkThroughActivity.class);
            startActivity(walk);
        }

        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {

            }
        }, 2000);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}

2 个答案:

答案 0 :(得分:3)

从此语句中删除上下文:

pref = context.getSharedPreferences("MyPref", 0);

应为pref = getSharedPreferences("MyPref", 0);

您遇到此问题,因为上下文未初始化。 您无需在此处引用上下文,因为AppCompatActivity是Context类的子级。因此,您可以直接致电getSharedPreferences

此后,您的应用程序崩溃,因为您尝试通过startActivity方法启动片段。要在活动中开始片段:

FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.container,new DriverDashboardFragment(),"driverDashboard");
transaction.addToBackStack(null);
transaction.commit();

将上面的代码替换为:

Intent driver=new Intent(SplashActivity.this, DriverDashboardFragment.class);
                startActivity(driver);

您需要将此添加到此活动的xml中:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />

答案 1 :(得分:1)

您的上下文为空

只需在setcontentView之后添加此行

 context= this;

它不会崩溃..