Search code examples
androidsqliteandroid-tablelayoutandroid-cursorsqliteopenhelper

AndroidDev: SQLite - Displaying values from DB into TableLayout?


I am working on an Android App for learning and it is based on the user being able to add their Pill/Medication, and then go to a 'Schedule' page where they can see the dosage and check if they have taken each dose.

I believe I have a successful Add page (where it adds the users entry to a SQLite database). However when I go to the 'Schedule' page to see the users entry, nothing is showing in the table row in the TableLayout. Not sure what I am missing? (maybe I have stared at the screen too long lol)

Here is my code for Schedule.java:

package cornez.com.pillreminder;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import org.w3c.dom.Text;

import java.text.SimpleDateFormat;

public class Schedule extends AppCompatActivity {
    //public class Schedule extends Activity implements View.OnClickListener, AdapterView.OnItemClickListener {

    private Context context;


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

        context=this;
        AndroidOpenDBHelper dataHelper=new AndroidOpenDBHelper(context);

        //Set Date Value
        TextView dateText = (TextView) findViewById(R.id.dateTV);
        long date = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy ");
        String dateString = sdf.format(date);
        dateText.setText(dateString);

        TableLayout scheduleTable = (TableLayout) findViewById(R.id.scheduleTable);         


        // Get data from sqlite database and add them to the table
        // Open the database for reading
        SQLiteDatabase db = dataHelper.getReadableDatabase();
        // Start the transaction.
        db.beginTransaction();

        try
        {
            String selectQuery = "SELECT COLUMN_NAME_NAME_OF_PILL, COLUMN_NAME_DOSAGE FROM "+ AndroidOpenDBHelper.TABLE_NAME_ADD_PILL;
            Cursor cursor = db.rawQuery(selectQuery,null);
            if(cursor.getCount() >0)
            {
                while (cursor.moveToNext()) {
                    // Read columns data
                    //int outlet_id= cursor.getInt(cursor.getColumnIndex("_id"));
                    String nameOfPill = cursor.getString(cursor.getColumnIndex("DetailsPojo.getNameOfPill()"));
                    String dosage = cursor.getString(cursor.getColumnIndex("DetailsPojo.getDosage()"));

                    // dara rows
                    TableRow row = new TableRow(context);
                    row.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
                            TableLayout.LayoutParams.WRAP_CONTENT));
                    String[] colText={nameOfPill,dosage};
                    for(String text:colText) {
                        TextView tv = new TextView(this);
                        tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
                                TableRow.LayoutParams.WRAP_CONTENT));
                        tv.setGravity(Gravity.CENTER);
                        tv.setTextSize(16);
                        tv.setPadding(5, 5, 5, 5);
                        tv.setText(text);
                        row.addView(tv);
                    }
                    scheduleTable.addView(row);

                }

            }
            db.setTransactionSuccessful();

        }
        catch (SQLiteException e)
        {
            e.printStackTrace();

        }
        finally
        {
            db.endTransaction();
            // End the transaction.
            db.close();
            // Close database
        }

    }
}

Code for AndroidOpenDBHelper.java:

package cornez.com.pillreminder;

/**
 * Created by Andrew on 4/9/2017.
 */


        import android.content.Context;
        import android.database.sqlite.SQLiteDatabase;
        import android.database.sqlite.SQLiteOpenHelper;
        import android.provider.BaseColumns;

// A helper class to manage database creation and version management.
public class AndroidOpenDBHelper extends SQLiteOpenHelper {
    // Database attributes
    public static final String DB_NAME = "pill_reminder_db";
    public static final int DB_VERSION = 1;

    // Table attributes
    public static final String TABLE_NAME_ADD_PILL = "add_pill";
    public static final String COLUMN_NAME_NAME_OF_PILL = "name_of_pill_column";
    public static final String COLUMN_NAME_DOSAGE = "dosage_column";
    public static final String COLUMN_NAME_FREQUENCY = "frequency_column";

    public AndroidOpenDBHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    // Called when the database is created for the first time.
    //This is where the creation of tables and the initial population of the tables should happen.
    @Override
    public void onCreate(SQLiteDatabase db) {
        // We need to check whether table that we are going to create is already exists.
        //Because this method get executed every time we created an object of this class.
        //"create table if not exists TABLE_NAME ( BaseColumns._ID integer primary key autoincrement, FIRST_COLUMN_NAME text not null, SECOND_COLUMN_NAME integer not null);"
        String sqlQueryToCreateDetailsTable = "create table if not exists " + TABLE_NAME_ADD_PILL + " ( " + BaseColumns._ID + " integer primary key autoincrement, "
                + COLUMN_NAME_NAME_OF_PILL + " text not null, "
                + COLUMN_NAME_DOSAGE + " text not null, "
                + COLUMN_NAME_FREQUENCY + " real not null);";
        // Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.
        db.execSQL(sqlQueryToCreateDetailsTable);
    }

    // onUpgrade method is use when we need to upgrade the database in to a new version
    //As an example, the first release of the app contains DB_VERSION = 1
    //Then with the second release of the same app contains DB_VERSION = 2
    //where you may have add some new tables or alter the existing ones
    //Then we need check and do relevant action to keep our pass data and move with the next structure
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if(oldVersion == 1 && newVersion == 2){
            // Upgrade the database
        }
    }
}

Code for DetailsPojo.java:

package cornez.com.pillreminder;

/**
 * Created by Andrew on 4/9/2017.
 */


public class DetailsPojo {

    private String nameOfPill;
    private String dosage;
    private String frequency;

    public String getNameOfPill() {
        return nameOfPill;
    }

    public void setNameOfPill(String nameOfPill) {

        this.nameOfPill = nameOfPill;
    }

    public String getDosage() {
        return dosage;
    }
    public void setDosage(String dosage) {
        this.dosage = dosage;
    }

    public String getFrequency() {
        return frequency;
    }
    public void setFrequency(String frequency) {
        this.frequency = frequency;
    }
}

Here is the AddPill.java file (adds the data to the DB):

package cornez.com.pillreminder;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import java.util.ArrayList;

public class AddPill extends AppCompatActivity implements View.OnClickListener {

    EditText editText;
    EditText editText2;
    Spinner spinner;
    Button saveBtn;

    private ArrayList addPillArrayList;


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

        editText = (EditText) findViewById(R.id.editText);
        editText2 = (EditText) findViewById(R.id.editText2);
        spinner = (Spinner) findViewById(R.id.spinner);
        saveBtn = (Button) findViewById(R.id.saveBtn);
        saveBtn.setOnClickListener(this);


        addPillArrayList = new ArrayList();

    }

    @Override
    public void onClick(View v) {
        // Get the values provided by the user via the UI
        String providedNameOfPill = editText.getText().toString();
        String providedDosage = editText2.getText().toString();
        String providedFrequency = spinner.getSelectedItem().toString();


        // Pass above values to the setter methods in POJO class
        DetailsPojo detailsPojoObj = new DetailsPojo();
        detailsPojoObj.setNameOfPill(providedNameOfPill);
        detailsPojoObj.setDosage(providedDosage);
        detailsPojoObj.setFrequency(providedFrequency);

        // Add an undergraduate with his all details to a ArrayList
        addPillArrayList.add(detailsPojoObj);

        // Inserting undergraduate details to the database is doing in a separate method
        insertPill(detailsPojoObj);


        //Toast pillAddedMsg = ;
        //finish();   THIS WILL RETURN TO ORIGINAL SCREEN, but maybe want to go to schedule instead
    }

    public void insertPill(DetailsPojo paraUndergraduateDetailsPojoObj){

        // First we have to open our DbHelper class by creating a new object of that
        AndroidOpenDBHelper androidOpenDbHelperObj = new AndroidOpenDBHelper(this);

        // Then we need to get a writable SQLite database, because we are going to insert some values
        // SQLiteDatabase has methods to create, delete, execute SQL commands, and perform other common database management tasks.
        SQLiteDatabase sqliteDatabase = androidOpenDbHelperObj.getWritableDatabase();

        // ContentValues class is used to store a set of values that the ContentResolver can process.
        ContentValues contentValues = new ContentValues();

        // Get values from the POJO class and passing them to the ContentValues class
        contentValues.put(AndroidOpenDBHelper.COLUMN_NAME_NAME_OF_PILL, paraUndergraduateDetailsPojoObj.getNameOfPill());
        contentValues.put(AndroidOpenDBHelper.COLUMN_NAME_DOSAGE, paraUndergraduateDetailsPojoObj.getDosage());
        contentValues.put(AndroidOpenDBHelper.COLUMN_NAME_FREQUENCY, paraUndergraduateDetailsPojoObj.getFrequency());

        // Now we can insert the data in to relevant table
        // I am going pass the id value, which is going to change because of our insert method, to a long variable to show in Toast
        long affectedColumnId = sqliteDatabase.insert(AndroidOpenDBHelper.TABLE_NAME_ADD_PILL, null, contentValues);

        // It is a good practice to close the database connections after you have done with it
        sqliteDatabase.close();

        // I am not going to do the retrieve part in this post. So this is just a notification for satisfaction ;-)
        Toast.makeText(this, "Values inserted column ID is :" + affectedColumnId, Toast.LENGTH_SHORT).show();

    }

}

Solution

  • String nameOfPill = cursor.getString(cursor.getColumnIndex("DetailsPojo.getNameOfPill()"));
    String dosage = cursor.getString(cursor.getColumnIndex("DetailsPojo.getDosage()"));
    

    I think the column names are mismatching from helper class.

    Use these

    String nameOfPill = cursor.getString(cursor.getColumnIndex(AndroidOpenDBHelper.COLUMN_NAME_NAME_OF_PILL));
    String dosage = cursor.getString(cursor.getColumnIndex(AndroidOpenDBHelper.COLUMN_NAME_DOSAGE));