共享偏好,它们去哪里了?

时间:2016-04-21 12:00:26

标签: android preferences shared

我知道共享偏好如何工作但我不知道在下面的代码中插入代码的位置以保存用户数据。我有一个登录,后台任务完成所有工作和注册。我希望应用程序打开用户登录时的启动页面。可以从其他答案中找出答案

Login.java

/Dist

Register.java

*.cs

BackgroundTask.java

Button bttnLogin;
EditText loginEmail, loginPassword;
TextView regLink;
AlertDialog.Builder alert;


@Override
protected void onCreate(Bundle savedInstanceState)
{

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    loginEmail = (EditText) findViewById(R.id.email);
    loginPassword = (EditText) findViewById(R.id.password);

    regLink = (TextView) findViewById(R.id.regLink);
    regLink.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            startActivity(new Intent(Login.this, Register.class));

        }
    });


    bttnLogin = (Button) findViewById(R.id.bttnLogin);
    bttnLogin.setOnClickListener(new View.OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            if (loginEmail.getText().toString().equals("") || loginPassword.getText().toString().equals(""))
            {
                alert = new AlertDialog.Builder(Login.this);
                alert.setTitle("Login Failed");
                alert.setMessage("Try again");
                alert.setPositiveButton("OK", new DialogInterface.OnClickListener()
                {

                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {

                        dialog.dismiss();
                    }

                });

                AlertDialog alertDialog = alert.create();
                alertDialog.show();
            } else  //if user provides proper data
            {
                BackgroundTask backgroundTask = new BackgroundTask(Login.this);
                backgroundTask.execute("login", loginEmail.getText().toString(), loginPassword.getText().toString());
            }

        }


    });

启动画面我希望应用程序打开

        private Button regButton;
        public EditText regName;
        public EditText regEmail;
        public EditText regPassword;
        public EditText conPassword;
        private AlertDialog.Builder alert;



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

    regName = (EditText) findViewById(R.id.name);
    regEmail = (EditText) findViewById(R.id.email);
    regPassword = (EditText) findViewById(R.id.password);
    conPassword = (EditText) findViewById(R.id.conPassword);
    regButton = (Button) findViewById(R.id.regButton);
    regButton.setOnClickListener(this);
}


@Override
public void onClick(View v)
{

    if (regName.getText().toString().equals("") || regEmail.getText().toString().equals("") ||  regPassword.getText().toString().equals("") || conPassword.getText().toString().equals(""))
    {
        alert = new AlertDialog.Builder(Register.this);
        alert.setTitle("Something not quite right");
        alert.setMessage("Please fill in all the fields");
        alert.setPositiveButton("OK", new DialogInterface.OnClickListener()
        {

            @Override
            public void onClick(DialogInterface dialog, int which)
            {

                dialog.dismiss();
            }

        });

        AlertDialog alertDialog = alert.create();
        alertDialog.show();

    } else if (!(regPassword.getText().toString().equals(conPassword.getText().toString())))
    {

        alert = new AlertDialog.Builder(Register.this);
        alert.setTitle("Passwords do not match");
        alert.setMessage("Try Again");
        alert.setPositiveButton("OK", new DialogInterface.OnClickListener()
        {

            @Override
            public void onClick(DialogInterface dialog, int which)
            {

                dialog.dismiss();

                conPassword.setText("");
                regPassword.setText("");
            }

        });

        AlertDialog alertDialog = alert.create();
        alertDialog.show();


    }
    else //if user provides proper data
    {
        BackgroundTask backgroundTask = new BackgroundTask(Register.this);
        backgroundTask.execute("register", regName.getText().toString(), regEmail.getText().toString()
                , regPassword.getText().toString(), conPassword.getText().toString());
    }

4 个答案:

答案 0 :(得分:1)

这是我在SharedPreferences

的每个Android应用中使用的内容
import android.content.Context;
import android.content.SharedPreferences;

/**
 * Created by Jimit Patel on 30/07/15.
 */
public class Prefs {

    private static final String TAG = Prefs.class.getSimpleName();

    private static final String MY_APP_PREFS = "my_app";

    /**
     * <p>Provides Shared Preference object</p>
     * @param context
     * @return
     */
    private static SharedPreferences getPrefs(Context context) {
        return context.getSharedPreferences(MY_APP_PREFS, Context.MODE_PRIVATE);
    }

    /**
     * <p>Saves a string value for a given key in Shared Preference</p>
     * @param context
     * @param key
     * @param value
     */
    public static void setString(Context context, String key, String value) {
        getPrefs(context).edit().putString(key, value).apply();
    }

    /**
     * <p>Saves integer value for a given key in Shared Preference</p>
     * @param context
     * @param key
     * @param value
     */
    public static void setInt(Context context, String key, int value) {
        getPrefs(context).edit().putInt(key, value).apply();
    }

    /**
     * <p>Saves float value for a given key in Shared Preference</p>
     * @param context
     * @param key
     * @param value
     */
    public static void setFloat(Context context, String key, float value) {
        getPrefs(context).edit().putFloat(key, value).apply();
    }

    /**
     * <p>Saves long value for a given key in Shared Preference</p>
     * @param context
     * @param key
     * @param value
     */
    public static void setLong(Context context, String key, long value) {
        getPrefs(context).edit().putLong(key, value).apply();
    }

    /**
     * <p>Saves boolean value for a given key in Shared Preference</p>
     * @param context
     * @param key
     * @param value
     */
    public static void setBoolean(Context context, String key, boolean value) {
        getPrefs(context).edit().putBoolean(key, value).apply();
    }

    /**
     * Provides string from the Shared Preferences
     * @param context
     * @param key
     * @param defaultValue
     * @return
     */
    public static String getString(Context context, String key, String defaultValue) {
        return getPrefs(context).getString(key, defaultValue);
    }

    /**
     * Provides int from Shared Preferences
     * @param context
     * @param key
     * @param defaultValue
     * @return
     */
    public static int getInt(Context context, String key, int defaultValue) {
        return getPrefs(context).getInt(key, defaultValue);
    }

    /**
     * Provides boolean from Shared Preferences
     * @param context
     * @param key
     * @param defaultValue
     * @return
     */
    public static boolean getBoolean(Context context, String key, boolean defaultValue) {
        return getPrefs(context).getBoolean(key, defaultValue);
    }

    /**
     * Provides float value from Shared Preferences
     * @param context
     * @param key
     * @param defaultValue
     * @return
     */
    public static float getFloat(Context context, String key, float defaultValue) {
        return getPrefs(context).getFloat(key, defaultValue);
    }

    /**
     * Provides long value from Shared Preferences
     * @param context
     * @param key
     * @param defaultValue
     * @return
     */
    public static long getLong(Context context, String key, long defaultValue) {
        return getPrefs(context).getLong(key, defaultValue);
    }

    public static void clearPrefs(Context context) {
        getPrefs(context).edit().clear().commit();
    }
}

使用它你只需使用它中的那些功能

答案 1 :(得分:0)

从服务器收到登录成功后,请执行以下代码

SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);    
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("hasLoggedIn", true);
editor.commit();

无论您想要检查用户是否已登录,都可以使用以下代码进行检查。

boolean hasLoggedIn = sharedpreferences.getBoolean("hasLoggedIn", false);

如果 hasLogged 布尔值为true,则表示用户已登录。

答案 2 :(得分:0)

只需创建一个名为SessionManagement.java的类并粘贴以下代码

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

/**
* Created by naveen.tp on 21/4/2016.
*/
public class SessionManagement {

SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
Context context;

int PRIVATE_MODE = 0;

private static final String PREF_NAME = "YourPreferences";

private static final String IS_LOGIN = "isLogedIn";

//Constructor
public SessionManagement(Context context) {

    this.context = context;
    sharedPreferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    editor = sharedPreferences.edit();
}


//Create Login Session
public void createLoginSession(boolean flag)
{
    editor.putBoolean(IS_LOGIN, flag);
    editor.commit();
}

//check for isLogin returns True/false
public boolean isLoggedIn()
{
    return sharedPreferences.getBoolean(IS_LOGIN, false);
}

}

在您的代码BackgroundTask.java onPostExcecute方法

<强> EDITED

else if(code.equals("login_true"))
{
 SessionManagement session = new SessionManagement(context);
 session.createLoginSession(true);
 Toast.makeText(context, "You are logged in", Toast.LENGTH_LONG).show();
 Intent intent = new Intent(activity, SplashScreen.class);
 activity.startActivity(intent);
}

您也可以通过调用

在下次启动画面中检查登录状态

<强> EDITED

SessionManagement session = new SessionManagement(this); 
boolean isLogin = session.isLoggedIn();
if(isLogin)
{
  //Already logged in
}
else
{
  //Not logged in
}

希望能帮到你!

答案 3 :(得分:0)

您创建的共享首选方法并保存

您可以使用此代码......对您有帮助

savaLoginValue(mobileno,password,userTypeId,clientid);

&#13;
&#13;
jar
&#13;
&#13;
&#13;

BackgoundTask.Class

&#13;
&#13;
private void savaLoginValue(String mobileno, String password) 
{
        SharedPreferences login = getSharedPreferences("Preferance", MODE_PRIVATE);
        SharedPreferences.Editor editor = login.edit();
        editor.putString("SPMobileno", mobileno);
        editor.putString("SPPass", password);
        editor.commit();
}
&#13;
&#13;
&#13;