jeudi 18 février 2016

Android SQLite cursor/adapter cannot get data from database

I have a gridview class here:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout

    xmlns:android="http://ift.tt/nIICcg"

    xmlns:tools="http://ift.tt/LrGmb4"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimaryDark"
    tools:context=".MainActivity">



    <LinearLayout
        android:id="@+id/topContent"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="7">

        <TextView
            android:id="@+id/textView0"
            android:background="@color/white"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="ID: "
            android:textSize="18sp"
            android:textColor="@color/black"
            android:gravity="center"
            />


        <TextView
            android:id="@+id/textView1"
            android:background="@color/purple"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/gridCode"
            android:textSize="18sp"
            android:textColor="@color/black"
            android:gravity="center"
            />

        <TextView
            android:id="@+id/textView2"
            android:background="@color/green"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/gridDay"
            android:textSize="18sp"
            android:textColor="@color/black"
            android:gravity="center"
            />

        <TextView
            android:id="@+id/textView3"
            android:background="@color/orange"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/gridStart"
            android:textSize="18sp"
            android:textColor="@color/black"
            android:gravity="center"
            />

        <TextView
            android:id="@+id/textView4"
            android:background="@color/blue"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/gridDuration"
            android:textSize="18sp"
            android:textColor="@color/black"
            android:gravity="center"
            />

        <TextView
            android:id="@+id/textView5"
            android:background="@color/yellow"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/gridType"
            android:textSize="18sp"
            android:textColor="@color/black"
            android:gravity="center"
            />

        <TextView
            android:id="@+id/textView6"
            android:background="@color/red"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/gridRoom"
            android:textSize="18sp"
            android:textColor="@color/black"
            android:gravity="center"
            />
    </LinearLayout>

    <GridView
        android:id="@+id/gridTable"
        android:layout_below="@+id/topContent"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:horizontalSpacing="10dip"
        android:verticalSpacing="15dip"
        android:stretchMode="columnWidth"
        android:gravity="center"

        android:numColumns="7"

        android:background="@color/colorPrimary"
        android:textSize="14sp"
        >
    </GridView>

</RelativeLayout> 

and a database helper:

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper
{
    //database information
    public static final String DATABASE_NAME    = "timetable.db";
    public static final String TABLE_NAME       = "timetable_data";

    //the data each column will store
    public static final String COL_1 = "ID";
    public static final String COL_2 = "CODE";
    public static final String COL_3 = "DAY";
    public static final String COL_4 = "START";
    public static final String COL_5 = "DURATION";
    public static final String COL_6 = "TYPE";
    public static final String COL_7 = "ROOM";


    //construct the database
    public DatabaseHelper(Context context)
    {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
        db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,CODE TEXT,DAY TEXT,START TEXT,DURATION TEXT,TYPE TEXT,ROOM TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
        onCreate(db);
    }

    public boolean insertData(String code, String day, String start, String duration, String type, String room)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_2,code);
        contentValues.put(COL_3,day);
        contentValues.put(COL_4,start);
        contentValues.put(COL_5,duration);
        contentValues.put(COL_6,type);
        contentValues.put(COL_7, room);

        long result = db.insert(TABLE_NAME,null,contentValues);
        if(result == -1)
            return false;
        else
            return true;
    }

    public Cursor getAllData()
    {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor data = db.rawQuery("select * from "+TABLE_NAME,null);
        return data;
    }

    public Integer deleteEntry(String id)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete(TABLE_NAME,"ID = ?", new String [] {id});
    }
}

I'm trying to populate this gridview with data stored in the database, everything compiles fine, but in the app i get an error saying that data from Col-1 (the id column) cannot be retrieved.

this is the gridviewactivity.java class mentioned in the above code:

import android.database.Cursor;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;

import java.util.ArrayList;

/**
 * Created by natha on 17/02/2016.
 *
 * This class gets all of the information in the getAllData() method, adds it to an array list,
 * then an array adapter reads the data from this array list and applies that data to the GridView.
 *
 */
public class GridViewActivity extends MainActivity
{
    private GridView gridTable;
    private ArrayList<String> moduleList;
    private ArrayAdapter<String> adapter;
    private Cursor data;

    DatabaseHelper timetableDB;

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

        //GridView
        gridTable=(GridView) findViewById(R.id.gridTable);

        //ArrayList
        moduleList  =   new ArrayList<>();
        adapter     =   new ArrayAdapter<>(getApplicationContext(),
                android.R.layout.simple_spinner_item,moduleList);

        String id, code, day, time, duration, type, room;

        id          =   "";
        code        =   "";
        day         =   "";
        time        =   "";
        duration    =   "";
        type        =   "";
        room        =   "";

        timetableDB = new DatabaseHelper(getBaseContext());//getting the context object

        timetableDB.getAllData();
        try
        {
            //for holding retrieve data from query and store in the form of rows
            Cursor data=timetableDB.getAllData();
            //Move the cursor to the first row.
            if(data.moveToFirst())
            {
                do
                {
                    id          =   data.getString(data.getColumnIndex    ("id"));
                    code        =   data.getString(data.getColumnIndex    ("code"));
                    day         =   data.getString(data.getColumnIndex    ("day"));
                    time        =   data.getString(data.getColumnIndex    ("time"));
                    duration    =   data.getString(data.getColumnIndex    ("duration"));
                    type        =   data.getString(data.getColumnIndex    ("type"));
                    room        =   data.getString(data.getColumnIndex    ("room"));

                    //add in to array list
                    moduleList  .   add(id);
                    moduleList  .   add(code);
                    moduleList  .   add(day);
                    moduleList  .   add(time);
                    moduleList  .   add(duration);
                    moduleList  .   add(type);
                    moduleList  .   add(room);

                    gridTable.setAdapter(adapter);

                }
                while(data.moveToNext());//Move the cursor to the next row.
            }
            else
            {
                Toast.makeText(getApplicationContext(),
                        "No data found", Toast.LENGTH_LONG).show();
            }
        }catch(Exception e)
        {
            Toast.makeText(getApplicationContext(),
                    "No data found "+e.getMessage(), Toast.LENGTH_LONG).show();
        }
        timetableDB.close();
    }
}

am i using the cursor correctly in this class?

thanks!

Aucun commentaire:

Enregistrer un commentaire