AndroidDev:SQLite - 将数据库中的值显示到 TableLayout 中?

AndroidDev: SQLite - Displaying values from DB into TableLayout?

我正在开发一个用于学习的 Android 应用程序,它基于用户能够添加他们的 Pill/Medication,然后转到他们可以访问的 'Schedule' 页面查看剂量并检查他们是否服用了每一剂。

我相信我有一个成功的添加页面(它将用户条目添加到 SQLite 数据库)。但是,当我转到 'Schedule' 页面查看用户条目时,TableLayout 的 table 行中没有显示任何内容。不确定我错过了什么? (可能是我看屏幕时间太长了哈哈)

这是我的 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
        }

    }
}

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

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

这是 AddPill.java 文件(将数据添加到数据库):

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

    }

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

我认为列名与助手 class 不匹配。

使用这些

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

像这样更改您的 sql 查询

  String selectQuery = " SELECT " + AndroidOpenDBHelper.COLUMN_NAME_NAME_OF_PILL + ","+ AndroidOpenDBHelper.COLUMN_NAME_DOSAGE FROM "+ AndroidOpenDBHelper.TABLE_NAME_ADD_PILL

在您的 onCreate 方法中调用以下方法

public List<DetailsPojo> getAllDetails() {
        List<DetailsPojo> DetailsPojoList = new ArrayList<DetailsPojo>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + AndroidOpenDBHelper.TABLE_NAME_ADD_PILL;

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

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                DetailsPojo cellinfo = new DetailsPojo();
                cellinfo.setNameOfPill(cursor.getString(0));
                cellinfo.setDosage(cursor.getString(1));
                cellinfo.setFrequency(cursor.getString(2));

                DetailsPojoList.add(cellinfo);
            } while (cursor.moveToNext());
        }

        return DetailsPojoList;
    }