下面将map保存到数据表中,下面的代码中忘记对 ois.close(); fis.close();
public boolean savemap(HashMap info) {
String sql = "";
try {
ByteArrayOutputStream fis = new ByteArrayOutputStream();
ObjectOutputStream ois = new ObjectOutputStream(fis);
ois.writeObject(info);
byte[] tbyte2 = fis.toByteArray();
sql = "insert into t_user values(null,?);";
Object[] args = new Object[]{tbyte2};
/*
sql = "insert into t_user values(null,?,?);";
Object[] args = new Object[]{tbyte2,tbyte2};
几个?在new object就要加入几个数据值
*/
m_db.execSQL(sql,args);
Log.v(TAG, "insert Table t_user ok");
return true;
} catch (Exception e) {
Log.v(TAG, "insert Table t_user err ,sql: " + sql);
return false;
}
}
下面在数据表中取得map数据,放入列表中。下面的代码中忘记对 fis.close();
public List> getmaptolist() {
List> List = new ArrayList>();
Cursor cur = loadAll();
if(cur == null)
return null;
cur.moveToFirst();
while (!cur.isAfterLast()) {
ByteArrayInputStream fis = new ByteArrayInputStream(cur.getBlob(1)); //ID(0) NAME(1)
ObjectInputStream ois=null;
try {
ois = new ObjectInputStream(fis);
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(ois == null)
{
cur.moveToNext();
continue;
}
HashMap ted =null;
try {
ted = (HashMap) ois.readObject();
} catch (OptionalDataException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ois.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List.add((Map) ted);
cur.moveToNext();
}
cur.close();
return List;
}
private static Cursor loadAll() {
//表里就放了两个字段ID编号,NAME存放map ID(0) NAME(1)
Cursor cur = m_db.query("t_user", new String[] { "_ID", "NAME" }, null,
null, null, null, null);
return cur;
}
下面是我的表的创建
private void CreateTable() {
try {
m_db.execSQL("CREATE TABLE IF NOT EXISTS t_user ("
+ "_ID INTEGER PRIMARY KEY autoincrement," + "NAME BLOB"
+ ");");
Log.v(TAG, "Create Table t_user ok");
} catch (Exception e) {
Log.v(TAG, "Create Table t_user err,table exists.");
}
}