如何使用Android Studio中的PostResponseAsyncTask将SharedPreferences设置为下一个活动值?

如何使用Android Studio中的PostResponseAsyncTask将SharedPreferences设置为下一个活动值?,第1张

概述我的问题是这个问题here的扩展,但是在这个问题中,我添加了两个函数:>共享首选项>记住我的功能(复选框)目前,我设法使用/不使用记住我的复选框登录,并打算从mysql数据库中获取其余的JSON对象.但是问题出在LoginActivity.javaPARTA块内部.当我重新启动/重建应用程序时,意图数据

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

>共享首选项
>记住我的功能(复选框)

目前,我设法使用/不使用记住我的复选框登录,并打算从MysqL数据库中获取其余的JsON对象.

但是问题出在LoginActivity.java PART A块内部.当我重新启动/重建应用程序时,意图数据为空,它不会存储并发送到下一个活动中.数据自动登录后,无法存储并发送到下一个活动.如下代码

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 one rrorResponse(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);    }}

编辑:

我的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: x8608-22 16:50:28.822 21022-21029/? I/art: DeBUGger is no longer active08-22 16:50:28.822 21022-21029/? I/art: Starting a blocking GC Instrumentation08-22 16:50:28.895 21022-21022/? W/System: ClassLoader referenced unkNown path: /data/app/com.app.test-2/lib/x8608-22 16:50:28.901 21022-21022/? I/InstantRun: starting instant run server: is main process08-22 16:50:29.129 21022-21040/? I/Openglrenderer: Initialized EGL, version 1.408-22 16:50:29.129 21022-21040/? D/Openglrenderer: Swap behavior 108-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 008-22 16:50:29.133 21022-21040/? D/EGL_emulation: eglCreateContext: 0xb3305060: maj 2 min 0 rcv 208-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.Drawable08-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.ListVIEw08-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 inputConnection08-22 16:50:46.163 21022-21022/com.app.test D/com.app.test.LoginActivity: Check flag is = true08-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 in08-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: ID00108-22 16:50:47.825 21022-21022/com.app.test D/com.app.test.LoginActivity: 12308-22 16:50:47.982 21022-21025/com.app.test I/art: Do partial code cache collection, code=29KB, data=30KB08-22 16:50:47.982 21022-21025/com.app.test I/art: After code cache collection, code=29KB, data=30KB08-22 16:50:47.982 21022-21025/com.app.test I/art: Increasing code cache capacity to 128KB08-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: x8608-22 16:54:32.694 24710-24710/com.app.test W/System: ClassLoader referenced unkNown path: /data/app/com.app.test-2/lib/x8608-22 16:54:32.699 24710-24710/com.app.test I/InstantRun: starting instant run server: is main process08-22 16:54:34.256 24710-24811/com.app.test I/Openglrenderer: Initialized EGL, version 1.408-22 16:54:34.257 24710-24811/com.app.test D/Openglrenderer: Swap behavior 108-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 008-22 16:54:34.258 24710-24811/com.app.test D/EGL_emulation: eglCreateContext: 0xb3305360: maj 2 min 0 rcv 208-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.Drawable08-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.ListVIEw08-22 16:54:35.299 24710-24811/com.app.test D/EGL_emulation: eglMakeCurrent: 0xb3305360: ver 2 0 (tinfo 0xb3303200)

感谢有人可以提供帮助.谢谢.

解决方法:

根据我对问题的理解,您希望数据被存储并打算在下一次自动登录时进入下一个活动(在A部分内部).

在根据您上面的代码从头开始尝试之后,我假设您的“ isLoggedIn”来自其他活动文件.

您只需要将布尔值“ isLoggedIn”更改为false,因为每当用户记住我登录时,它都会存储sharedPreferences数据并将其用于下一个活动.

与不记得我的登录相同,它存储了sharedPreferences数据,但isLoggedIn为false.因此,当您的应用重新启动或重建时,它将不再自动登录.当“ isLoggedIn”为false时,请不要忘记清除并提交sharedPreferences.

这是代码.

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

在NextActivity.java中,添加sharedPreferences并将其设置为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();
总结

以上是内存溢出为你收集整理的如何使用Android Studio中的PostResponseAsyncTask将SharedPreferences设置为下一个活动值?全部内容,希望文章能够帮你解决如何使用Android Studio中的PostResponseAsyncTask将SharedPreferences设置为下一个活动值?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/web/1091687.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-27
下一篇2022-05-27

发表评论

登录后才能评论

评论列表(0条)

    保存