是否可以从一个HashMap方法获取Interger和String值?

时间:2015-05-27 15:42:01

标签: android hashmap

我想合并我的两个Hashmap方法。一种方法是获取用户ID,另一种方法是获取用户字符串信息。但我想从一个hashmap方法获取所有信息。可能吗?如果是,我如何在我的getuserdetails hashmap方法中执行此操作?

方法1:

private static readonly string[] Scopes = {GmailService.Scope.MailGoogleCom};
...
string clientSecret = Settings.ClientSecret;
string clientId = Settings.ClientId;
Task<UserCredential> tCredential;
ClientSecrets clientSecrets = new ClientSecrets {ClientId = clientId, ClientSecret = clientSecret};
tCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(
    clientSecrets,
    Scopes,
    "user",
    CancellationToken.None);

方法2:

public HashMap<String, Integer> getUid() {

        HashMap<String, Integer> uid = new HashMap<String,Integer>();
        String selectQuery = "SELECT  * FROM " + TABLE_LOGIN;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        // Move to first row
        cursor.moveToFirst();
        Log.d("database", "before uid put");
        if (cursor.getCount() > 0) {
            uid.put("uid",cursor.getInt(0));
        }
        cursor.close();
        // return user

        return uid;
}

3 个答案:

答案 0 :(得分:2)

这里最干净的方法是创建一个User对象,其中包含id,name,email和created_at字段,如下所示:

public class User {
  private int id;
  private String name;
  private String email;
  private Date createdAt; // Or use string here, whichever you want

  // create or generate getters and setters for above fields
}

然后,您可以使用查询从数据库中获取数据并创建用户:

public User getUserDetails() {
    String selectQuery = "SELECT  * FROM " + TABLE_LOGIN;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // Move to first row
    cursor.moveToFirst();
    User user = new User();
    if (cursor.getCount() > 0) {
        user.setId(cursor.getInt(0));
        user.setName(cursor.getString(1));
        user.setEmail(cursor.getString(2));
        user.setCreatedAt(cursor.getString(3));
    }
    else {
        cursor.close();
        return null; // There wasn't a user to be found
    }
    cursor.close();

    return user;
}

现在,您的方法会创建一个User对象,其中包含所有必需的信息。

答案 1 :(得分:2)

使用uid创建一个类并且命名可验证并创建一个hashmap方法作为此类的返回类型。希望这会奏效。

答案 2 :(得分:1)

你可以在像

这样的课程中包装起来
public class Info {
   public int uid; 
   public String name;
}

并拥有HashMap<String, Info>