问题
my question is the extension of this question here but in this question I added two function which are :
- SharedPreferences
- Remember me function (Checkbox)
Currently, I managed to login with/without remember me checkbox and intent the rest of the JSON Object fetch from mysql database.
But the problem is inside LoginActivity.java PART A block . When I restart/rebuild the apps, the intent data is null which is not stored and sent into next activity. The data could not be stored and sent into next activity when it automatically logged in. The code as below
JSON Object
{
"access":"PA001",
"password":"123",
"fullname":"ARCADE",
"branch":"HQ",
"section":"MPR"
}
access.php
<?php
$conn = mysqli_connect("","","","");
if(
isset($_POST['access']) &&
isset($_POST['password'])
){
$access = $_POST['access'];
$password = $_POST['password'];
$sql = "SELECT * FROM table WHERE access = '$access' AND password = '$password' ";
$result = mysqli_query($conn, $sql);
if($result && mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
$accessdb = $row['access'];
$passworddb = $row['password'];
$fullnamedb = $row['fullname'];
$branchdb = $row['branch'];
$sectiondb = $row['section'];
echo "success_access";
$response = array('access' => $accessdb, 'password' => $passworddb, 'fullname' => $fullnamedb, 'branch' => $branchdb, 'section' => $sectiondb);
echo json_encode($response);
}
mysqli_free_result($result);
} else {
echo "access_failed";
}
}
?>
LoginActivity.java
public class LoginActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
final String TAG = this.getClass().getName();
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
EditText etLogin, etPassword;
CheckBox cbRememberMe;
Button bLogin;
boolean checkRememberMe;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
etLogin = (EditText)findViewById(R.id.etLogin);
etPassword = (EditText)findViewById(R.id.etPassword);
cbRememberMe = (CheckBox)findViewById(R.id.cbRememberMe);
cbRememberMe.setOnCheckedChangeListener(this);
checkRememberMe = cbRememberMe.isChecked();
sharedPreferences = getSharedPreferences("login.conf", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
//////////////////////////////////////// PART A /////////////////////////////////////
final String accessdb = sharedPreferences.getString("access", "");
final String passworddb = sharedPreferences.getString("password", "");
final String fullnamedb = sharedPreferences.getString("fullname", "");
final String branchdb = sharedPreferences.getString("branch", "");
final String sectiondb = sharedPreferences.getString("branch", "");
final HashMap data = new HashMap();
data.put("access", accessdb);
data.put("password", passworddb);
data.put("fullname", fullnamedb);
data.put("branch", branchdb);
data.put("section", sectiondb);
if(!(accessdb.contains("") && passworddb.contains("") && fullnamedb.contains("") && branchdb.contains("") && sectiondb.contains(""))){
PostResponseAsyncTask task = new PostResponseAsyncTask(LoginActivity.this, data, new AsyncResponse() {
@Override
public void processFinish(String s) {
// edited here ,add Log
Log.d(TAG, "processFinish : " + s);
String responseToJSONObject = s.substring(s.indexOf("{"));
if(s.contains("success_access")){
try {
JSONObject jsonObject = new JSONObject(responseToJSONObject);
final String logindb = jsonObject.getString("login");
final String pwdb = jsonObject.getString("pw");
final String realnamedb = jsonObject.getString("real_name");
final String deptdb = jsonObject.getString("dept");
Intent intent = new Intent(LoginActivity.this, NextActivity.class);
intent.putExtra("login", logindb);
intent.putExtra("pw", pwdb);
intent.putExtra("real_name", realnamedb);
intent.putExtra("dept", deptdb);
LoginActivity.this.startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
task.execute("http://localhost/login.php");
}
//////////////////////////////////////// PART A /////////////////////////////////////
bLogin = (Button)findViewById(R.id.bLogin);
bLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String url = "http://localhost/login.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// edited here ,add Log
Log.d(TAG, "onResponse : " + response);
if(response.contains("success_access")){
String resp = response.substring(response.indexOf("{"));
// LOGIN WITH CHECK REMEMBER ME
if(checkRememberMe){
try {
JSONObject jsonObject = new JSONObject(resp);
final String accessdb = jsonObject.getString("access");
final String passworddb = jsonObject.getString("password");
final String fullnamedb = jsonObject.getString("fullname");
final String branchdb = jsonObject.getString("branch");
final String sectiondb = jsonObject.getString("section");
editor.putString("access", etLogin.getText().toString());
editor.putString("password", etPassword.getText().toString());
editor.putString("fullname", fullnamedb);
editor.putString("branch", branchdb);
editor.putString("section", sectiondb);
editor.putBoolean("isLoggedIn", true);
editor.apply();
Intent intent = new Intent(LoginActivity.this, NextActivity.class);
intent.putExtra("access", accessdb);
intent.putExtra("password", passworddb);
intent.putExtra("fullname", fullnamedb);
intent.putExtra("branch", branchdb);
intent.putExtra("section", sectiondb);
LoginActivity.this.startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
// LOGIN WITH CHECK REMEMBER ME
// LOGIN WITHOUT CHECK REMEMBER ME
else {
try {
JSONObject jsonObject = new JSONObject(resp);
final String accessdb = jsonObject.getString("access");
final String passworddb = jsonObject.getString("password");
final String fullnamedb = jsonObject.getString("fullname");
final String branchdb = jsonObject.getString("branch");
final String sectiondb = jsonObject.getString("section");
Intent intent = new Intent(LoginActivity.this, NextActivity.class);
intent.putExtra("access", accessdb);
intent.putExtra("password", passworddb);
intent.putExtra("fullname", fullnamedb);
intent.putExtra("branch", branchdb);
intent.putExtra("section", sectiondb);
LoginActivity.this.startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
// LOGIN WITHOUT CHECK REMEMBER ME
} else{
Toast.makeText(getApplicationContext(), "Error" , Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Error" , Toast.LENGTH_SHORT).show();
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("login", etLogin.getText().toString());
params.put("pw", etPassword.getText().toString());
return params;
}
};
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
}
});
}
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
checkRememberMe = isChecked;
Log.d(TAG, "Remember me is = " + checkRememberMe);
}
}
EDITED :
my Logcat
08-22 16:50:28.802 21022-21022/? I/art: Not late-enabling -Xcheck:jni (already on)
08-22 16:50:28.802 21022-21022/? W/art: Unexpected CPU variant for X86 using defaults: x86
08-22 16:50:28.822 21022-21029/? I/art: Debugger is no longer active
08-22 16:50:28.822 21022-21029/? I/art: Starting a blocking GC Instrumentation
08-22 16:50:28.895 21022-21022/? W/System: ClassLoader referenced unknown path: /data/app/com.app.test-2/lib/x86
08-22 16:50:28.901 21022-21022/? I/InstantRun: starting instant run server: is main process
08-22 16:50:29.129 21022-21040/? I/OpenGLRenderer: Initialized EGL, version 1.4
08-22 16:50:29.129 21022-21040/? D/OpenGLRenderer: Swap behavior 1
08-22 16:50:29.130 21022-21040/? W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
08-22 16:50:29.130 21022-21040/? D/OpenGLRenderer: Swap behavior 0
08-22 16:50:29.133 21022-21040/? D/EGL_emulation: eglCreateContext: 0xb3305060: maj 2 min 0 rcv 2
08-22 16:50:29.150 21022-21040/? D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303360)
08-22 16:50:29.156 21022-21040/? D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303360)
08-22 16:50:29.964 21022-21022/com.app.test W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
08-22 16:50:30.037 21022-21022/com.app.test W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
08-22 16:50:30.040 21022-21040/com.app.test D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303360)
08-22 16:50:44.279 21022-21022/com.app.test W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
08-22 16:50:46.163 21022-21022/com.app.test D/com.app.test.LoginActivity: Check flag is = true
08-22 16:50:47.820 21022-21323/com.app.test D/NetworkSecurityConfig: No Network Security Config specified, using platform default
// LOG.d after i logged in with remember me check in
08-22 16:50:47.824 21022-21022/com.app.test E/com.app.test.LoginActivity: Response is = success_access{"access":"ID001","password":"1233","fullname":"ARCADE","branch":"HQ", "section":"MPR"}
08-22 16:50:47.825 21022-21022/com.app.test E/com.app.test.LoginActivity: JSON Object is = {"access":"ID001","password":"1233","fullname":"ARCADE","branch":"HQ", "section":"MPR"}
08-22 16:50:47.825 21022-21022/com.app.test D/com.app.test.LoginActivity: ID001
08-22 16:50:47.825 21022-21022/com.app.test D/com.app.test.LoginActivity: 123
08-22 16:50:47.982 21022-21025/com.app.test I/art: Do partial code cache collection, code=29KB, data=30KB
08-22 16:50:47.982 21022-21025/com.app.test I/art: After code cache collection, code=29KB, data=30KB
08-22 16:50:47.982 21022-21025/com.app.test I/art: Increasing code cache capacity to 128KB
08-22 16:50:47.994 21022-21040/com.app.test D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303360)
08-22 16:50:48.083 21022-21040/com.app.test D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303360)
08-22 16:50:48.100 21022-21040/com.app.test D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303360)
08-22 16:50:48.135 21022-21022/com.app.test W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
// LOG.d when I restarted apps without logout.
08-22 16:54:32.607 24710-24710/? I/art: Not late-enabling -Xcheck:jni (already on)
08-22 16:54:32.607 24710-24710/? W/art: Unexpected CPU variant for X86 using defaults: x86
08-22 16:54:32.694 24710-24710/com.app.test W/System: ClassLoader referenced unknown path: /data/app/com.app.test-2/lib/x86
08-22 16:54:32.699 24710-24710/com.app.test I/InstantRun: starting instant run server: is main process
08-22 16:54:34.256 24710-24811/com.app.test I/OpenGLRenderer: Initialized EGL, version 1.4
08-22 16:54:34.257 24710-24811/com.app.test D/OpenGLRenderer: Swap behavior 1
08-22 16:54:34.257 24710-24811/com.app.test W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
08-22 16:54:34.257 24710-24811/com.app.test D/OpenGLRenderer: Swap behavior 0
08-22 16:54:34.258 24710-24811/com.app.test D/EGL_emulation: eglCreateContext: 0xb3305360: maj 2 min 0 rcv 2
08-22 16:54:34.266 24710-24811/com.app.test D/EGL_emulation: eglMakeCurrent: 0xb3305360: ver 2 0 (tinfo 0xb3303200)
08-22 16:54:34.274 24710-24811/com.app.test D/EGL_emulation: eglMakeCurrent: 0xb3305360: ver 2 0 (tinfo 0xb3303200)
08-22 16:54:35.124 24710-24710/com.app.test W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
08-22 16:54:35.292 24710-24710/com.app.test W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
08-22 16:54:35.299 24710-24811/com.app.test D/EGL_emulation: eglMakeCurrent: 0xb3305360: ver 2 0 (tinfo 0xb3303200)
Appreciate if someone can help. Thanks.
回答1:
From what I see and understand in your question, you want the data to be stored and intent into next activity on next auto logged in (inside PART A).
After I tried it from my end based on your code above and I assume your "isLoggedIn" is from other activity file.
You just need to change boolean "isLoggedIn" into false because whenever user log in with remember me, it stored the sharedPreferences data and intent it into next activity.
Same as log in without remember me, it stored the sharedPreferences data but isLoggedIn is false. Therefore, when your apps restart or rebuild, it will not auto logged in anymore. Don't forget to clear and commit the sharedPreferences when "isLoggedIn" is false.
Here's the code.
LoginActivity.java
if(checkRememberMe){
// Data added
} else {
try {
JSONObject jsonObject = new JSONObject(resp);
final String accessdb = jsonObject.getString("access");
final String passworddb = jsonObject.getString("password");
final String fullnamedb = jsonObject.getString("fullname");
final String branchdb = jsonObject.getString("branch");
final String sectiondb = jsonObject.getString("section");
editor.putString("access", etLogin.getText().toString());
editor.putString("password", etPassword.getText().toString());
editor.putString("fullname", fullnamedb);
editor.putString("branch", branchdb);
editor.putString("section", sectiondb);
editor.putBoolean("isLoggedIn", false);
editor.apply();
Intent intent = new Intent(LoginActivity.this, NextActivity.class);
intent.putExtra("access", accessdb);
intent.putExtra("password", passworddb);
intent.putExtra("fullname", fullnamedb);
intent.putExtra("branch", branchdb);
intent.putExtra("section", sectiondb);
LoginActivity.this.startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
And inside NextActivity.java, add sharedPreferences and set it as String.
sharedPreferences sharedPreferences = getSharedPreferences("login.conf", Context.MODE_PRIVATE);
final String accessdb = sharedPreferences.getString("access","");
final String pwdb = sharedPreferences.getString("pw","");
final String fullnamedb = sharedPreferences.getString("fullname","");
final String branchdb = sharedPreferences.getString("branch","");
final String sectiondb = sharedPreferences.getString("section","");
Intent intent = getIntent();
String access_db = intent.getStringExtra("access");
String pw_db = intent.getStringExtra("pw");
String fullname_db = intent.getStringExtra("fullname");
String branch_db = intent.getStringExtra("branch");
String section_db = intent.getStringExtra("section");
Toast.makeText(getApplicationContext(), "access is = " + accessdb, Toast.makeText.LENGTH_SHORT).show();
回答2:
Try this.
public class SharedPreferenceUtils {
private static final String SP_NAME = "sp";
public static final String ACCESS = "access";
public static final String FULL_NAME = "fullname";
public static final String BRANCH = "branch";
public static final String SECTION = "section";
public static final String IS_LOGGED_IN = "isLoggedIn";
// create
public static boolean createSP(Context context, String access, String fullname, String branch, String section, boolean isLoggedIn) {
SharedPreferences.Editor editor = context.getSharedPreferences("login.conf", Context.MODE_PRIVATE).edit();
editor.putString(ACCESS, access);
editor.putString(FULL_NAME, fullname);
editor.putString(BRANCH, branch);
editor.putString(SECTION, section);
editor.putBoolean(IS_LOGGED_IN, isLoggedIn);
return editor.commit();
}
// clear
public static void clearSP(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear().apply();
}
// get access info
public static String getAccess(Context context) {
SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
return sp.getString(ACCESS, "");
}
// get branch info
public static String getFullName(Context context) {
SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
return sp.getString(FULL_NAME, "");
}
// get fullname info
public static String getBranch(Context context) {
SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
return sp.getString(BRANCH, "");
}
// get section info
public static String getSection(Context context) {
SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
return sp.getString(SECTION, "");
}
// get isLoggedIn info
public static boolean getIsLoggedIn(Context context) {
SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
return sp.getBoolean(ACCESS, false);
}
}
And in your code.
// edited here
final String accessdb = SharedPreferenceUtils.getAccess(this);
final String fullnamedb = SharedPreferenceUtils.getFullName(this);
final String branchdb = SharedPreferenceUtils.getBranch(this);
final String sectiondb = SharedPreferenceUtils.getSection(this);
final HashMap data = new HashMap();
data.put("access", accessdb);
data.put("password", passworddb);
data.put("fullname", fullnamedb);
data.put("branch", branchdb);
data.put("section", sectiondb);
And if isRemember
if(checkRememberMe){
SharedPreferenceUtils.createSP(LoginActivity.this,etLogin.getText().toString(),fullnamedb,branchdb,sectiondb,true);
}
来源:https://stackoverflow.com/questions/45810586/how-to-intent-sharedpreferences-into-next-activity-value-using-postresponseasync