如何在Sharedpreferene中存储JSON返回值

时间:2016-03-07 13:49:48

标签: android json android-sharedpreferences

我收到Android应用程序崩溃问题。实际上我试图在Android应用程序的sharedPreference中存储json返回值。哪个没有错误,但应用程序仍在继续崩溃,我尝试多次卸载应用程序并且没有进展。我不知道错误,再次我是新的共享首选项,实际上这个应用程序在我更改之前使用了sqllite。 我试图在sharedpreferance中存储json返回数据,这是我的loginActivity文件:

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

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

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

import java.util.HashMap;
import java.util.Map;

import info.androidhive.loginandregistration.R;
import info.androidhive.loginandregistration.app.AppConfig;
import info.androidhive.loginandregistration.app.AppController;
import info.androidhive.loginandregistration.helper.SQLiteHandler;
import info.androidhive.loginandregistration.helper.SessionManager;

public class LoginActivity extends Activity {
    private static final String TAG = RegisterActivity.class.getSimpleName();
    private Button btnLogin;
    private Button btnLinkToRegister;
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);

        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

        // SQLite database handler
        db = new SQLiteHandler(getApplicationContext());

        // Session manager
        session = new SessionManager(getApplicationContext());

        // Check if user is already logged in or not
        if (session.isLoggedIn()) {
            // User is already logged in. Take him to main activity
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }

        // Login button Click Event
        btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                // Check for empty data in the form
                if (!email.isEmpty() && !password.isEmpty()) {
                    // login user
                    checkLogin(email, password);
                } else {
                    // Prompt user to enter credentials
                    Toast.makeText(getApplicationContext(),
                            "Please enter the credentials!", Toast.LENGTH_LONG)
                            .show();
                }
            }

        });

        // Link to Register Screen
        btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        RegisterActivity.class);
                startActivity(i);
                finish();
            }
        });

    }

    /**
     * function to verify login details in mysql db
     * */
    private void checkLogin(final String email, final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_login";

        pDialog.setMessage("Logging in ...");
        showDialog();

        StringRequest strReq = new StringRequest(Method.POST,
                AppConfig.URL_LOGIN, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    // Check for error node in json
                    if (!error) {
                        // user successfully logged in
                        // Create login session
                        session.checkLogin();

                        // Now store the user in SQLite
                        String uid = jObj.getString("uid");

                        JSONObject user = jObj.getJSONObject("user");
                        int id   =   user.getInt("id");
                        String name = user.getString("name");
                        String email = user.getString("email");
                        String status = user.getString("status");

                        session.createLoginSession(email,password,id);
                        Intent intent = new Intent(LoginActivity.this,
                                MainActivity.class);
                        intent.putExtra("status",status);
                        startActivity(intent);
                        finish();
                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("email", email);
                params.put("password", password);

                return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
}

SessionManager 是:

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;

import java.util.HashMap;

import info.androidhive.loginandregistration.activity.LoginActivity;

public class SessionManager {
    // LogCat tag
    private static String TAG = SessionManager.class.getSimpleName();
    // Shared Preferences
    SharedPreferences pref;
    Editor editor;
    Context _context;
    // Shared pref mode
    int PRIVATE_MODE = 1;

    // Shared preferences file name
    private static final String PREF_NAME = "OnlineShop";
    private static final String KEY_IS_LOGGED_IN = "isLoggedIn";
    // Email address (make variable public to access from outside)
    public static final String KEY_EMAIL = "email";

    // Password (make variable public to access from outside)
    public static final String KEY_PASS = "password";

    //ID userid for the session
    public static final String KEY_ID="uid";



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

    /**
     * Create login session
     * */
    public void createLoginSession(String email, String password, int uid){
        // Storing login value as TRUE
        editor.putBoolean(KEY_IS_LOGGED_IN, true);

        // Storing email in pref
        editor.putString(KEY_EMAIL, email);

        // Storing password in pref
        editor.putString(KEY_PASS, password);

        //Storing userid uid in pref
        editor.putInt(KEY_ID, uid);
        // commit changes
        editor.commit();
    }

/*  public void setLogin(boolean isLoggedIn) {
        editor.putBoolean(KEY_IS_LOGGED_IN, isLoggedIn);
        editor.commit();
        Log.d(TAG, "User login session modified!");
    }
    */
    /**
     * Check login method wil check user login status
     * If false it will redirect user to login page
     * Else won't do anything
     * */
    public void checkLogin(){
        // Check login status
        if(!this.isLoggedIn()){
            // user is not logged in redirect him to Login Activity
            Intent i = new Intent(_context, LoginActivity.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);
        }

    }
    /**
     * Get stored session data
     * */
    public HashMap<String, String> getUserDetails(){
        HashMap<String, String> user = new HashMap<String, String>();
        // user email
        user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));

        // user password
        user.put(KEY_PASS, pref.getString(KEY_PASS, null));

        //user id
        user.put(KEY_ID, pref.getString(KEY_ID, null));
        // return user
        return user;
    }

    /**
     * Clear session details
     * */
    public void logoutUser(){
        // Clearing all data from Shared Preferences
        editor.clear();
        editor.commit();

        // After logout redirect user to Loing Activity
        Intent i = new Intent(_context, LoginActivity.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);
    }


    public boolean isLoggedIn(){

        return pref.getBoolean(KEY_IS_LOGGED_IN, true);
    }
}

错误

03-07 19:26:27.643 1795-1795/? E/AndroidRuntime: FATAL EXCEPTION: main Process: 
info.androidhive.loginandregistration, 
PID: 1795 java.lang.RuntimeException: 
Unable to start activity ComponentInfo{info.androidhive.loginandregistration/info.androidhive.loginandreg‌​istration.activity.MainActivity}: 
        java.lang.NullPointerException: Attempt to invoke virtual method 
        'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference

2 个答案:

答案 0 :(得分:0)

这与在SharedPreferences中存储JSON值无关。崩溃发生的原因不同。在您的MainActivity中,您正在尝试读取Bundle的内容,特别是“status”的值,但问题是您在调用MainActivity时并不总是会添加额外的值,并且很可能您不检查在尝试阅读它之前是否为null。在一个地方你可以调用它:

Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);

和另一个:

Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("status",status);
startActivity(intent);

因此,在MainActivity中实现一些正确的错误处理,你应该摆脱这种崩溃。

答案 1 :(得分:0)

        public class SharedPreference {
            private SharedPreferences mPrefs;
            private Context mContext;
            private String KEY = "KEY";
            private String JSONKEY = "JSONKEY";


            public SharedPreference(Context mContext) {
                this.mContext = mContext;
                mPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
            }

        // for saving list in JSON format
            public boolean setList(List<String> list)
            {
                SharedPreferences.Editor prefsEditor = mPrefs.edit();
                Gson gson = new Gson();
                String json = gson.toJson(list);
                prefsEditor.putString(KEY, json);
                return prefsEditor.commit();
            }
        // get list from json format
            public List<String> getList()
            {
                Gson gson = new Gson();
                String json = mPrefs.getString(KEY, "");
                Type type = new TypeToken<ArrayList<String>>() {}.getType();
                return gson.fromJson(json,type);
            }


        // Set Json
            public boolean setJson(JSONObject json)
            {
                SharedPreferences.Editor prefsEditor = mPrefs.edit();
                String jsonString = json.toString();
                prefsEditor.putString(JSONKEY, jsonString);
                return prefsEditor.commit();
            }

        // get json
            public JSONObject getJson() throws JSONException {
                Gson gson = new Gson();
                String json = mPrefs.getString(JSONKEY, "");

                return new JSONObject(json);
            }


        }

你应该得到如下的字符串,以避免空指针异常

// string can be null
   String status = getIntent().getStringExtra("status");

if(status!= null)
{
// do your work here
}