无法从SQLite DB填充Spinner

时间:2015-03-15 16:33:17

标签: android sqlite spinner

我经历了几个教程,尝试从本地SQLite数据库填充微调器。我已经创建了一个成功将项目插入数据库的类,但是当我尝试填充微调器时,当我尝试将数据附加到微调器时它似乎失败了(但是那个数据究竟是什么,我不确定..哈哈)我已经尝试了多种方法来做到这一点但每次都得到同样的错误。任何人都可以解释为什么会发生这种情况,或者可能的解决方案是,我会非常感激。

我的Spinner on postreview.xml:

<Spinner
    android:id="@+id/category_spinner"
    android:layout_width="fill_parent"
    android:layout_height="50dp"
    android:layout_alignParentLeft="true"
    android:layout_marginRight="15dp"
    android:layout_below="@+id/category_label"
    android:layout_marginLeft="15dp" 
    android:textSize="8dp" 
    android:prompt="@string/spinner_title"
    />

我的评论页面活动:

package ca.nait.kerickson16;

import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class PostReview extends Activity implements OnClickListener
{
// Spinner element
Spinner categorySelect;

DBManager db = new DBManager(this);
static final String TAG = "PostReview";
@Override
protected void onCreate(Bundle savedInstanceState) 
{
    categorySelect = (Spinner) findViewById(R.id.category_spinner);
    loadSpinnerCategories();

    super.onCreate(savedInstanceState);
    setContentView(R.layout.postreview);
}

public void onClick(View view) 
{


}

public void loadSpinnerCategories() 
{
    // database handler
    db = new DBManager(PostReview.this);
     Log.d(TAG,"New DB Handler");
    // Spinner Drop down elements
    List<String> categories = db.getAllCategories();
    Log.d(TAG,"Got List of Categories");

    // Creating adapter for spinner
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, categories);
    Log.d(TAG,"Created Adapter for spinner");

    // Drop down layout style - list view with radio button
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    Log.d(TAG,"list view with radio button");
    // attaching data adapter to spinner
    categorySelect.setAdapter(dataAdapter);
}

}

我的数据库处理程序文件:     包ca.nait.kerickson16;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;

public class DBManager extends SQLiteOpenHelper
{
// global variables & constants
static final String TAG = "DBManager";
static final String DB_NAME = "hotOrNot.db";
static final int DB_VERSION = 1;
static final String TABLE = "hotOrNot";
static final String C_ID = BaseColumns._ID;
static final String C_CATEGORY = "category";


// Constructor
public DBManager(Context context)
{
    super(context, DB_NAME, null, DB_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) 
{   
    String sql = "create table " + TABLE + " (" + C_ID + " int primary key, " + C_CATEGORY + " varchar(32))";
    db.execSQL(sql);
    Log.d(TAG,sql);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
{
    db.execSQL("drop table if exists " + TABLE);
    Log.d(TAG, "in onUpdated()");
    onCreate(db);
}


public void insertCategory(String categoryName) 
{

    Log.d(TAG, "in insert DB method");


    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(C_CATEGORY, categoryName);
    database.insert(TABLE, null, values);
    database.close();
}

public List<String> getAllCategories()
{
    List<String> categories = new ArrayList<String>();


//        String[] projection = {
//              C_CATEGORY
//              };
//      
//        
//        SQLiteDatabase db = this.getReadableDatabase();
//        Cursor cursor = db.query(TABLE, projection, null, null, null, null, C_CATEGORY + " DESC");
//      
//        // looping through all rows and adding to list
//        if (cursor.moveToFirst()) 
//        {
//            do 
//            {
//              categories.add(cursor.getString(0));
//            } while (cursor.moveToNext());
//        }
//         
//        // closing connection
//        cursor.close();
//        db.close();
//         
//        // returning categories
//        return categories;

 // Select All Query
    String selectQuery = "SELECT * FROM " + TABLE;

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

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) 
    {
        do 
        {
            categories.add(cursor.getString(1));
        } while (cursor.moveToNext());
    }

    // closing connection
    cursor.close();
    db.close();

    // returning
    return categories;
}

}

非常感谢任何帮助!!

PS - 我在LogCat中的错误如下:

03-15 16:58:25.902: D/Week06Activity(8063): in onCreate()
03-15 16:58:34.631: D/PostReview(8063): New DB Handler
03-15 16:58:34.751: D/PostReview(8063): Got List of Categories
03-15 16:58:34.751: D/PostReview(8063): Created Adapter for spinner
03-15 16:58:34.751: D/PostReview(8063): list view with radio button
03-15 16:58:34.761: D/AndroidRuntime(8063): Shutting down VM
03-15 16:58:34.761: W/dalvikvm(8063): threadid=1: thread exiting with uncaught exception (group=0x40015560)
03-15 16:58:34.791: E/AndroidRuntime(8063): FATAL EXCEPTION: main
03-15 16:58:34.791: E/AndroidRuntime(8063): java.lang.RuntimeException: Unable to start activity ComponentInfo{ca.nait.kerickson16/ca.nait.kerickson16.PostReview}: java.lang.NullPointerException
03-15 16:58:34.791: E/AndroidRuntime(8063):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
03-15 16:58:34.791: E/AndroidRuntime(8063):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
03-15 16:58:34.791: E/AndroidRuntime(8063):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
03-15 16:58:34.791: E/AndroidRuntime(8063):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
03-15 16:58:34.791: E/AndroidRuntime(8063):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-15 16:58:34.791: E/AndroidRuntime(8063):     at android.os.Looper.loop(Looper.java:123)
03-15 16:58:34.791: E/AndroidRuntime(8063):     at android.app.ActivityThread.main(ActivityThread.java:3683)
03-15 16:58:34.791: E/AndroidRuntime(8063):     at java.lang.reflect.Method.invokeNative(Native Method)
03-15 16:58:34.791: E/AndroidRuntime(8063):     at java.lang.reflect.Method.invoke(Method.java:507)
03-15 16:58:34.791: E/AndroidRuntime(8063):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-15 16:58:34.791: E/AndroidRuntime(8063):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-15 16:58:34.791: E/AndroidRuntime(8063):     at dalvik.system.NativeStart.main(Native Method)
03-15 16:58:34.791: E/AndroidRuntime(8063): Caused by: java.lang.NullPointerException
03-15 16:58:34.791: E/AndroidRuntime(8063):     at ca.nait.kerickson16.PostReview.loadSpinnerCategories(PostReview.java:54)
03-15 16:58:34.791: E/AndroidRuntime(8063):     at ca.nait.kerickson16.PostReview.onCreate(PostReview.java:24)
03-15 16:58:34.791: E/AndroidRuntime(8063):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-15 16:58:34.791: E/AndroidRuntime(8063):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
03-15 16:58:34.791: E/AndroidRuntime(8063):     ... 11 more

3 个答案:

答案 0 :(得分:0)

您需要将此代码放在setContentView

之后
    categorySelect = (Spinner) findViewById(R.id.category_spinner);
 loadSpinnerCategories(); 

这里的问题是在布局绑定之前你试图初始化微调器

答案 1 :(得分:0)

您没有致电setContentView。因此,您的代码无法找到微调器,并且您获得了NPE。

稍微修改你的onCreate

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    //Add this line, your_layout is your layout where your spinner is defined.
    setContentView(R.layout.your_layout);


    categorySelect = (Spinner) findViewById(R.id.category_spinner);
    loadSpinnerCategories();

    super.onCreate(savedInstanceState);
    setContentView(R.layout.postreview);
}

答案 2 :(得分:0)

@Override
protected void onCreate(Bundle savedInstanceState) 
{
setContentView(R.layout.postreview); // content view should be placed first
categorySelect = (Spinner) findViewById(R.id.category_spinner);
loadSpinnerCategories();

super.onCreate(savedInstanceState);

}

试试这个。在设置内容视图之前,您无法填充微调器。感谢