调用SharedPreferences时应用程序崩溃(NullPointerException)

时间:2014-11-24 08:59:23

标签: android nullpointerexception sharedpreferences

如果选中了checkbock,我想保存登录数据。

但是当我拨打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);
    }



}

SessionManager.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 个答案:

答案 0 :(得分:3)

你永远不会初始化SessionManager。在onCreate中添加

 session = new SessionManager(this);

在开始AsyncTask

之前

答案 1 :(得分:0)

这是NullPointerException

session.saveSession(user, password);

在您的代码中,您已声明会话,但已初始化。所以它抛出空指针异常

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

session = new SessionManager(getApplicationContext());

这将解决问题。

答案 2 :(得分: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();
            }
        });

}