我在DB中使用整数时遇到问题。我在这里创建了一个SQLiteOpenHelper
将对DBAdapter:
public static final String KEY_ROWID="id";
public static final String KEY_EXR="name";
public static final String KEY_WGHT="weight";
public static final String KEY_REP="repetition";
public static final String KEY_DATE="duedate";
final static String[] columns = {KEY_ROWID, KEY_EXR, KEY_WGHT, KEY_REP};
final static String DATABASE_NAME = "ExerciseDB";
final static String DATABASE_TABLE = "exercisetb";
final static int DATABASE_VERSION = 2;
//DBAdapter için Loglar
private static final String TAG = "DBAdapter";
private static final String DATABASE_CREATE =
"create table if not exists exercisetb (id integer primary key autoincrement, "
+ "name VARCHAR not null, weight VARCHAR not null, repetition integer not null);";
插入:
public long insertRecord() {
ContentValues values = new ContentValues();
values.put(DBAdapter.KEY_EXR, name.toString());
values.put(DBAdapter.KEY_WGHT, weight.toString();
values.put(DBAdapter.KEY_REP, Integer.parseInt(repetition.toString()));
values.clear();
return mDbHelper.getWritableDatabase().insert(DBAdapter.DATABASE_NAME, null, values);
}
编辑: 我添加了insertRecord()来显示出现问题的步骤:
public long insertRecord() {
ContentValues values = new ContentValues();
values.put(DBAdapter.KEY_EXR, name.toString());
Log.i(TAG,"Name field assign.");
values.put(DBAdapter.KEY_WGHT, Integer.parseInt(weight.toString()));
Log.i(TAG,"weight assisgn.");
values.put(DBAdapter.KEY_REP, Integer.parseInt(repetition.toString()));
Log.i(TAG,"repetition field assign.");
values.clear();
return mDbHelper.getWritableDatabase().insert(DBAdapter.DATABASE_NAME, null, values);
}
尝试插入后记录输出:
04-07 15:23:25.217 3442-3442/com.example.alperen.exercisem I/addnew﹕ OnClick'e girildi
04-07 15:23:25.217 3442-3442/com.example.alperen.exercisem I/addnew﹕ Name field assign.
04-07 15:23:25.217 3442-3442/com.example.alperen.exercisem I/addnew﹕ weight assisgn.
04-07 15:23:25.217 3442-3442/com.example.alperen.exercisem D/AndroidRuntime﹕ Shutting down VM
04-07 15:23:25.217 3442-3442/com.example.alperen.exercisem W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x430ef140)
04-07 15:23:25.227 3442-3442/com.example.alperen.exercisem E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.alperen.exercisem, PID: 3442
java.lang.NumberFormatException: Invalid int: "android.widget.EditText{21d1d000 VFED..CL .F...... 0,166-720,249 #7f080043 app:id/repetition}"
at java.lang.Integer.invalidInt(Integer.java:137)
at java.lang.Integer.parse(Integer.java:374)
at java.lang.Integer.parseInt(Integer.java:365)
at java.lang.Integer.parseInt(Integer.java:331)
at com.example.alperen.exercisem.Addnew$1.insertRecord(Addnew.java:69)
最后一个变量出现问题。我们可以把KEY_EXR; KEY_WGHT但不是KEY_REP。如果我只将KEY_REP列更改为VARCHAR,那么我可以向该行添加数据。我可能在创建表格时犯了错误。
答案 0 :(得分:0)
对于非空字段,也请指定默认值。 此外,根据崩溃报告,还有数字格式例外。检查Integer.parseInt(repetition.toString()),很可能重复不是数值。
答案 1 :(得分:-1)
请在insertRecord()方法中注释行:
// values.clear();
因为它从值列表中清除了您的值,并且它不会更新表中的新行。