我正在学习编码,并制作了一个秒表,它将字符串保存在字符串中,并将日期也作为字符串来获取。我想把它们放在一个SQLite数据库中(这样我以后可以在一个listview中显示日期,并在另一个显示所有laptimes的活动中打开它)。我已经在互联网上跟踪了一些代码并尝试将这些代码放在一起所以我可能会查看我的代码中的一些内容。我已经评论了我认为我理解的部分,所以你可以按照我的想法做一点。Android Java SQLite数据库:数据库不需要2个字符串输入
问题:当我按下保存下面的代码执行并返回toastmessage:Somehting出错了。
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String dateStamp = getCurrentTimeStamp();
AddData(dataInput, dateStamp);
//DatabaseHelper.deleteAll();
}
}); //save data though AddData method as input the listText
的方法addData为如下:
public void AddData(String time, String date) {
boolean insertData = DatabaseHelper.addData(time, date);
if (insertData) {
toastMessage(dataInput);
} else {
toastMessage("Something went wrong");
}
}
在DatabaseHelper类布尔方法是这样的:
public boolean addData(String times, String date) { //addData that takes a string
SQLiteDatabase db = this.getWritableDatabase(); //database called db and use getWritableDatabase method
ContentValues contentValues = new ContentValues(); //make a new object of ContentValues
contentValues.put(COL_2, times); //put COL_2 and the String in the ContentValues object
contentValues.put(COL_3, date);
long result = db.insert(TABLE_NAME, null, contentValues); //insert contentValues object into the table
//if date as inserted incorrectly it will return -1
if (result == -1) {
db.close();
return false;
} else {
return true;
}
}
它的工作原理,当我在addData输入只是1个变量()但是不是我以后实施的2。我认为它应该工作。下面我还将用于制作SQLite数据库的代码放入其中。
public static final String TABLE_NAME = "stopwatch"; //make a table with name
public static final String COL_1 = "ID"; //make an ID for every colomn
public static final String COL_2 = "times"; //make a 2nd colomn for data
public static final String COL_3= "date";
public DatabaseHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) { //make the onCreate method that takes the database as input
String createTable = "CREATE TABLE " + TABLE_NAME + " (" + COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_2 +" TEXT" + COL_3 +" TEXT)"; //create the table with SQL statements to input the data correctly
db.execSQL(createTable); //input the SQL statements in the DB
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { //make upgrade method that takes the database and the versions
db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME); //execute SQL statements drop table and which one
onCreate(db); //run through create method
}
我希望有人能帮助我找到问题,以便我可以了解更多。
SQL语句是'DROP TABLE IF EXISTS .....''DROP IF TABLE EXISTS ....' – Titus
谢谢!我已经从另一个代码中复制了这些内容,并试图查看不同的内容,但作为初学者,我仍然错过了那些小东西 – Tmen