80,351
社区成员
发帖
与我相关
我的任务
分享
package yeelone.sqlite;
…………包名
public class mySQLite extends ListActivity {
private static int NUM=0;
private static int version=2;
private ImageButton AddList=null;
List<HashMap<String,String>> list=new ArrayList<HashMap<String,String>>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AddList=(ImageButton)findViewById(R.id.addlist);
AddList.setOnClickListener(new addOnClickListener());
}
//当点击右上角的按钮时,弹出一个dialog,有一个输入框 可以输入内容。内容就是listview要显示的内容,这些内容
是一些标题 。
class addOnClickListener implements Button.OnClickListener{
@Override
public void onClick(View v) {
//创建名为Diary_db的数据库
MySQLhelper dbhelper=new MySQLhelper(mySQLite.this, "Diary_db");
SQLiteDatabase db=dbhelper.getReadableDatabase();
Intent intent=new Intent();
intent.setClass(mySQLite.this,addTitledialog.class);
mySQLite.this.startActivityForResult(intent, 1);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(resultCode)
{
//当弹出的dialog返回时,处理返回的输入的数据
case 1:
//Storage是我自己写的一个类,用于保存listview 的ID信息,还有内容变量
String sid=String.valueOf(Storage.getId());
String str=Storage.getTitle().toString();
String cont=Storage.getContent().toString();
System.out.println("id:"+ sid+" title:"+ str+" content:"+cont);
//设置listview中的内容,内容是标题。
setTitle(str);
MySQLhelper dbhelper=new MySQLhelper(mySQLite.this, "Diary_db",2);
SQLiteDatabase db=dbhelper.getWritableDatabase();
System.out.println("first create dbhelper");
ContentValues values=new ContentValues();
values.put("_id", sid);
values.put("title", str);
values.put("content", cont);
//将数据保存进Diary_db数据库Diary表中
db.insert("Diary", null, values);
break;
case 2:
update();
break;
}
}
private void setTitle(String str){
HashMap<String, String> map=new HashMap<String, String>();
map.put("title",str);
list.add(map);
SimpleAdapter adapter=new SimpleAdapter(this,list,R.layout.list_item,new String[]{"title"},new int[]{R.id.list_item});
setListAdapter(adapter);
}
…………………………………………
}
}
package yeelone.sqlopenhelper;
import ……………………
public class MySQLhelper extends SQLiteOpenHelper {
private static final int VERSION=1;
public MySQLhelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}
public MySQLhelper(Context context, String name) {
this(context, name,VERSION);
}
public MySQLhelper(Context context, String name,int version) {
this(context, name, null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table Diary(_id int primary key ,title varchar(255) not null, content text)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table Diary");
onCreate(db);
}
}