Inserting data into SQLite and displaying into ListView

落花浮王杯 提交于 2020-01-07 02:37:06

问题


I've been trying to insert data into my database but each time it crashes ("Unfortunatelty, has stopped.) each time when I try to insert data into my SQLite database. Hope some kind android programmer can help look through my code sample below.

This is my DbHelper java file used to create my table.

/** 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;
}
}

This is my DetailsPage activity where I'm asking the users to input data into the EditText fields. Some previous data were retrieved from intentdata. I understand that some of the items should be placed in another table but for now I'm using a static data saved in a class file. As for the GifImageView, I created another class to be able to play the Gif image.

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();
    }

}
}

I'm trying to display the table entries into another activity page made from a custom arrayadapter class. But currently I can't even access the page due to the program crashing.

The ViewTableEntriesPage coding is shown below.

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);
    }
}
}

Finally my customAdapter class file is shown below.

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;
}
}

As suggested here is the error stack trace.

02-20 01:04:51.729 21085-21085/com.example.beatthat E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.beatthat, PID: 21085 android.database.sqlite.SQLiteException: near "SET": syntax error (code 1): , while compiling: CREATE TABLE workout_sets (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, SET TEXT, REP TEXT) ################################################################# Error Code : 1 (SQLITE_ERROR) Caused By : SQL(query) error or missing database. (near "SET": syntax error (code 1): , while compiling: CREATE TABLE workout_sets (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, SET TEXT, REP TEXT)) ################################################################# at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method) at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1058) at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:623) at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588) at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:59) at android.database.sqlite.SQLiteStatement.(SQLiteStatement.java:31) at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1812) at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1743) at com.example.beatthat.data.ExerciseDbHelper.onCreate(ExerciseDbHelper.java:53) at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251) at 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) at android.view.View.performClick(View.java:5697) at android.widget.TextView.performClick(TextView.java:10826) at android.view.View$PerformClick.run(View.java:22526) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:158) at android.app.ActivityThread.main(ActivityThread.java:7225) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

来源:https://stackoverflow.com/questions/42329936/inserting-data-into-sqlite-and-displaying-into-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!