如何刷新共享偏好中的值?

时间:2018-06-08 12:46:09

标签: php android retrofit android-sharedpreferences

我正在使用Retrofit库开发一个动态的Android应用程序。该应用程序将请求发送到服务器端php文件,并从他们那里收到json响应。我正在关注登录注册系统的this教程。从mysql数据库检索的值首先存储在SharedPreferences中,然后设置为相应的TextView

一切正常。但是,当我更改数据库中的值时,用户需要注销并再次登录才能看到更新的值。我试过在我的ProfileFragment.java中创建一个函数

private void refreshProcess(String email1){
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RequestInterface requestInterface = retrofit.create(RequestInterface.class);

    User user = new User();
    user.setEmail(email1);
    ServerRequest request = new ServerRequest();
    request.setOperation(Constants.REFRESH_OPERATION);
    request.setUser(user);
    Call<ServerResponse> response = requestInterface.operation(request);
    response.enqueue(new Callback<ServerResponse>() {
        @Override
        public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {

            ServerResponse resp = response.body();
            Snackbar.make(getView(), resp.getMessage(), Snackbar.LENGTH_LONG).show();

            if(resp.getResult().equals(Constants.SUCCESS)){
                SharedPreferences.Editor editor = pref.edit();
                editor.putBoolean(Constants.IS_LOGGED_IN,true);
                editor.putString(Constants.EMAIL,resp.getUser().getEmail());
                editor.putString(Constants.NAME,resp.getUser().getName());
                editor.putString(Constants.ROLLNO,resp.getUser().getRollno());
                editor.putString(Constants.TOTL_FEES,resp.getUser().getTotl_fees());
                editor.putString(Constants.PAID_FEES,resp.getUser().getPaid_fees());
                editor.putString(Constants.REM_FEES,resp.getUser().getRem_fees());
                editor.putString(Constants.MON_ATT,resp.getUser().getMon_att());
                editor.putString(Constants.TUE_ATT,resp.getUser().getTue_att());
                editor.putString(Constants.WED_ATT,resp.getUser().getWed_att());
                editor.putString(Constants.THRS_ATT,resp.getUser().getThrs_att());
                editor.putString(Constants.FRI_ATT,resp.getUser().getFri_att());
                editor.putString(Constants.SAT_ATT,resp.getUser().getSat_att());
                editor.putString(Constants.SUN_ATT,resp.getUser().getSun_att());
                editor.putString(Constants.TST1_DATE,resp.getUser().getTst1_date());
                editor.putString(Constants.TST1_DATE,resp.getUser().getTst1_date());
                editor.putString(Constants.TST1_MARKS,resp.getUser().getTst1_marks());
                editor.putString(Constants.TST1_RANK,resp.getUser().getTst1_rank());
                editor.putString(Constants.TST2_DATE,resp.getUser().getTst2_date());
                editor.putString(Constants.TST2_MARKS,resp.getUser().getTst2_marks());
                editor.putString(Constants.TST2_RANK,resp.getUser().getTst2_rank());
                editor.putString(Constants.TST3_DATE,resp.getUser().getTst3_date());
                editor.putString(Constants.TST3_MARKS,resp.getUser().getTst3_marks());
                editor.putString(Constants.TST3_RANK,resp.getUser().getTst3_rank());
                editor.putString(Constants.TST4_DATE,resp.getUser().getTst4_date());
                editor.putString(Constants.TST4_MARKS,resp.getUser().getTst4_marks());
                editor.putString(Constants.TST4_RANK,resp.getUser().getTst4_rank());
                editor.putString(Constants.TST5_DATE,resp.getUser().getTst5_date());
                editor.putString(Constants.TST5_MARKS,resp.getUser().getTst5_marks());
                editor.putString(Constants.TST5_RANK,resp.getUser().getTst5_rank());
                editor.putString(Constants.UNIQUE_ID,resp.getUser().getUnique_id());
                editor.putString(Constants.PERSONAL_MSG,resp.getUser().getPersonalMsg());
                editor.putString(Constants.BROADCAST_MSG,resp.getUser().getBroadcast_msg());
                editor.apply();
                goToProfile();

            }
            progress.setVisibility(View.INVISIBLE);
        }


        private void goToProfile(){

            Fragment profile = new ProfileFragment();
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            ft.replace(R.id.fragment_frame,profile);
            ft.commit();
        }

        @Override
        public void onFailure(Call<ServerResponse> call, Throwable t) {

            progress.setVisibility(View.INVISIBLE);
            Log.d(Constants.TAG,"failed");
            Snackbar.make(getView(), t.getLocalizedMessage(), Snackbar.LENGTH_LONG).show();

        }
    });
}

该函数发送初始化为当前登录用户的电子邮件字符串。它作为字符串存储在Constants.java类中,该类具有设置值,该值在用户登录时存储在SharedPreferences中。

String email1=pref.getString(Constants.EMAIL,"");
            refreshProcess(email1);

在服务器端,我有index.php文件检查操作刷新

if ($operation == 'refresh') {

          $user = $data -> user;
          $email = $user -> email;

          echo $fun -> refreshUserData($email);

    }

functions.php文件具有refreshUserData函数

public function refreshUserData($email){
$db = $this -> db;

$result =  $db -> refreshData($email);

if(!$result) {

    $response["result"] = "failure";
    $response["message"] = "Failed to Refresh";
    return json_encode($response);

   } else {

    $response["result"] = "success";
    $response["message"] = "Refresh Complete";
    $response["user"] = $result;
    return json_encode($response);

   }
}

以下是文件refreshData

中的函数DBOperations.php
public function refreshData($email){

$sql = 'SELECT * FROM users WHERE email = :email';
      $query = $this -> conn -> prepare($sql);
      $query -> execute(array(':email' => $email));
      $data = $query -> fetchObject();

    $user["name"] = $data -> name;
    $user["attendance"] = $data -> attendance;
    $user["email"] = $data -> email;
    $user["unique_id"] = $data -> unique_id;
    $user["rollno"] = $data -> rollno;
    $user["totl_fees"] = $data -> totl_fees;
    $user["paid_fees"] = $data -> paid_fees;
    $user["rem_fees"] = $data -> rem_fees;
    $user["mon_att"] = $data -> mon_att;
    $user["tue_att"] = $data -> tue_att;
    $user["wed_att"] = $data -> wed_att;
    $user["thrs_att"] = $data -> thrs_att;
    $user["fri_att"] = $data -> fri_att;
    $user["sat_att"] = $data -> sat_att;
    $user["sun_att"] = $data -> sun_att;
    $user["tst1_date"] = $data -> tst1_date;
    $user["tst1_marks"] = $data -> tst1_marks;
    $user["tst1_rank"] = $data -> tst1_rank;
    $user["tst2_date"] = $data -> tst2_date;
    $user["tst2_marks"] = $data -> tst2_marks;
    $user["tst2_rank"] = $data -> tst2_rank;
    $user["tst3_date"] = $data -> tst3_date;
    $user["tst3_marks"] = $data -> tst3_marks;
    $user["tst3_rank"] = $data -> tst3_rank;
    $user["tst4_date"] = $data -> tst4_date;
    $user["tst4_marks"] = $data -> tst4_marks;
    $user["tst4_rank"] = $data -> tst4_rank;
    $user["tst5_date"] = $data -> tst5_date;
    $user["tst5_marks"] = $data -> tst5_marks;
    $user["tst5_rank"] = $data -> tst5_rank;
    $user["personal_msg"] = $data -> personal_msg;
    $user["broadcast_msg"] = $data -> broadcast_msg;

    return $user;
}

完成所有这些传奇之后,当我点击调用功能refreshProcess()的按钮Refresh时,应用程序停止。这是logcat

06-08 18:09:50.101 2544-2544/net.softglobe.learn2crack E/AndroidRuntime: FATAL EXCEPTION: main
Process: net.softglobe.learn2crack, PID: 2544
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setVisibility(int)' on a null object reference
    at net.softglobe.learn2crack.ProfileFragment$5.onResponse(ProfileFragment.java:293)
    at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

请提供令人满意的解决方案,帮助我解决这个问题,因为我花了很长时间来做这个并在各处搜索如何实现这一目标,但没有得到回应。

0 个答案:

没有答案