我正在尝试检索存储在数据库中的数据。
我想以arraylist格式检索它
ArrayList (ProfileID, Name)
我有一个Databasehandler我正在尝试以下内容:
public ArrayList<String> getinviteDetails()
{
String selectQuery = "SELECT * FROM " + TABLE_DETAILS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
ArrayList<String> datalist = new ArrayList<String>();
if (cursor.moveToLast())
{
datalist.add(cursor.getString(0));
datalist.add(cursor.getString(1));
datalist.add(cursor.getString(2));
datalist.add(cursor.getString(3));
}
cursor.close();
db.close();
return datalist;
}
但这会像
一样得到保存 ArrayList (ProfileID)
ArrayList (Name)
我不确定如何以ArrayList(ProfileID,Name)格式存储它?有人可以帮我解决这个问题吗?
谢谢!
答案 0 :(得分:2)
您不能在ArrayList中拥有键值对。使用HashMap代替它。http://developer.android.com/reference/java/util/HashMap.html 正确的方法应如下
public HashMap<String, String> getinviteDetails() {
HashMap<String, String> datalist = new HashMap<String, String>();
SQLiteDatabase db = null;
Cursor cursor = null;
try {
db = this.getWritableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_DETAILS;
cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
// Loop all entries and fill datalist
while (cursor.moveToNext()) {
String profileID = cursor.getString(cursor
.getColumnIndex(PROFILE_COLUMN_NAME));
String name = cursor.getString(cursor
.getColumnIndex(NAME_COLUMN_NAME));
datalist.put(profileID, name);
}
}
} catch (Exception e) {
// TODO: handle exception
} finally {
if (cursor != null) {
cursor.close();
}
if (db != null) {
db.close();
}
}
return datalist;
}
答案 1 :(得分:1)
拥有如下的模型类:
class ModelProfileClass
{
// Constructor for ProfileID and Name
public ModelProfileClass (String PROFILE_ID, String UNAME)
{
this.profile_ID = PROFILE_ID;
this.uname = UNAME;
}
// getters and setters for ProfileID and Name
//get_PROFILEID(), get_UNAME() , set_PROFILEID(String profileID) , set_UNAME(String uname)
}
在你的主要课程中,
// Create a list of objects of ModelProfileClass
List<ModelProfileClass> profileList= new ArrayList<ModelProfileClass>();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
// For each iteration, making the object null
ModelProfileClass profileObject= null;
do {
// Constructor is invoked in the model class and so, the object values are set.
profileObject= new ModelProfileClass(
cursor.getString(0) ,
cursor.getString(1)
);
// Adding current object to the object array list
profileList.add(profileObject);
} while (cursor.moveToNext()); // Do this till the last record.
cursor.close();
如果您想要检索位置可用的记录,则必须使用:
String profileID = profileList.get(position).get_PROFILEID();
String uName = profileList.get(position).get_UNAME();