2016-06-02 6 views
0

私はVolleyを使ってHTTP Postリクエストを作成しています。共有優先設定Volley StringRequest

これはうまくいきますが、onResponseメソッド内でSharedPreference値を設定しようとしていますが、この値は設定されていないようです。

ボレーコード:

public void sendPostRequest() { 

     RequestQueue queue = Volley.newRequestQueue(this); 

     StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { 
      @Override 
      public void onResponse(String response) { 
       progress.dismiss(); 
       try { 
        JSONObject obj = new JSONObject(response); 
        if (obj.has("success")){ 

         SharedPreferences sharedPref = LoginActivity.this.getPreferences(Context.MODE_PRIVATE); 
         SharedPreferences.Editor editor = sharedPref.edit(); 
         editor.putBoolean("loggedIn", true); 
         editor.commit(); 

         Intent intent = new Intent(LoginActivity.this, SearchActivity.class); 
         startActivity(intent); 
        }else{ 
         error.setText(obj.getString("error")); 
        } 
       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 


      } 
     }, new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError volleyError) { 
       System.out.println("volley Error ................."); 
      } 
     }) { 
      @Override 
      protected Map<String, String> getParams() throws AuthFailureError { 
       Map<String, String> params = new HashMap<String, String>(); 

       params.put("username", emailTxt.getText().toString()); 
       params.put("password", passwordTxt.getText().toString()); 
       return params; 
      } 
     }; 

     queue.add(stringRequest); 


    } 

意図はので、私はif文、我々は成功をヒットしている知ってトリガーされます。ユーザーがすでに

public class MainActivity extends AppCompatActivity { 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.activity_main); 

     getSupportActionBar().hide(); 

     SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE); 

     boolean loggedIn = sharedPref.getBoolean("loggedIn", false); 

       if (loggedIn){ 
        Intent intent = new Intent(MainActivity.this, SearchActivity.class); 
        startActivity(intent); 
       }else{ 
        Intent intent = new Intent(MainActivity.this, RegisterActivity.class); 
        startActivity(intent); 
       } 

    } 

ログインしている場合

以下のコードは、しかしLOGGEDINは常に偽であるパスのログインによってランチャーの活動に実行されます。

+1

このコードはスプラッシュ画面にありますか? – Piyush

+0

@PiyushGuptaはい下のコードはスパッシュ画面です –

+0

次に、ビューを読み込む前にこの関数を呼び出す必要があります。この_loggedIn _をスプラッシュ画面に記録し、その値は何ですか? – Piyush

答えて

3

としては、ここを参照してください:

getPreferences

はSharedPreferencesが

LoginActivityMainActivity活性の両方が異なっているこの活動にプライベート をしている設定にアクセスするためのオブジェクトを取得するので、常に取得しますfalse

両方のアクティビティでgetPreferencesの代わりにgetSharedPreferencesを使用して動作させます。

関連する問題