mercredi 17 février 2016

Why does an empty query return when there should be data in the SQLite database?

I'm working an an Android app that keeps track of workout progress using a SQLite database. In this database I have created six different tables to keep track of various data. My problem is when I attempt to retrieve data from one of the tables. I surrounded a Select all query with a try catch block, and it turns out it is returning an empty query. In my Oncreate method within the database handler I have added (or attempted to add) data into one of my tables. Unfortunately it does not seem add it, or at least not when the query is run. If anyone can spot the problem and help me with it that would be great. Thanks.

Below is the class that handles the database:

package com.dwolford.workoutroutine;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;

//import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * Manages the Workout Tracker database
 */
public class DatabaseHandler extends SQLiteOpenHelper{


// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String WORKOUT_TRACKER_DB = "WorkoutTrackerDB";

private static final String TABLE_DISTANCE_EXERCISE = "distance_exercise";
private static final String TABLE_REPETITION_EXERCISE = "repetition_exercise";
private static final String TABLE_DISTANCE_WORKOUT = "distance_workout";
private static final String TABLE_REPETITION_WORKOUT = "repetition_workout";
private static final String TABLE_DISTANCE_PROGRESS = "distance_progress";
private static final String TABLE_REPETITION_PROGRESS = "repetition_progress";

private static final String EXERCISE_NAME = "exercise_name";
private static final String REPETITIONS = "repetitions";
private static final String WORKOUT_NAME = "workout_name";
private static final String DATE = "date";
private static final String ID = "id";
private static final String DISTANCE = "distance";
private static final String WEIGHT = "weight";
private static final String TIME = "time";
private static final String COMMENT = "comment";



/**
 * Creates the statements for the distance exercise table
 */
private static final String CREATE_DISTANCE_EXERCISE_TABLE = "CREATE TABLE " + TABLE_DISTANCE_EXERCISE + "("
        + EXERCISE_NAME + " TEXT," + ID + " INTEGER" + ")";

/**
 * Creates the statements for the repetition exercise table
 */
String CREATE_TABLE_REPETITION_EXERCISE_TABLE = "CREATE TABLE " + TABLE_REPETITION_EXERCISE + "("
        + EXERCISE_NAME + " TEXT" + ID + " INTEGER" + ")";

/**
 * Creates the statements for the distance workout table
 */
String CREATE_DISTANCE_WORKOUT_TABLE = "CREATE TABLE " + TABLE_DISTANCE_WORKOUT + "("
        + WORKOUT_NAME + " TEXT PRIMARY KEY," + ID + " INTEGER,"
        + DISTANCE + " FLOAT," + TIME + " FLOAT" +")";

/**
 * Creates the statements for the repetition workout table
 */
String CREATE_TABLE_REPETITION_WORKOUT_TABLE = "CREATE TABLE " + TABLE_REPETITION_WORKOUT + "("
        + WORKOUT_NAME + " TEXT PRIMARY KEY," + EXERCISE_NAME + " TEXT,"
        + REPETITIONS + " INTEGER," + WEIGHT + " FLOAT" + ")";

/**
 * Creates the statements for the distance progress table
 */
String CREATE_DISTANCE_PROGRESS_TABLE = "CREATE TABLE " + TABLE_DISTANCE_PROGRESS + "("
        + ID + " INTEGER PRIMARY KEY," + DATE + " TEXT,"//Figure out how to store date
        + DISTANCE + " FLOAT," + TIME + " FLOAT," + COMMENT + " TEXT" +")";

/**
 * Creates the statements for the distance progress table
 */
String CREATE_TABLE_REPETITION_PROGRESS_TABLE = "CREATE TABLE " + TABLE_REPETITION_PROGRESS + "("
        + ID + " INTEGER PRIMARY KEY," + DATE + " TEXT,"//Figure out how to store date
        + REPETITIONS + " INTEGER" + WEIGHT + " FLOAT," + COMMENT + " TEXT" +")";


public DatabaseHandler(Context context) {
    super(context, WORKOUT_TRACKER_DB, null, DATABASE_VERSION);
}


// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {

    WorkoutTracker tracker = new WorkoutTracker();

    db.execSQL(CREATE_DISTANCE_EXERCISE_TABLE);
    db.execSQL(CREATE_TABLE_REPETITION_EXERCISE_TABLE);
    db.execSQL(CREATE_DISTANCE_WORKOUT_TABLE);
    db.execSQL(CREATE_TABLE_REPETITION_WORKOUT_TABLE);
    db.execSQL(CREATE_DISTANCE_PROGRESS_TABLE);
    db.execSQL(CREATE_TABLE_REPETITION_PROGRESS_TABLE);

    //db.execSQL(("insert into " + TABLE_REPETITION_EXERCISE + " (" + EXERCISE_NAME + ", " + ID + ") values('Farmer Walk', '100000');"));
    //Add in pre-existing exercises
    tracker.setExerciseName("Clean Deadlift");
    addNewRepExercise(tracker);
    tracker.setExerciseName("Hammer Curl");
    addNewRepExercise(tracker);
    tracker.setExerciseName("Incline Hammer Curl");
    addNewRepExercise(tracker);
    tracker.setExerciseName("Clean and Jerk");
    addNewRepExercise(tracker);

    /*addNewRepExercise("Front Dumbbell Raise");
    addNewRepExercise("Dumbbell Triceps Extension");
    addNewRepExercise("Squat");
    addNewRepExercise("Leg Raise");
    addNewRepExercise("Calf Raise");
    addNewRepExercise("Bicep Curl");
    addNewRepExercise("Spider Curl");
    addNewRepExercise("Cable Row");*/

}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_DISTANCE_EXERCISE);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_DISTANCE_WORKOUT);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_REPETITION_WORKOUT);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_DISTANCE_PROGRESS);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_REPETITION_PROGRESS);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_REPETITION_EXERCISE);

    // Create tables again
    onCreate(db);
}


/**
 *
 * Pulls all exercises from the repetition table
 */
public List<WorkoutTracker> getAllRepExercises(Context context)
{
    List<WorkoutTracker> exerciseList = new ArrayList<WorkoutTracker>();

    // Select all exercises from database
    String selectQuery = "SELECT * FROM " + TABLE_REPETITION_EXERCISE;
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = null;

    //addNewRepExercise(new WorkoutTracker(100000, "Pull Ups"));

    try
    {
        cursor = db.rawQuery(selectQuery, null);
        if(cursor != null)
        {
            try
            {
                if(cursor.moveToFirst())
                {
                    do {
                        WorkoutTracker exercise = new WorkoutTracker();
                        //Get exercise name from database
                        exercise.setExerciseName(cursor.getString(0));
                        //Get exercise ID from database
                        exercise.setID(Integer.parseInt(cursor.getString(1)));
                        // Adding exercise to list
                        exerciseList.add(exercise);
                        Toast.makeText(context.getApplicationContext(), "It Works", Toast.LENGTH_LONG).show();
                    }while(cursor.moveToNext());
                }
                else
                {
                    //No results from query
                    Toast.makeText(context.getApplicationContext(), "Empty Query", Toast.LENGTH_LONG).show();
                }

            }
            finally
            {
                cursor.close();
            }
        }
    }
    catch(SQLiteException exception)//If exception is found
    {

        //Display exception
        Toast.makeText(context.getApplicationContext(), exception.toString(), Toast.LENGTH_LONG).show();
    }

    // looping through all rows and adding to list
    /*if (cursor.moveToFirst()) {
        do {
            WorkoutTracker exercise = new WorkoutTracker();
            //Get exercise name from database
            exercise.setExerciseName(cursor.getString(0));
            //Get exercise ID from database
            exercise.setID(Integer.parseInt(cursor.getString(1)));
            // Adding exercise to list
            exerciseList.add(exercise);
        } while (cursor.moveToNext());
    }*/

    // return exercise list
    return exerciseList;
}



/**
 *
 * Pulls all exercises from the distance table
 */
public List<WorkoutTracker> getAllDistanceExercises()
{
    List<WorkoutTracker> exerciseList = new ArrayList<WorkoutTracker>();

    // Select all exercises from database
    String selectQuery = "SELECT  * FROM " + TABLE_DISTANCE_EXERCISE;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            WorkoutTracker exercise = new WorkoutTracker();
            //Get exercise name from database
            exercise.setExerciseName(cursor.getString(0));
            //Get exercise ID from database
            exercise.setID(Integer.parseInt(cursor.getString(1)));
            // Adding exercise to list
            exerciseList.add(exercise);
        } while (cursor.moveToNext());
    }
    // return exercise list
    return exerciseList;
}


 /*
    Adds completed user exercise to the database. This includes the exercise name, date, and number of repetitions
 */
public void addExerciseRep(String exerciseName, Date date, Double repetitions) {
    SQLiteDatabase db = this.getWritableDatabase();

    //Format date before placing in database
    SimpleDateFormat dateFormat = new SimpleDateFormat(("yyyy-MM-dd"));
    String formatDate = dateFormat.format(date);

    ContentValues values = new ContentValues();
    values.put(EXERCISE_NAME, exerciseName); // Exercise name
    values.put(DATE, formatDate); // Exercise date
    values.put(REPETITIONS, repetitions); // Exercise number of repetitions

    // Inserting Row
    //db.insert(TABLE_PROGRESS, null, values);
    db.close(); // Closing database connection
}


/*
Adds a new repetition exercise to the database
*/
public void addNewRepExercise(WorkoutTracker tracker) {
    SQLiteDatabase db = this.getWritableDatabase();

    //Checking to see if exercise by that name already exists
    //Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM TABLE_REPETITION_EXERCISE WHERE EXERCISE_NAME LIKE'" + exerciseName + "'", null);

    //Generate new random number
    Random rand = new Random();
    //Generates a random number as an ID between 100001 and 499998
    int randomID = (rand.nextInt(499999-100000) + 100000);

    ContentValues values = new ContentValues();
    values.put(EXERCISE_NAME, tracker.getExerciseName()); // Exercise Name
    values.put(ID, randomID); // Exercise ID

    // Inserting Row
    db.insert(TABLE_REPETITION_EXERCISE, null, values);
    db.close(); // Closing database connection
}


/*
Adds a new workout routine to the database
*/
public void addNewWorkoutRoutine(String workoutName, String[] exerciseName, Double[] repetitions) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();

    //Until there are no more exercises, place in database unter workout name
    for(int i = 0; i < exerciseName.length; i++)
    {
        values.put(EXERCISE_NAME, exerciseName[i]); // Exercise Name
        values.put(REPETITIONS, repetitions[i]); // Number of repetitions
        values.put(WORKOUT_NAME, workoutName); // Workout Name
        // Inserting Row
        //db.insert(TABLE_EXERCISE, null, values);
    }


    db.close(); // Closing database connection
}


/*
    Getting repetitions progress information from one specific day
*/
public String[] getDateWorkout(Date date) {
    String nameDateReps[] = new String[3];
    SQLiteDatabase db = this.getReadableDatabase();

    //Format date before looking for it in database
    SimpleDateFormat dateFormat = new SimpleDateFormat(("yyyy-MM-dd"));
    String formatDate = dateFormat.format(date);


    Cursor cursor = db.query(TABLE_REPETITION_PROGRESS, new String[] { EXERCISE_NAME,
                    DATE, REPETITIONS }, DATE + "=?",
            new String[] { String.valueOf(formatDate) }, null, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();

    nameDateReps[0] = cursor.getString(0);//get Exercise name
    nameDateReps[1] = cursor.getString(1);//get Exercise date
    nameDateReps[2] = cursor.getString(2);//get Exercise repetitions

    // return array with name, date, and repetitions
    return nameDateReps;
}


// Getting all repetition workout progress
public List<String> getAllContacts() {
    List<String> progressList = new ArrayList<String>();//Contains all workout progress
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_REPETITION_PROGRESS;

    String exerciseName = "";
    String date = "";
    String repetitions = "";
    int ID = 0;
    String comment = "";

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            exerciseName = cursor.getString(0);
            date = cursor.getString(1);
            repetitions = cursor.getString(2);
            // Adding contact to list
            progressList.add((exerciseName + " " + date + " " + repetitions));
        } while (cursor.moveToNext());
    }

    // return contact list
    return progressList;
}
}

Below is the class that manages and gets the data that will be used by the DatabaseHandler class:

package com.dwolford.workoutroutine;

/**
 * Created by David Wolford on 1/31/2016.
 * This class is utilized to get and modify the variables used in the           tracking of information in the database system
 */
public class WorkoutTracker {

int repetitions;
String date;
String exerciseName;
String comment;
int ID;
double weight;
double distance;
String routineName;
double time;

// Empty constructor
public WorkoutTracker(){

}

// constructor used for saving and modifying exercises
public WorkoutTracker(int id, String ex_name){
    this.ID = id;
    this.exerciseName = ex_name;
}

// constructor for distance progress
public WorkoutTracker(int ID, double Distance, double Time, String Date, String Comment){
    this.ID = ID;
    this.distance = Distance;
    this.date = Date;
    this.comment = Comment;
    this.time = Time;
}


// constructor for repetition progress
public WorkoutTracker(int ID, double Weight, int Repetitions, String Date, String Comment){
    this.ID = ID;
    this.repetitions = Repetitions;
    this.weight = Weight;
    this.date = Date;
    this.comment = Comment;
}


// constructor for repetition workouts
public WorkoutTracker(int ID, double Weight, int Repetitions, String RoutineName){
    this.ID = ID;
    this.routineName = RoutineName;
    this.weight = Weight;
    this.repetitions = Repetitions;
}

// constructor for distance workouts
public WorkoutTracker(int ID, double Distance, double Time, String RoutineName){
    this.ID = ID;
    this.routineName = RoutineName;
    this.distance = Distance;
    this.time = Time;
}

// getting ID
public int getID(){
    return this.ID;
}

// setting id
public void setID(int id){
    this.ID = id;
}

// getting exercise name
public String getExerciseName(){
    return this.exerciseName;
}

// setting exercise name
public void setExerciseName(String name){
    this.exerciseName = name;
}

// getting reps
public double getReps(){
    return this.repetitions;
}

// setting reps
public void setReps(int Repetitions){
    this.repetitions = Repetitions;
}

// getting time
public double getTime(){
    return this.time;
}

// setting time
public void setTime(double Time){
    this.time = Time;
}

// getting weight
public double getWeight(){
    return this.weight;
}

// setting weight
public void setWeight(double Weight){
    this.weight = Weight;
}

// getting Date
public String getDate(){
    return this.date;
}

// setting Date
public void setDate(String Date){
    this.date = Date;
}

// getting Comment
public String getComment(){
    return this.comment;
}

// setting Comment
public void setComment(String Comment){
    this.comment = Comment;
}

// getting Distance
public double getDistance(){
    return this.distance;
}

// setting Distance
public void setDistance(double Distance){
    this.distance = Distance;
}

// getting Routine name
public String getRoutineName(){
    return this.routineName;
}

// setting Distance Routine name
public void setRoutineName(String RoutineName){
    this.routineName = RoutineName;
}
}

And below is the class in which I am attempting to access the database using the helper class:

package com.dwolford.workoutroutine;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;


public class CreateRepWorkout extends Activity {

Spinner ExerciseDrop;
Button Back;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_create_rep_workout);

    DatabaseHandler db = new DatabaseHandler(this);

    db.addNewRepExercise(new WorkoutTracker(100002, "Farmer Walk"));

    /**
     * Lists the exercise options that can be added
     */
    ExerciseDrop = (Spinner)findViewById(R.id.exerciseDrop);



    Context context = this;
    //Holds all the available exercises
    List<WorkoutTracker> exerciseList = db.getAllRepExercises(context);
    //Create adapter to allow exercises to be displayed in spinner
    ArrayAdapter<WorkoutTracker> adapter = new ArrayAdapter<WorkoutTracker>(this, android.R.layout.simple_spinner_item,exerciseList);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    ExerciseDrop.setAdapter(adapter);
    ExerciseDrop.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText((getBaseContext()), (parent.getItemIdAtPosition(position) + 2) + " selected", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });


    Back = (Button)findViewById(R.id.back);
    Back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_create_rep_workout, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

Aucun commentaire:

Enregistrer un commentaire