2013-11-28 62 views
0

我有一個問題。我有一個應用程序,你可以投票給你喜歡的人。你可以每天只投一次。當用戶使用SharedPreferences進行投票時,我保存了這一天,因此用戶不能在當天再投一次。一切都很好。我創建了另一項活動,並從該活動中瞭解用戶的選擇。這意味着,我知道誰是用戶想投票。我的問題是:如何獲得用戶的共享首選項(上次投票的日期),將其寫入SharedPreferences(投票活動會知道我選擇了某人),並且必須將相同的代碼從投票活動複製到第二個活動或我可以使用我的投票活動從一些代碼的地方?我的代碼保存首選項和調用JSON:從另一個活動調用JSON

private void savePreferences(String key, int value) { 
     SharedPreferences sharedPreferences = PreferenceManager 
       .getDefaultSharedPreferences(this); 
     Editor editor = sharedPreferences.edit(); 
     editor.putInt(key, value); 
     editor.commit(); 
    } 

    class AttemptLogin extends AsyncTask<String, String, String> { 

     @Override 
     protected void onPostExecute(String file_url) { 
      // TODO Auto-generated method stub 
      super.onPostExecute(file_url); 
      pDialog.dismiss(); 

     } 

     @Override 
     protected String doInBackground(String... args) { 
      // TODO Auto-generated method stub 
      String pos = pos1.toString(); 

      Log.i("12", pos); 
      int success; 
      try { 
       List<NameValuePair> params = new ArrayList<NameValuePair>(); 
       params.add(new BasicNameValuePair("pos", pos)); 
       Log.d("request!", pos); 

       JSONObject json = jsonParser.makeHttpRequest(VOTE_URL, "POST", 
         params); 


       success = json.getInt(TAG_SUCCESS); 
       if (success == 1) { 
        Log.d("Successful!", json.toString()); 

        Intent i = new Intent(Vote.this, MainActivity.class); 
        finish(); 
        startActivity(i); 
       } else { 
        Log.d("Failure!", json.toString()); 

       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

      return null; 
     } 

     @Override 
     protected void onPreExecute() { 
      // TODO Auto-generated method stub 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(Balsuok.this); 
      pDialog.setMessage("Voting..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(true); 
      pDialog.show(); 

     } 

    } 
+0

我想你忘了保存在sharedpreferences –

+0

JSON結果我並不需要保存JSON結果。我只需要保存上一次用戶上次投票的日期 – linkas

回答

0

設置像這樣的共享首選項。

活動1: -

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); 
SharedPreferences.Editor editor = prefs.edit(); 
editor.putString(key, value); 
editor.commit(); 

獲取這樣第二活動共享偏好。

活性2: -

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); 
return preferences.getString(key, null); 
+0

只需要提示,用您的日期設置密鑰dd-MM-yyyy ...然後您將現在當用戶已經投票,如果key!= null用戶已經投票了date – GhostDerfel

+0

我剛剛發佈瞭如何設置和獲取Shared Pref的方法。他希望他的價值。 –

+0

另一件事,最好的方法是如果用戶已經在web服務中投票,如果使用SharedPreferences進行驗證,那麼如果用戶只是清理應用程序數據或刪除應用程序,您將丟失所有數據 – GhostDerfel