2016-11-04 120 views
3

我正在創建一個與SOAP Web服務進行交互以從數據庫獲取數據的應用程序。當用戶成功登錄時,它會通過網絡服務生成一個令牌。稍後在其他活動中需要此標記來調用Web服務方法。我的問題是,如何在需要時將該令牌傳遞給下一個活動,並在用戶註銷之前將其保留。如何在Android中的本地或會話存儲中存儲令牌?

MainActivity.java

SharedPreferences偏好= getApplicationContext()getSharedPreferences( 「YourSessionName」,MODE_PRIVATE)。 SharedPreferences.Editor editor = preferences.edit(); editor.putString(「name」,AIMSvalue);

    editor.commit(); 

OtherActivity.java

SharedPreferences preferences=getSharedPreferences("YourSessionName", MODE_PRIVATE); 
    SharedPreferences.Editor editor=preferences.edit(); 

    token=preferences.getString("name",""); 

    editor.commit(); 
+0

我認爲[SharedPreferences](https://developer.android.com/reference/android/content/SharedPreferences.html)是正確的地方 –

+0

沒有它的不工作。 –

+0

使用SharedPreferences時遇到了什麼問題? –

回答

1
public class CommonUtilities { 

    private static SharedPreferences.Editor editor; 
    private static SharedPreferences sharedPreferences; 
    private static Context mContext; 

/** 
    * Create SharedPreference and SharedPreferecne Editor for Context 
    * 
    * @param context 
    */ 
    private static void createSharedPreferenceEditor(Context context) { 
     try { 
      if (context != null) { 
       mContext = context; 
      } else { 
       mContext = ApplicationStore.getContext(); 
      } 
      sharedPreferences = context.getSharedPreferences(IConstants.SAMPLE_PREF, Context.MODE_PRIVATE); 
      editor = sharedPreferences.edit(); 
     } catch (Exception ex) { 
      ex.printStackTrace(); 
     } 

    } 

/** 
* Put String in SharedPreference Editor 
* 
* @param context 
* @param key 
* @param value 
*/ 
public static void putPrefString(Context context, String key, String value) { 
    try { 
     createSharedPreferenceEditor(context); 
     editor.putString(key, value); 
     editor.commit(); 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
    } 

} 

} 

使用此putString()方法來存儲一個令牌,當你登錄,並刪除標記,當您退出或令牌過期。

+0

我已經做到了這一點,但沒有工作。在調用登錄後調用第二種Web服務方法時,它始終將其視爲新請求,即從登錄屏幕生成的令牌不能正確傳遞到另一個屏幕。@ Kush Patel –