如何实现 SHARED PREFERENCE (java, sql database LOGIN)

how to implement SHARED PREFERENCE (java, sql database LOGIN)

大家好,我得到了一个登录名 activity,它通过服务器检查用户名和密码以对用户进行身份验证。我想使用 sharedpermissions 来存储用户名和密码,这样用户就不会每次都登录。我还想创建一个登录按钮。 我试图实现它,但它只是跳过登录活动并将我带到我的第二个 activity。我留下了一些共享权限代码作为评论 (//)

谁能show/tell我能做到最好吗?

public class LoginActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);


    //String username = "";
    //String password = "";
    //SharedPreferences pre;


    final EditText etUsername = (EditText) findViewById(R.id.etUsername);
    final EditText etPassword = (EditText) findViewById(R.id.etPassword);
    final TextView tvRegisterLink = (TextView) findViewById(R.id.tvRegisterhere);
    final Button bLogin = (Button) findViewById(R.id.bLogin);

    if(TextUtils.isEmpty(etUsername.getText().toString())||TextUtils.isEmpty(etPassword.getText().toString())){
        Intent intent = new Intent(LoginActivity.this, UserAreaActivity.class);
        LoginActivity.this.startActivity(intent);
    } else {
        Intent registerIntent = new Intent(LoginActivity.this, LoginActivity.class);
        LoginActivity.this.startActivity(registerIntent);
    }




    final String username1 = SharedPreferenceUtils.getUsername(this);
    final String password1 = SharedPreferenceUtils.getPassword(this);

    // pre = getSharedPreferences("pref",MODE_PRIVATE);
    //if(pre.getBoolean("username",true) && pre.getBoolean("password",true)){













    tvRegisterLink.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
            LoginActivity.this.startActivity(registerIntent);
        }
    });

    bLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String username = etUsername.getText().toString();
            final String password = etPassword.getText().toString();


            // Response received from the server
            Response.Listener<String> responseListener = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);
                        boolean success = jsonResponse.getBoolean("success");

                        if (success) {
                            String name = jsonResponse.getString("name");
                            SharedPreferenceUtils.createSP(LoginActivity.this,username1,password1);





                            Intent intent = new Intent(LoginActivity.this, UserAreaActivity.class);
                            intent.putExtra("name", name);
                            intent.putExtra("username", username);

                            LoginActivity.this.startActivity(intent);


                        } else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
                            builder.setMessage("Login Failed")
                                    .setNegativeButton("Retry", null)
                                    .create()
                                    .show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            };

            LoginRequest loginRequest = new LoginRequest(username, password, responseListener);
            RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
            queue.add(loginRequest);






        }
    });


}

}

public class UserAreaActivity extends AppCompatActivity {

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


    final TextView etusername = (TextView) findViewById(R.id.textView2);
    final TextView etwelcome = (TextView) findViewById(R.id.textView);
    final ImageButton red = (ImageButton) findViewById(R.id.imageButton);
    final ImageButton messages = (ImageButton) findViewById(R.id.imageButton2);
    final ImageButton blue = (ImageButton) findViewById(R.id.imageButton3);
    final ImageButton ping = (ImageButton) findViewById(R.id.imageButton4);
    final TextView etuname = (TextView) findViewById(R.id.textView3);
    final Button Logout = (Button) findViewById(R.id.logout);

    //String Name = SharedPreferenceUtils.getName(this);
    //etwelcome.setText(Name);




    red.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent registerIntent = new Intent(UserAreaActivity.this, Report.class);
            UserAreaActivity.this.startActivity(registerIntent);

        }
    });

    messages.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent registerIntent = new Intent(UserAreaActivity.this, Messages.class);
            UserAreaActivity.this.startActivity(registerIntent);


        }
    });

    Logout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            boolean isClear = SharedPreferenceUtils.clearSP(UserAreaActivity.this);
            if(isClear){
                Intent registerIntent = new Intent(UserAreaActivity.this, LoginActivity.class);
                UserAreaActivity.this.startActivity(registerIntent);
            }




        }
    });

   Intent intent = getIntent();
    String name = intent.getStringExtra("name");
    String username = intent.getStringExtra("username");



    String message = "Welcome " + name;
    etwelcome.setText(message);
    etusername.setText(username);








    //Intent in = new Intent(getApplicationContext(), Messages.class);
    //in.putExtra("username", username);
    //UserAreaActivity.this.startActivity(in);

}











}

您可以在代码中使用 SharedPreferences

试试这个。

public class SharedPreferenceUtils {

    private static final String SP_NAME = "sp";
    public static final String USERNAME = "username";
    public static final String PASSWORD = "password";


    // create
    public static boolean createSP(Context context, String username, String password) {
        SharedPreferences.Editor editor = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE).edit();
        editor.putString(USERNAME, username);
        editor.putString(PASSWORD, password);
        return editor.commit();
    }

    // clear
    public static boolean clearSP(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        return editor.clear().commit();
    }

    // get access info
    public static String getUsername(Context context) {
        SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        return sp.getString(USERNAME, "");
    }
    // get branch info
    public static String getPassword(Context context) {
        SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        return sp.getString(PASSWORD, "");
    }
}

LoginActivity中使用

SharedPreferenceUtils.createSP(this,username,password);

并用于其他Activity

String username = SharedPreferenceUtils.getUsername(this);
String password = SharedPreferenceUtils.getPassword(this);

编辑

if (success) {
      String name = jsonResponse.getString("name");
      SharedPreferenceUtils.createSP(this, username, password);
}

编辑

private EditText etUsername, etPassword;

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

    etUsername = (EditText) findViewById(R.id.etUsername);
    etPassword = (EditText) findViewById(R.id.etPassword);

    String username = SharedPreferenceUtils.getUsername(this);
    String password = SharedPreferenceUtils.getPassword(this);
    etUsername.setText(username);
    etPassword.setText(password);
}

编辑

 if(TextUtils.isEmpty(etUsername.getText().toString())||TextUtils.isEmpty(etPassword.getText().toString())){
        Intent intent = new Intent(LoginActivity.this, A.class);
        LoginActivity.this.startActivity(intent);
 } else {
        Intent registerIntent = new Intent(LoginActivity.this, B.class);
        LoginActivity.this.startActivity(intent);
 }

编辑

boolean isClear = SharedPreferenceUtils.clearSP(UserAreaActivity.this);
if(isClear){
        Intent registerIntent = new Intent(UserAreaActivity.this, LoginActivity.class);
        UserAreaActivity.this.startActivity(registerIntent);
}