布局文件如下:
<?xml version="1.0" encoding="utf-8"?>Activity代码如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.sqlite.MainActivity"
android:orientation="vertical">
<EditText
android:id="@+id/et_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<EditText
android:id="@+id/et_desc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/btn_insert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="insert"/>
<ListView
android:id="@+id/lv_info"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
public class MainActivity extends AppCompatActivity {运行效果:
private SQLiteDatabase db;
private Button btn_insert;
private EditText et_name,et_desc;
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// null表示使用默认的工厂
db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString()+"/my.db3",null);
btn_insert = (Button) findViewById(R.id.btn_insert);
listView = (ListView) findViewById(R.id.lv_info);
et_name = (EditText) findViewById(R.id.et_name);
et_desc = (EditText) findViewById(R.id.et_desc);
btn_insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = et_name.getText().toString();
String desc = et_desc.getText().toString();
try{
insertData(db,name,desc);
Cursor cursor = db.rawQuery("select * from news_info",null);
inflateCursor(cursor);
}catch (SQLiteException e){
db.execSQL("create table news_info(_id integer primary key autoincrement," +
" news_name varchar(50),news_desc varchar(255))");
insertData(db,name,desc);
Cursor cursor = db.rawQuery("select * from news_info",null);
inflateCursor(cursor);
}
}
});
}
private void insertData(SQLiteDatabase db,String name,String desc){
db.execSQL("insert into news_info values(null,?,?)",
new String[]{name,desc});
}
private void inflateCursor(Cursor cursor){
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.line,cursor,
new String[]{"news_name","news_desc"},new int[]{R.id.news_name,R.id.news_desc},
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
listView.setAdapter(adapter);
}
@Override
protected void onDestroy() {
super.onDestroy();
if(db != null && db.isOpen()){
db.close();
}
}
}