gpt4 book ai didi

android - 是否可以从一个 HashMap 方法中同时获取 Integer 和 String 值?

转载 作者:太空狗 更新时间:2023-10-29 16:35:14 25 4
gpt4 key购买 nike

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

方法一:

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;
}

方法二:

    public HashMap<String, String> getUserDetails() {
HashMap<String, String> user = new HashMap<String, String>();
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;

SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
user.put("name", cursor.getString(1));
user.put("email", cursor.getString(2));
user.put("created_at", cursor.getString(3));
}
cursor.close();
// return user
Log.d(TAG, "Fetching user from Sqlite: " + user.toString());

return 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 对象,其中包含所有必需的信息。

关于android - 是否可以从一个 HashMap 方法中同时获取 Integer 和 String 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30487147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com