我一直在尝试将数据插入到我的数据库中,但每当我尝试将数据插入到我的SQLite数据库中时,它每次崩溃(" Unfortunatelty,已经停止。)希望某些Android程序员可以帮助查看下面的代码示例。
这是我用来创建表格的DbHelper java文件。
/** Name of the database file */
private static final String DATABASE_NAME = "beat_that.db";
/** Name of the table */
public final static String TABLE_WORKOUT_SETS = "workout_sets";
// Common column names
public final static String _ID = BaseColumns._ID;
// WORKOUT_SETS Table - column names
public final static String EXERCISE_NAME = "name";
public final static String EXERCISE_SET = "set";
public final static String EXERCISE_REP = "rep";
/** Database version.*/
private static final int DATABASE_VERSION = 1;
public ExerciseDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* This is called when the database is created for the first time.
*/
@Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_WORKOUT_SETS + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
" NAME TEXT, SET TEXT, REP TEXT)";
db.execSQL(createTable);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP IF TABLE EXISTS " + TABLE_WORKOUT_SETS);
onCreate(db);
}
public boolean addData(String name, String set, String rep) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(EXERCISE_NAME, name);
contentValues.put(EXERCISE_SET, set);
contentValues.put(EXERCISE_REP, rep);
long result = db.insert(TABLE_WORKOUT_SETS, null, contentValues);
//if data is inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
//query for 1 week repeats
public Cursor getListContents() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_WORKOUT_SETS, null);
return data;
}
}
这是我的DetailsPage活动,我要求用户将数据输入EditText字段。以前的一些数据是从intentdata中检索出来的。我知道有些项目应放在另一个表格中,但现在我使用保存在类文件中的静态数据。至于GifImageView,我创建了另一个能够播放Gif图像的类。
public class ExerciseDetailActivity extends AppCompatActivity{
/** EditText field to enter the exercise's set */
EditText mSetEditText;
/** EditText field to enter the exercise's rep */
EditText mRepEditText;
Button btnAddData, btnViewData;
ExerciseDbHelper myDb;
String exerciseName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exercise_detail);
// Initialize views
GifImageView imageView = (GifImageView) findViewById(R.id.exercise_image);
TextView shortDescText = (TextView) findViewById(R.id.exercise_short_desc);
btnAddData = (Button) findViewById(R.id.add_to_workout);
btnViewData = (Button) findViewById(R.id.view_workout);
mSetEditText = (EditText) findViewById(R.id.edit_set);
mRepEditText = (EditText) findViewById(R.id.edit_rep);
// Receive data
Intent intent = this.getIntent();
exerciseName = intent.getExtras().getString("exerciseName");
int imageId = intent.getExtras().getInt("imageId");
String shortDesc = intent.getExtras().getString("shortDesc");
//Bind data
setTitle(exerciseName);
imageView.setGifImageResource(imageId);
shortDescText.setText(shortDesc);
myDb = new ExerciseDbHelper(this);
btnViewData.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
Intent intent = new Intent(ExerciseDetailActivity.this,WorkoutSetActivity.class);
startActivity(intent);
}
});
// Set a click listener on that View
btnAddData.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the begin workout is clicked on.
@Override
public void onClick(View view) {
String name = exerciseName;
String set = mSetEditText.getText().toString().trim();
String rep = mRepEditText.getText().toString().trim();
if(name.length() != 0 && set.length() != 0 && rep.length() != 0){
AddData(name,set, rep);
mSetEditText.setText("");
mRepEditText.setText("");
}else{
Toast.makeText(ExerciseDetailActivity.this,"You must put something in the text field!",Toast.LENGTH_LONG).show();
}
}
});
}
private void AddData(String name,String set, String rep) {
boolean insertData = myDb.addData(name,set,rep);
if(insertData==true){
Toast.makeText(ExerciseDetailActivity.this,"Successfully Entered Data!",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(ExerciseDetailActivity.this,"Something went wrong :(.",Toast.LENGTH_LONG).show();
}
}
}
我试图将表条目显示到另一个自定义arrayadapter类的活动页面中。但由于程序崩溃,目前我甚至无法访问该页面。
ViewTableEntriesPage编码如下所示。
public class WorkoutSetActivity extends AppCompatActivity {
ExerciseDbHelper myDB;
ArrayList<WorkoutSet> workoutList;
ListView listView;
WorkoutSet workoutSet;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.exercise_list);
myDB = new ExerciseDbHelper(this);
workoutList = new ArrayList<>();
Cursor data = myDB.getListContents();
int numRows = data.getCount();
if(numRows == 0){
Toast.makeText(WorkoutSetActivity.this,"The Database is empty :(.",Toast.LENGTH_LONG).show();
}else{
int i=0;
while(data.moveToNext()){
workoutSet = new WorkoutSet(data.getString(1),data.getString(2),data.getString(3));
workoutList.add(i,workoutSet);
System.out.println(data.getString(1)+" "+data.getString(2)+" "+data.getString(3));
System.out.println(workoutList.get(i).getName());
i++;
}
WorkoutSetAdapter adapter = new WorkoutSetAdapter(this, R.layout.activity_workout_set, workoutList);
listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
}
}
最后我的customAdapter类文件如下所示。
public class WorkoutSetAdapter extends ArrayAdapter<WorkoutSet> {
private LayoutInflater mInflater;
private ArrayList<WorkoutSet> workoutSets;
private int mViewResourceId;
public WorkoutSetAdapter(Context context, int textViewResourceId ,ArrayList<WorkoutSet> workoutSets) {
super(context, textViewResourceId, workoutSets);
this.workoutSets = workoutSets;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mViewResourceId = textViewResourceId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if the existing view is being reused, otherwise inflate the view
convertView = mInflater.inflate(mViewResourceId, null);
// Get the {@link Word} object located at this position in the list
WorkoutSet currentWorkout = getItem(position);
if (currentWorkout != null) {
// Find individual views that we want to modify in the list item layout
TextView nameTextView = (TextView) convertView.findViewById(R.id.workout_name);
TextView setTextView = (TextView) convertView.findViewById(R.id.workout_set);
TextView repTextView = (TextView) convertView.findViewById(R.id.workout_rep);
// Update the TextViews with the attributes for the current workout
if (nameTextView != null) {
nameTextView.setText(currentWorkout.getName());
}
if (setTextView != null) {
setTextView.setText(("Sets: "+ currentWorkout.getSet()));
}
if (repTextView != null) {
repTextView.setText(("Reps: "+ currentWorkout.getRep()));
}
}
// Return the whole list item layout (containing 2 TextViews and an ImageView)
// so that it can be shown in the ListView
return convertView;
}
}
这里建议的是错误堆栈跟踪。
02-20 01:04:51.729 21085-21085 / com.example.beatthat E / AndroidRuntime:FATAL EXCEPTION:main 处理:com.example.beatthat,PID:21085 android.database.sqlite.SQLiteException:near&#34; SET&#34 ;:语法错误(代码1):,编译时:CREATE TABLE workout_sets(ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,SET TEXT,REP TEXT) ################################################## ############### 错误代码:1(SQLITE_ERROR) 引起:SQL(查询)错误或缺少数据库。 (附近&#34; SET&#34 ;:语法错误(代码1):,编译时:CREATE TABLE workout_sets(ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,SET TEXT,REP TEXT)) ################################################## ############### 在android.database.sqlite.SQLiteConnection.nativePrepareStatement(本机方法) 在android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1058) 在android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:623) 在android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588) 在android.database.sqlite.SQLiteProgram。(SQLiteProgram.java:59) 在android.database.sqlite.SQLiteStatement。(SQLiteStatement.java:31) 在android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1812) 在android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1743) 在com.example.beatthat.data.ExerciseDbHelper.onCreate(ExerciseDbHelper.java:53) 在android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251) 在android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163) at com.example.beatthat.data.ExerciseDbHelper.addData(ExerciseDbHelper.java:64) at com.example.beatthat.ExerciseDetailActivity.AddData(ExerciseDetailActivity.java:106) at com.example.beatthat.ExerciseDetailActivity.access $ 000(ExerciseDetailActivity.java:15) at com.example.beatthat.ExerciseDetailActivity $ 2.onClick(ExerciseDetailActivity.java:93) 在android.view.View.performClick(View.java:5697) 在android.widget.TextView.performClick(TextView.java:10826) 在android.view.View $ PerformClick.run(View.java:22526) 在android.os.Handler.handleCallback(Handler.java:739) 在android.os.Handler.dispatchMessage(Handler.java:95) 在android.os.Looper.loop(Looper.java:158) 在android.app.ActivityThread.main(ActivityThread.java:7225) at java.lang.reflect.Method.invoke(Native Method) 在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1230) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)