gpt4 book ai didi

android - 如何在 Android Studio 中使用 PostResponseAsyncTask 将 SharedPreferences 设置为下一个 Activity 值?

转载 作者:太空宇宙 更新时间:2023-11-03 13:10:45 34 4
gpt4 key购买 nike

我的问题是这个问题的扩展 here但在这个问题中我添加了两个函数:

  1. 共享首选项
  2. 记住我功能(复选框)

目前,我设法在有/没有记住我复选框的情况下登录,并打算从 mysql 数据库中获取其余的 JSON 对象。

但问题出在 LoginActivity.java PART A block 内部。当我重新启动/重建应用程序时, Intent 数据为空,不会存储并发送到下一个 Activity 。自动登录时,数据无法存储和发送到下一个 Activity 。代码如下

JSON 对象

{
"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);
}
}

编辑:

我的日志

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)

感谢有人能提供帮助。谢谢。

最佳答案

试试这个。

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);
}

}

并在您的代码中。

// 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);

如果是记住

if(checkRememberMe){
SharedPreferenceUtils.createSP(LoginActivity.this,etLogin.getText().toString(),fullnamedb,branchdb,sectiondb,true);
}

关于android - 如何在 Android Studio 中使用 PostResponseAsyncTask 将 SharedPreferences 设置为下一个 Activity 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45810586/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com