2014-11-24 63 views
0

我想如果checkbock检查保存登录数据..应用程序崩溃时SharedPreferences被称为(NullPointerException异常)

但是当我打电话session.saveSession(user, password);应用程序崩溃...

我不知道我的错误是:(

Start.java

package de.hoell.jobcontrol; 

import android.app.Activity; 
import android.app.ProgressDialog; 
import android.content.Intent; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.Button; 
import android.widget.CheckBox; 
import android.widget.EditText; 
import android.widget.Toast; 

import org.json.JSONException; 
import org.json.JSONObject; 

import de.hoell.jobcontrol.query.Functions; 
import de.hoell.jobcontrol.session.SessionManager; 


public class Start extends Activity { 

    Button btnLogin; 
    EditText InputName; 
    EditText InputPass; 
    CheckBox InputCheck; 
    public static String user; 
    private String password; 
    SessionManager session; 


    // JSON Node names 
    private static final String TAG_SUCCESS = "success"; 
    private static final String TAG_ERROR = "error"; 
    private static final String TAG_MESSAGE = "message"; 





    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_start); 

     //Importing all assets like buttons, text fields 
     InputName = (EditText) findViewById(R.id.login_name); 
     InputPass = (EditText) findViewById(R.id.login_pass); 
     btnLogin = (Button) findViewById(R.id.button); 
     InputCheck = (CheckBox) findViewById(R.id.checkBox); 

     btnLogin.setOnClickListener(new View.OnClickListener() 
     { 
      @Override 
      public void onClick(View view) 
      { 
      new JSONLogin().execute(); 
      } 
     }); 

    } 
    private class JSONLogin extends AsyncTask<String, String, JSONObject> { 
     private ProgressDialog pDialog; 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 

      pDialog = new ProgressDialog(Start.this); 
      pDialog.setMessage("Sending Data ..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(true); 
      pDialog.show(); 
     } 
     @Override 
     protected JSONObject doInBackground(String... args) { 

      user = InputName.getText().toString(); 
      password = InputPass.getText().toString(); 

      Functions Function = new Functions(); 
      JSONObject json = Function.loginUser(user, password); 

      // check for login response 
      // check log cat fro response 
      Log.d("Create Response", json.toString()); 
      return json; 
     } 
     @Override 
     protected void onPostExecute(JSONObject json) { 
      pDialog.dismiss(); 
      try { 
       int success = json.getInt(TAG_SUCCESS); 

       if (success == 1) { 
        // successfully logged in 

        if (InputCheck.isChecked()){ 

         System.out.println("Checkbox is gesetz daten werden gespeichert "); 

         session.saveSession(user, password); 
        } 
        else{ 
         System.out.println("Checkbox is leer daten werden NICHT gespeichert"); 
        } 

        Intent i = new Intent(getApplicationContext(), MainActivity.class); 
        startActivity(i); 


        // closing this screen 
        finish(); 
       } else { 
        Toast.makeText(getApplicationContext(), "Falscher Login-Name/Falsches Passwort!!!", Toast.LENGTH_SHORT).show(); 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 








    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 

     getMenuInflater().inflate(R.menu.start, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 
     if (id == R.id.action_info) { 
      Toast.makeText(getApplicationContext(), "Version 0.0.6", Toast.LENGTH_SHORT).show(); 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 



} 

会议Manager.java

package de.hoell.jobcontrol.session; 

import android.content.Context; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import java.util.HashMap; 


import de.hoell.jobcontrol.MainActivity; 
import de.hoell.jobcontrol.Start; 

/** 
* Created by Hoell on 21.11.2014. 
*/ 
public class SessionManager { 




     // Shared Preferences reference 
     SharedPreferences pref; 

     // Editor reference for Shared preferences 
     SharedPreferences.Editor editor; 

     // Context 
     Context _context; 

     // Shared pref mode 
     int PRIVATE_MODE = 0; 

     // Sharedpref file name 
     private static final String PREFER_NAME = "AndroidExamplePref"; 

     // All Shared Preferences Keys 
     private static final String IS_USER_LOGIN = "IsUserLoggedIn"; 

     // User name (make variable public to access from outside) 
     public static final String KEY_USER = "user"; 

     // Email address (make variable public to access from outside) 
     public static final String KEY_PWD = "pwd"; 

     // Constructor 
     public SessionManager(Context context){ 
      this._context = context; 
      pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE); 
      editor = pref.edit(); 
     } 



    //Create login session 
     public void saveSession(String user, String pwd){ 
      // Storing login value as TRUE 
      editor.putBoolean(IS_USER_LOGIN, true); 

      // Storing user in pref 
      editor.putString(KEY_USER, user); 

      // Storing pwd in pref 
      editor.putString(KEY_PWD, pwd); 

      // commit changes 
      editor.commit(); 
      System.out.println("Daten gespeichert:"+user + pwd); 
     } 

     /** 
     * Check login method will check user login status 
     * If false it will redirect user to login page 
     * Else do anything 
     * */ 
     public boolean checkLogin(){ 
      // Check login status 
      if(!this.isUserLoggedIn()){ 

       // user is not logged in redirect him to Login Activity 
       Intent i = new Intent(_context, Start.class); 

       // Closing all the Activities from stack 
       i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

       // Add new Flag to start new Activity 
       i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

       // Staring Login Activity 
       _context.startActivity(i); 

       return true; 
      } 
      return false; 
     } 



     /** 
     * Get stored session data 
     * */ 
     public HashMap<String, String> getUser(){ 

      //Use hashmap to store user credentials 
      HashMap<String, String> user = new HashMap<String, String>(); 

      // user name 
      user.put(KEY_USER, pref.getString(KEY_USER, null)); 

      // user email id 
      user.put(KEY_PWD, pref.getString(KEY_PWD, null)); 


      // return user 
      return user; 
     } 

     /** 
     * Clear session details 
     * */ 
     public void logoutUser(){ 

      // Clearing all user data from Shared Preferences 
      editor.clear(); 
      editor.commit(); 

      // After logout redirect user to Login Activity 
      Intent i = new Intent(_context,Start.class); 

      // Closing all the Activities 
      i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

      // Add new Flag to start new Activity 
      i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

      // Staring Login Activity 
      _context.startActivity(i); 
     } 


     // Check for login 
     public boolean isUserLoggedIn(){ 
      return pref.getBoolean(IS_USER_LOGIN, false); 
     } 
} 

logcat的

11-24 09:56:31.222  417-1662/de.hoell.myfirstapp E/JSON﹕ {"tag":"login","success":1,"error":0,"message":"erfolgreich eingelogt!"} 
11-24 09:56:31.232  417-1662/de.hoell.myfirstapp D/Create Response﹕ {"message":"erfolgreich eingelogt!","error":0,"success":1,"tag":"login"} 
11-24 09:56:31.262  417-417/de.hoell.myfirstapp I/System.out﹕ Checkbox is gesetz daten werden gespeichert 
11-24 09:56:31.262  417-417/de.hoell.myfirstapp D/AndroidRuntime﹕ Shutting down VM 
11-24 09:56:31.262  417-417/de.hoell.myfirstapp W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4180cda0) 
11-24 09:56:31.262  417-417/de.hoell.myfirstapp E/AndroidRuntime﹕ FATAL EXCEPTION: main 
    Process: de.hoell.myfirstapp, PID: 417 
    java.lang.NullPointerException 
      at de.hoell.jobcontrol.Start$JSONLogin.onPostExecute(Start.java:104) 
      at de.hoell.jobcontrol.Start$JSONLogin.onPostExecute(Start.java:65) 
      at android.os.AsyncTask.finish(AsyncTask.java:632) 
      at android.os.AsyncTask.access$600(AsyncTask.java:177) 
      at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645) 
      at android.os.Handler.dispatchMessage(Handler.java:102) 
      at android.os.Looper.loop(Looper.java:157) 
      at android.app.ActivityThread.main(ActivityThread.java:5356) 
      at java.lang.reflect.Method.invokeNative(Native Method) 
      at java.lang.reflect.Method.invoke(Method.java:515) 
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265) 
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081) 
      at dalvik.system.NativeStart.main(Native Method) 

回答

3

你永远intialize SessionManager。在新增的onCreate

session = new SessionManager(this); 

开始AsyncTask

+0

这就是我所讲的有关! – 2014-11-24 09:02:07

+1

非常感谢:) 我很愚蠢...... sry – TrooperMaXX 2014-11-24 09:05:26

0

之前,这是一个NullPointerException

session.saveSession(user, password); 

在代码中,你已经宣布会议,但不初始化它。所以它抛出的空指针异常

在使用它之前,您需要初始化变量会话。

session = new SessionManager(getApplicationContext()); 

这将解决问题。

+0

thx对于很好的解释:) – TrooperMaXX 2014-11-24 09:15:07

0

使用之前,你必须初始化SessionManager对象SessionManager类的任何方法:

例子:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_start); 

     //Importing all assets like buttons, text fields 
     InputName = (EditText) findViewById(R.id.login_name); 
     InputPass = (EditText) findViewById(R.id.login_pass); 
     btnLogin = (Button) findViewById(R.id.button); 
     InputCheck = (CheckBox) findViewById(R.id.checkBox); 

     session = new SessionManager(this); 

     btnLogin.setOnClickListener(new View.OnClickListener() 
     { 
      @Override 
      public void onClick(View view) 
      { 
      new JSONLogin().execute(); 
      } 
     }); 

} 
+0

我dind't需要鳕鱼,但非常感谢你:) – TrooperMaXX 2014-11-24 09:15:55

+0

@ TrooperMaXX,NP祝你好运。 – 2014-11-24 09:16:53

相关问题