Je travaille sur une application Android pour apprendre et elle est basée sur la possibilité pour l'utilisateur d'ajouter sa pilule / médicament, puis d'accéder à une page `` Calendrier '' où il peut voir le dosage et vérifier s'il a pris chaque dose.

Je crois que j'ai une page d'ajout réussie (où elle ajoute l'entrée des utilisateurs à une base de données SQLite). Cependant, lorsque je vais à la page «Planification» pour voir l'entrée des utilisateurs, rien ne s'affiche dans la ligne du tableau dans le TableLayout. Vous ne savez pas ce qui me manque? (Peut-être ai-je regardé l'écran trop longtemps lol)

Voici mon code pour 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 pour 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
        }
    }
}

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

Voici le fichier AddPill.java (ajoute les données à la base de données):

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
DJPharaohCHS 20 avril 2017 à 07:44

3 réponses

Meilleure réponse
String nameOfPill = cursor.getString(cursor.getColumnIndex("DetailsPojo.getNameOfPill()"));
String dosage = cursor.getString(cursor.getColumnIndex("DetailsPojo.getDosage()"));

Je pense que les noms de colonnes ne correspondent pas à ceux de la classe d'assistance.

Utilisez ceux-ci

String nameOfPill = cursor.getString(cursor.getColumnIndex(AndroidOpenDBHelper.COLUMN_NAME_NAME_OF_PILL));
String dosage = cursor.getString(cursor.getColumnIndex(AndroidOpenDBHelper.COLUMN_NAME_DOSAGE));
1
SriMaharshi Manchem 21 avril 2017 à 05:29

Modifiez votre requête SQL comme ceci

  String selectQuery = " SELECT " + AndroidOpenDBHelper.COLUMN_NAME_NAME_OF_PILL + ","+ AndroidOpenDBHelper.COLUMN_NAME_DOSAGE FROM "+ AndroidOpenDBHelper.TABLE_NAME_ADD_PILL
0
Sandeep dhiman 20 avril 2017 à 05:44

Dans votre méthode onCreate, appelez la méthode suivante

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;
    }
0
Dilip 20 avril 2017 à 05:54