2017-06-11 99 views
-3

我有2個活動,並在我的Android項目1的配置文件:Android的SharedPreferences返回空對象引用

  1. LoginActivity
  2. MainActivity
  3. 配置

這裏是我的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:嘗試在空對象引用上調用虛擬方法'void android.widget.TextView.setText(java.lang.CharSequence)'

錯誤在uName字符串,我不知道這裏發生了什麼。
有人可以幫我嗎?

+0

您是否嘗試手動設置'uName'字符串?你是否檢查LoginActivity類中的'username'是否有值? – andre3wap

+0

是的,我已經完成了。使用Toast.makeText(LoginActivity.this,用戶名,Toast.LENGTH_LONG).show();顯示用戶名的價值。該值與我在用戶名文本字段中鍵入的值完全相同。 –

回答

0

獲取空指針異常的原因是,您將數據保存到MainActivity的SharedPreferences並嘗試從另一個活動的SharedPreferences檢索,而不是您的plesase try語句。

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); 
+0

我應該在哪裏編碼?登錄或MainActivity? –

+0

他們兩個,我的意思是無論你定義SharedPreferences實例 – aydinugur

+0

好吧,我會嘗試它。謝謝。 –

0

最後我解決了這個問題。

  1. 我改變此代碼:

    AppCompatTextView名稱=(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);

到:

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); 

瞧!錯誤消失了。