数据存储与显示
一、实验思路
1.掌握SQLite存储数据方法。
2.使用SQLiteOpenHelper辅助类,进行操作数据库
二、实验环境
1.jdk1.8.0_201
2.Android Studio3.3以上
3.Android 8.0(API level 26)
三、项目分析
1.创建一个app实现数据的输入与存储,以及显示。
2.所采用的主要技术
使用SQL语句操作SQLite数据库
四、部分代码
1.创建或打开数据库(此处需要使用绝对路径)
db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir()
.toString() + "/my.db3" , null);
2.获取用户输入
public void onClick(View source) {
String title = ((EditText)findViewById(R.id.title))
.getText().toString();
String content = ((EditText)findViewById(R.id.content))
.getText().toString();
3.查询以及存储与读取
try
{
insertData(db , title , content);
//查询news_info表的所有记录
Cursor cursor = db.rawQuery("select * from news_inf", null);
inflateList(cursor);
}
catch(SQLException se)
{
//执行DDL创建数据表
db.execSQL("create table news_inf(_id integer primary key autoincrement,"
+ " news_title varchar(50),"
+ " news_content varchar(255))");
//执行insert语句插入数据
insertData(db , title , content);
//查询news_info表的所有记录
Cursor cursor =db.rawQuery("select * from news_inf", null);
inflateList(cursor);
}
}
});
}
private void insertData(SQLiteDatabase db
, String title , String content)
{
//执行插入语句
db.execSQL("insert into news_inf values(null , ? , ?)"
, new String[]{title , content});
}
private void inflateList(Cursor cursor)
{
//填充SimpleCursorAdapter,注意控件的对应关系
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
MainActivity.this,
R.layout.line,cursor,
new String[]{"news_title" , "news_content"}
,new int[]{R.id.my_title,R.id.my_content},
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
//显示数据
listView.setAdapter(adapter);
}
码云地址:https://gitee.com/Wwmf/SQL
本程序代码经学习第一行代码和疯狂的安卓以及网上查阅资料完成,不足之处希望大家指出。