0

我正在學習Android應用程序,它基於用戶能夠添加他們的Pill/Medication,然後進入一個'Schedule'頁面,在那裏他們可以看到劑量並檢查他們是否服用了每個劑量。AndroidDev:SQLite - 從數據庫顯示值到TableLayout?

我相信我有一個成功的添加頁面(它將用戶條目添加到SQLite數據庫)。但是,當我轉到「計劃」頁面查看用戶條目時,TableLayout中的表格行中沒有顯示任何內容。不知道我錯過了什麼?

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 COLLUMN_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, " 
       + COLLUMN_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

這裏是我的Schedule.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; 
    } 
} 

這裏爲t他AddPill.java文件(數據添加到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.COLLUMN_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(); 

    } 

} 
+0

你確定的數據被存儲在DB中。請分享代碼以添加數據。 –

+0

好@SriMaharshi Manchem,我剛剛編輯我的帖子,以追加添加數據的AddPill.java代碼。讓我知道你的想法,並感謝你。 – DJPharaohCHS

+0

嗨請參考下面我的答案,然後再試一次。我認爲問題出在列名上。 –

回答

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

我認爲列名是從輔助類不匹配。

使用這些

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

謝謝,但它仍然是空的 – DJPharaohCHS

0

更改您的SQL查詢這樣

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

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