dsa122870 2013-11-10 03:27
浏览 69
已采纳

Android:如何从SQLite数据库中调用和保存userID作为会话?

In my application, I am trying to figure out how to save userID session and use it until the user closes the app.

I know in PHP you can just use the $_SESSION['userID'] = $user_id

I want to run a query something like this in Android SQLite

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

This is from php, is there some way I can do this in android? I heard about shared preferences but I am not sure how it works?

Sorry, I just started learning about Android programming. I am a bit of a noob. I'll appreciate if you could help me out here.

EDIT: this userID is a column that I will be calling from SQLite database and saving it as a session when the user logs in.

  • 写回答

2条回答 默认 最新

  • dongpo5264 2013-11-10 03:59
    关注

    First you have to declare global shared preferences:

    SharedPreferences sp;
    

    then in onCreate you delcare sp:

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

    So basically when the user login you check whether he is logged in, if it is true, then save his ID in the shared preferences using:

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

    and in the login class in onCreate, you add the second block to check whether the user is logged in and he has never logged out. and simply if he is then take him to the next activity.

    if (cID != 0)
        {
            Intent iLogged = new Intent(this, The-Next-Class.class);
            finish();
            startActivity(iLogged);
        }
    

    whenever you want to retrieve the value you just add...

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

    and to log out the user and delete the session use the following:

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

    Edit 2:

    What you got to do is...

    1) retrieve the ID from the shared preferences.. now if the UserID column is int then use.

    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) you have to check, if the ID != 0 then pass the value to the query...

    SELECT user_id, username, password
    FROM users
    WHERE user_id = ID
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型