Sharedpreferences不保存用户数据

时间:2019-05-04 16:21:24

标签: php android login sharedpreferences

我正在创建一个android app来测试我有registrationlogin的位置。

用户注册时,他输入NameSurnameUsername

我将您的数据保存在shared preferences中,并在“家庭活动”中显示它们。

用户注销后,他必须登录才能登录。在login表单中,用户必须仅输入username

通过身份验证后,“家庭活动”中应该有您的信息,但是您只能看到其Username,而NameSurname则看不到。

您能帮我理解为什么在您login时它不能显示所有数据吗?

登录活动

public class MainActivity extends AppCompatActivity {

    private Button login, registrazione;
    private EditText username;

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

       login = (Button)findViewById(R.id.button2);
       registrazione = (Button)findViewById(R.id.button);
       username = (EditText)findViewById(R.id.editText5);

        if (SharedPref.getInstance(this).isLoggedIn()) {
            startActivity(new Intent(this, Home.class));
            finish();
        }

       registrazione.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               Intent intent = new Intent(getApplicationContext(),RegisterR.class);
               startActivity(intent);
           }
       });

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                validateUserData();
            }
        });



    }

    private void validateUserData() {

        //first getting the values
        final String user_username = username.getText().toString();

        //checking if username is empty
        if (TextUtils.isEmpty(user_username)) {
            username.setError("Please enter your username");
            username.requestFocus();
            // Vibrate for 100 milliseconds
            login.setEnabled(true);
            return;
        }
        //checking if password is empty




        //Login User if everything is fine
        loginUser(user_username);


    }

    private void loginUser(String username) {

        //making api call
        Api api = ApiClient.getClient().create(Api.class);
        Call<Model> login = api.login(username);

        login.enqueue(new Callback<Model>() {
            @Override
            public void onResponse(Call<Model> call, Response<Model> response) {

                if(response.body().getIsSuccess() == 1){

                    String user = response.body().getUsername();
                    String user1 = response.body().getName();
                    String user2 = response.body().getSurname();


                    //storing the user in shared preferences
                    SharedPref.getInstance(MainActivity.this).storeUserName(user,user1,user2);

                    startActivity(new Intent(MainActivity.this,Home.class));
                }else{
                    Toast.makeText(MainActivity.this,response.body().getMessage(),Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<Model> call, Throwable t) {
                Toast.makeText(MainActivity.this,t.getLocalizedMessage(),Toast.LENGTH_SHORT).show();

            }
        });


    }


}

家庭活动

public class Home extends AppCompatActivity {

    private TextView nome,cognome,username;
    private Button logout;

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


        nome = (TextView)findViewById(R.id.textView);
        cognome = (TextView)findViewById(R.id.textView2);
        username = (TextView)findViewById(R.id.textView3);


        String loggedUsername = SharedPref.getInstance(this).LoggedInUser();
        username.setText("Username : "+loggedUsername);
        String loggedUsername1 = SharedPref.getInstance(this).LoggedInUser1();
        nome.setText("Name : "+loggedUsername1);
        String loggedUsername2 = SharedPref.getInstance(this).LoggedInUser2();
        cognome.setText("Name : "+loggedUsername2);

        logout = (Button)findViewById(R.id.button4);

        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                SharedPref.getInstance(getApplicationContext()).logout();
            }
        });

    }
}

SharedPref活动

public class SharedPref {

    //Storage File
    public static final String SHARED_PREF_NAME = "larnmktech";

    //Username
    public static final String USER_NAME = "username";

    public static final String NAME = "name";

    public static final String SURNAME = "surname";


    public static SharedPref mInstance;

    public static Context mCtx;



    public SharedPref(Context context) {
        mCtx = context;


    }


    public static synchronized SharedPref getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new SharedPref(context);
        }
        return mInstance;
    }


    //method to store user data
    public void storeUserName(String names, String names1, String names2) {
        SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(USER_NAME, names);
        editor.putString(NAME, names1);
        editor.putString(SURNAME, names2);

        editor.apply();
    }

    //check if user is logged in
    public boolean isLoggedIn() {
        SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        return sharedPreferences.getString(USER_NAME, null) != null;
    }


    //find logged in user
    public String LoggedInUser() {
        SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
         return  sharedPreferences.getString(USER_NAME, null);
    }
    public String LoggedInUser1() {
        SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        return  sharedPreferences.getString(NAME, null);

    }

    public String LoggedInUser2() {
        SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        return sharedPreferences.getString(SURNAME, null);


    }


    //Logout user
    public void logout() {
        SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.apply();
        mCtx.startActivity(new Intent(mCtx, MainActivity.class));
    }

}

模型活动

public class Model {
    private String name;
    private String surname;
    private String username;

    private int isSuccess;
    private String message;

    public Model(String name, String surname, String username, int isSuccess, String message) {
        this.name = name;
        this.surname = surname;
        this.username = username;
        this.isSuccess = isSuccess;
        this.message = message;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getIsSuccess() {
        return isSuccess;
    }

    public void setIsSuccess(int isSuccess) {
        this.isSuccess = isSuccess;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}

Api活动

@POST("l.php")
    @FormUrlEncoded
    Call<Model> login(@Field("username") String username);

Login.php

<?php

//getting user values
$username=$_POST['username'];

//an array of response
$output = array();

//requires database connection
require_once('db.php');

//checking if email exit
$conn=$dbh->prepare("SELECT username FROM utenti WHERE username=?");
$conn->bindParam(1,$username);
$conn->execute();
if($conn->rowCount() == 0){
$output['isSuccess'] = 0;
$output['message'] = "Username sbagliato";
}

//get the username
if($conn->rowCount() !==0){
$results=$conn->fetch(PDO::FETCH_OBJ);
//we get both the username and password
$username=$results->username;


$output['isSuccess'] = 1;
$output['message'] = "login sucessful";
$output['username'] = $username;

}
echo json_encode($output);

?>

如果有人可以帮助我,我很乐意听。

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以将用户数据保存为共享首选项,也可以使用共享首选项创建登录会话,如下所示:-

 public class AppPrefrences {

            private static SharedPreferences mPrefs;
            private static SharedPreferences.Editor mPrefsEditor;

            public static boolean isUserLoggedOut(Context ctx) {
                mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
                return mPrefs.getBoolean("id_logged_in", true);
            }

            public static void setUserLoggedOut(Context ctx, Boolean value) {
                mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
                mPrefsEditor = mPrefs.edit();
                mPrefsEditor.putBoolean("id_logged_in", value);
                mPrefsEditor.commit();
            }

        public static String getUserName(Context ctx) {
            mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
            return mPrefs.getString("userName", "");
        }

        public static void setUserName(Context ctx, String value) {
            mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
            mPrefsEditor = mPrefs.edit();
            mPrefsEditor.putString("userName", value);
            mPrefsEditor.commit();
        }

       public static void clearAllPreferences(Context ctx) {
            mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
            mPrefsEditor = mPrefs.edit();
            mPrefsEditor.clear();
            mPrefsEditor.commit();
    }
        }

,当您登录您的应用程序时,请像下面这样设置值:-

setUserLoggedOut(YourActivity.class, false);

并在启动屏幕上设置如下检查:-

if (isUserLoggedOut(StartActivity.this)) {
                    startActivity(new Intent(StartActivity.this, LoginActivity.class));
                    finish();
                } else {
                    startActivity(new Intent(StartActivity.this, MainActivity.class));
                    finish();
                }