Android SQLite游标/适配器无法从数据库

时间:2016-02-18 12:35:45

标签: android sqlite gridview

我在这里有一个gridview类:

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

<RelativeLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    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> 

和数据库助手:

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

我尝试使用存储在数据库中的数据填充此gridview,所有内容编译都很好,但在应用程序中我收到一条错误消息,指出无法检索Col-1(id列)中的数据。

这是上面代码中提到的gridviewactivity.java类:

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

        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();
            moduleList  =   new ArrayList<>();

            //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);
                }
                while(data.moveToNext());//Move the cursor to the next row.
                adapter     =   new ArrayAdapter<>(getApplicationContext(),
                        android.R.layout.simple_spinner_item,moduleList);
                gridTable.setAdapter(adapter);
            }
            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();
    }
}

我在这个班级中正确使用光标吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

  

我在这个班级中正确使用光标吗?

是的,但问题是在错误的地方创建ArrayAdapter

在Cursor.like中添加moduleList ArrayList中的所有项后创建do{ // add items in moduleList } while(data.moveToNext());//Move the cursor to the next row. // create ArrayAdapter object here: adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_spinner_item,moduleList); // call setAdapter gridTable.setAdapter(adapter); 的对象:

{{1}}

答案 1 :(得分:0)

&#34; id&#34;专栏不存在。 当您创建数据库时,您正在使用&#34; ID&#34;作为列名而不是&#34; id&#34;所以当你调用data.getString(data.getColumnIndex(&#34; id&#34;));它无法找到该列。