SQLite的使用:
1、编写DatabaseHelper类继承自SQLiteOpenHelper类,在DatabaseHelper类中实现三个方法:构造函数,onCreate,onUpgrade
public class DatebaseHelperextends SQLiteOpenHelper {
public static final StringTABLE_STUDENT ="shuju";
public static final StringCOLUMN_STUDENT_NUMBERS ="names";
// shuju
private Stringsql_create_student ="create table " +TABLE_STUDENT
+" ( _id integer primary key autoincrement ,"
+COLUMN_STUDENT_NUMBERS +")";
public DatebaseHelper(Context context) {
// 上下文,数据库文件名,null,数据库版本号
super(context, "Search.db", null, 1);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(sql_create_student);
}
public void onUpgrade(SQLiteDatabase db, int v1, int v2) {
}
}
2,编写对数据库操作的类
public class SearchUtil {
private static SQLiteDatabasedb;
private static DatebaseHelperdatebaseHelper;
private SearchUtil(Context context){
db =datebaseHelper.getWritableDatabase();
}
public static DatebaseHelpergetInstance(Context context){
if (datebaseHelper==null){
datebaseHelper =new DatebaseHelper(context);
}
return datebaseHelper;
}
public static void insert(String name){
ContentValues contentValues =new ContentValues();
contentValues.put("names",name);
db.insert(datebaseHelper.TABLE_STUDENT,null,contentValues);
}
public ListgetAllList(){
List name =new ArrayList<>();
Cursor cursor =db.query(datebaseHelper.TABLE_STUDENT,null,null,null,null,null,null,"names desc");
while (cursor.moveToNext()){
String names = cursor.getString(cursor.getColumnIndex(datebaseHelper.COLUMN_STUDENT_NUMBERS));
name.add(names);
}
return name;
}
}
添加语句,查询语句:
SearchUtil.getInstance(SearchActivity.this).insert(searchView.getQuery().toString());
SearchUtil.getInstance(SearchActivity.this).getAllList();