2013-11-10 61 views
0

在我的應用程序中,我試圖弄清楚如何保存用戶ID會話並在用戶關閉應用程序之前使用它。Android:如何從SQLite數據庫中將用戶ID作爲會話進行調用和保存?

我知道在PHP中,你可以只使用$ _SESSION [ '用戶ID'] = $ user_id的

我想在Android的SQLite的運行查詢像這樣

SELECT user_id, username, password 
FROM users 
**WHERE user_id = $_SESSION[user_id]** 

這是從PHP ,有沒有什麼辦法可以在android中做到這一點?我聽說過共享偏好設置,但我不確定它是如何工作的?

對不起,我剛開始學習Android編程。我有點小菜。如果你能在這裏幫助我,我會很感激。

編輯:這個用戶ID是我從SQLite數據庫被調用並將其保存爲一個會話時

回答

0

首先,用戶登錄您必須聲明全局共享偏好列:

SharedPreferences sp; 

然後在你的onCreate SP delcare:

sp = getSharedPreferences("Session", 0); //"Session" is the file name it MUST be the same in all activities that require shared preferences. 

所以基本上,當用戶登錄你檢查他是否是登錄後,如果這是真的,然後用保存他的ID在共享偏好:

SharedPreferences.Editor e = sp.edit(); 
       e.putInt("ID", ID-Value-that-you-used-it-to-check-for-ID); 
       e.commit(); 

,並在的onCreate登錄類,添加第二塊以檢查用戶是否登錄,他從來沒有登出。如果他隨後帶他去下一個活動。

if (cID != 0) 
    { 
     Intent iLogged = new Intent(this, The-Next-Class.class); 
     finish(); 
     startActivity(iLogged); 
    } 
只要你想找回你只需要添加值

...

int ID = sp.getInt("ID", 0); 

,並註銷用戶,然後刪除該會話使用下列內容:

sp.edit().clear().commit(); 
     Intent iLogout = new Intent(this, Login.class); 
     finish(); 
     startActivity(iLogout); 
     break; 

編輯2 :

你要做的是...

1)從共享首選項中檢索ID ..現在如果UserID列是int,則使用。

int ID = sp.getInt("ID", 0); // 0 is default value which means if couldn't find the value in the shared preferences file give it a value of 0. 

2)你必須檢查,如果ID!= 0,則值傳遞給查詢......

SELECT user_id, username, password 
FROM users 
WHERE user_id = ID 
+0

這個用戶ID是一個列,我將從SQLite數據庫中調用並在用戶登錄時將其保存爲會話。你知道如何繼續這樣做嗎? – Rager58

+0

檢查編輯的部分希望你有想法,如果不添加代碼來幫助你更多 – Coderji

+0

我該如何聲明用戶的user_id列作爲sql數據庫中的一個int? e.putInt(「ID」,不知道這部分); 請參閱上面的代碼 – Rager58

1

我做在我的Android應用程序使用此AppPreferences類似的東西是在應用程序

public class AppPreferences { 
public static final String ApplicationPreferences = "com.akada.danceworksonline.studio.MainActivity"; 
public String putEmail = "email"; 
private SharedPreferences sharedPrefs; 
private SharedPreferences.Editor prefsEditor; 

public AppPreferences(Context context) { 

    this.sharedPrefs = context.getSharedPreferences(ApplicationPreferences, 
      0); 
    this.prefsEditor = sharedPrefs.edit(); 

} 

public String getEmailPref() { 
    return sharedPrefs.getString(putEmail, ""); 
} 

public void saveEmail(String text) { 
    prefsEditor.putString(putEmail, text); 
    prefsEditor.commit(); 
} 

使用一類我創建保存電子郵件的一個例子以後,有你的地方讓你的數據庫調用具有沿此線的東西。

AppPreferences _appPrefs = new AppPreferences(getApplicationContext()); 

然後你可以做類似_appPrefs.saveEmail(textviewEmail),或者你得到你的價值。

+0

謝謝!我有點得到了我想要的東西;然而,我怎麼用SQLite數據庫來實現呢? – Rager58

+0

我沒有使用SQLite,所以你自己在那裏。如果我幫助我會欣賞一個upvote :) – ksudu94

+0

對不起,我沒有足夠的聲譽來增加投票。 :( – Rager58

相關問題