Android SharedPreferences返回null对象引用

时间:2017-06-11 18:30:49

标签: java android nullpointerexception

我的Android项目中有2个活动和1个配置文件:

  1. LoginActivity
  2. MainActivity
  3. 配置
  4. 这是我的LoginActivity代码:

    public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    
        //Defining views
        private EditText editTextUsername;
        private EditText editTextPassword;
        private AppCompatButton buttonLogin;
    
        //boolean variable to check user is logged in or not
        //initially it is false
        private boolean loggedIn = false;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);
    
            //Initializing views
            editTextUsername = (EditText) findViewById(R.id.editTextUsername);
            editTextPassword = (EditText) findViewById(R.id.editTextPassword);
    
            buttonLogin = (AppCompatButton) findViewById(R.id.buttonLogin);
    
            //Adding click listener
            buttonLogin.setOnClickListener(this);
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            //In onresume fetching value from sharedpreference
            SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME,Context.MODE_PRIVATE);
    
            //Fetching the boolean value form sharedpreferences
            loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
    
            //If we will get true
            if(loggedIn){
                //We will start the Profile Activity
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
            }
        }
    
        private void login(){
            //Getting values from edit texts
            final String username = editTextUsername.getText().toString().trim();
            final String password = editTextPassword.getText().toString().trim();
    
            //Creating a string request
            StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.LOGIN_URL,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            //If we are getting success from server
                            if(response.equalsIgnoreCase(Config.LOGIN_SUCCESS)){
                                //Creating a shared preference
                                SharedPreferences sharedPreferences = LoginActivity.this.getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
    
                                //Creating editor to store values to shared preferences
                                SharedPreferences.Editor editor = sharedPreferences.edit();
    
                                //Adding values to editor
                                editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, true);
                                editor.putString(Config.USERNAME_SHARED_PREF, username);
    
                                //Saving values to editor
                                editor.commit();
    
                                //Starting profile activity
                                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                startActivity(intent);
    
                            }else{
                                //If the server response is not success
                                //Displaying an error message on toast
                                Toast.makeText(LoginActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show();
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            //You can handle error here if you want
                        }
                    }){
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String,String> params = new HashMap<>();
                    //Adding parameters to request
                    params.put(Config.KEY_EMAIL, username);
                    params.put(Config.KEY_PASSWORD, password);
    
                    //returning parameter
                    return params;
                }
            };
    
            //Adding the string request to the queue
            RequestQueue requestQueue = Volley.newRequestQueue(this);
            requestQueue.add(stringRequest);
        }
    
        @Override
        public void onClick(View v) {
            //Calling the login function
            login();
        }
    }
    

    这是我的MainActivity代码:

    public class MainActivity extends AppCompatActivity {
    
        private AdView mAdView;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
    
            AppCompatTextView name = (AppCompatTextView) toolbar.findViewById(R.id.name);
            AppCompatTextView job = (AppCompatTextView) toolbar.findViewById(R.id.job);
            AppCompatTextView gender = (AppCompatTextView) toolbar.findViewById(R.id.gender);
            AppCompatTextView born = (AppCompatTextView) toolbar.findViewById(R.id.born);
            CircleImageView profile_image = (CircleImageView) toolbar.findViewById(R.id.profile_image);
    
            final CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
            AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.app_bar);
    
            collapsingToolbarLayout.setTitle(" ");
    
            appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
                boolean isShow = false;
                int scrollRange = -1;
    
                @Override
                public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                    if (scrollRange == -1) {
                        scrollRange = appBarLayout.getTotalScrollRange();
                    }
                    if (scrollRange + verticalOffset == 0) {
                        collapsingToolbarLayout.setTitle("MIS");
                        isShow = true;
                    } else if(isShow) {
                        collapsingToolbarLayout.setTitle(" "); //carefull there should a space between double quote otherwise it wont work
                        isShow = false;
                    }
                }
            });
    
            /*mAdView = (AdView) findViewById(R.id.adView);
            AdRequest adRequest = new AdRequest.Builder().build();
            mAdView.loadAd(adRequest);
            */
    
            //Fetching email from shared preferences
            SharedPreferences myPrefs = this.getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
            String uName = myPrefs.getString(Config.USERNAME_SHARED_PREF,"");
    
            name.setText(uName);
    
            FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    /*Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();
                            */
                    logout();
                }
            });
        }
    
        //Logout function
        private void logout(){
            //Creating an alert dialog to confirm logout
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
            alertDialogBuilder.setMessage("Are you sure you want to logout?");
            alertDialogBuilder.setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
    
                            //Getting out sharedpreferences
                            SharedPreferences preferences = getSharedPreferences(Config.SHARED_PREF_NAME,Context.MODE_PRIVATE);
                            //Getting editor
                            SharedPreferences.Editor editor = preferences.edit();
    
                            //Puting the value false for loggedin
                            editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, false);
    
                            //Putting blank value to email
                            editor.putString(Config.USERNAME_SHARED_PREF, "");
    
                            //Saving the sharedpreferences
                            editor.commit();
    
                            //Starting login activity
                            Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
                            startActivity(intent);
                            finish();
                        }
                    });
    
            alertDialogBuilder.setNegativeButton("No",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
    
                        }
                    });
    
            //Showing the alert dialog
            AlertDialog alertDialog = alertDialogBuilder.create();
            alertDialog.show();
    
        }
    }
    

    这是我的配置:

    public class Config {
        //URL to our login.php file
        public static final String LOGIN_URL = "";
    
        //Keys for email and password as defined in our $_POST['key'] in login.php
        public static final String KEY_EMAIL = "username";
        public static final String KEY_PASSWORD = "password";
    
        //If server response is equal to this that means login is successful
        public static final String LOGIN_SUCCESS = "success";
    
        //Keys for Sharedpreferences
        //This would be the name of our shared preferences
        public static final String SHARED_PREF_NAME = "mis_app";
    
        //This would be used to store the email of current logged in user
        public static final String USERNAME_SHARED_PREF = "username";
    
        //We will use this to store the boolean in sharedpreference to track user is loggedin or not
        public static final String LOGGEDIN_SHARED_PREF = "loggedin";
    }
    

    运行项目并单击“登录”按钮后,我在logcat中收到此错误:

      

    引起:java.lang.NullPointerException:尝试调用虚方法&#39; void android.widget.TextView.setText(java.lang.CharSequence)&#39;在空对象引用上

    错误在 uName 字符串中,我不知道这里发生了什么。
    有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:0)

获取空指针异常的原因是您将数据保存到MainActivity的SharedPreferences并尝试从另一个活动的SharedPreferences,plesase try语句而不是您的语句中检索。

@RequestMapping(value = "/events", method = RequestMethod.GET)
public List<Event> getEvents() {
    return eventRepo.findAllByUserId(1L);
}

答案 1 :(得分:0)

最后我解决了这个问题。

  1. 我更改了此代码:

    AppCompatTextView name =(AppCompatTextView)toolbar.findViewById(R.id.name);         AppCompatTextView job =(AppCompatTextView)toolbar.findViewById(R.id.job);         AppCompatTextView gender =(AppCompatTextView)toolbar.findViewById(R.id.gender);         AppCompatTextView born =(AppCompatTextView)toolbar.findViewById(R.id.born);         CircleImageView profile_image =(CircleImageView)toolbar.findViewById(R.id.profile_image);

  2. 成:

    AppCompatTextView toolbar_name = (AppCompatTextView) toolbar.findViewById(R.id.name);
            AppCompatTextView toolbar_job = (AppCompatTextView) toolbar.findViewById(R.id.job);
            AppCompatTextView toolbar_gender = (AppCompatTextView) toolbar.findViewById(R.id.gender);
            AppCompatTextView toolbar_born = (AppCompatTextView) toolbar.findViewById(R.id.born);
            CircleImageView toolbar_profile_image = (CircleImageView) toolbar.findViewById(R.id.profile_image);
    

    然后在它下面添加了这段代码:

    AppCompatTextView name = (AppCompatTextView)findViewById(R.id.name);
            AppCompatTextView job = (AppCompatTextView)findViewById(R.id.job);
            AppCompatTextView gender = (AppCompatTextView)findViewById(R.id.gender);
            AppCompatTextView born = (AppCompatTextView)findViewById(R.id.born);
            CircleImageView profile_image = (CircleImageView)findViewById(R.id.profile_image);
    

    瞧!错误消失了。