在尝试从SQL数据库检索数据到listview android时,接收Null Pointer Exception

时间:2015-06-10 02:29:31

标签: java android database sqlite listview

当我试图从我的SQLite数据库中获取数据并且我不确定如何解决这个问题时,我一直收到Null Pointer Exception。代码:

活动:

public class Draft_Budget extends Activity {
String[] budget;
DBHelper budDb;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.draft_budget);
    ActionBar actionBar = getActionBar();
    actionBar.show();

    populateListViewFromDB();
    registerListClickCallback();

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    budget =
            getResources().getStringArray(R.array.Budget_freq);
    Spinner s1 = (Spinner) findViewById(R.id.spinner2);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, budget);

    s1.setAdapter(adapter);
    s1.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            int index = arg0.getSelectedItemPosition();
            Toast.makeText(getBaseContext(), "you have selected item: " + budget[index], Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });
}
@Override
protected void onDestroy(){
    super.onDestroy();
    closeDB();
}

private void openDB(){
    budDb = new DBHelper(this);
    budDb.open();
}

private void closeDB() {
    budDb.close();
}

public void add_expense(View view){
    Intent intent = new Intent(this, Setup_expenses.class);
    intent.putExtra("expense_Id",0);
    startActivity(intent);
    populateListViewFromDB();
}

public void clearexp(View v){
    budDb.deleteAll();
    populateListViewFromDB();
}

private void populateListViewFromDB(){
    Cursor cursor = budDb.getAllRows();
    startManagingCursor(cursor);

    String[] fromFeildNames = new String[]
            {DBHelper.KEY_label, DBHelper.KEY_cost, DBHelper.KEY_cost};
    int[] toViewIDs = new int[]
            {R.id.expense_name, R.id.expense_Id, R.id.expense_cost};
    SimpleCursorAdapter exCursorAdapter = new SimpleCursorAdapter(
            this,
            R.layout.view_expense_entry,
            cursor,
            fromFeildNames,
            toViewIDs);
    ListView expenselist = (ListView) findViewById(R.id.list_expense);
    expenselist.setAdapter(exCursorAdapter);
}

private void registerListClickCallback(){
    ListView budlist = (ListView) findViewById(R.id.list_expense);
    budlist.setOnItemClickListener(new AdapterView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long idInDB){
            updateItemForId(idInDB);
            displayToastForId(idInDB);
        }
    });
}

private void updateItemForId(long idInDB){
    Cursor cursor = budDb.getRow(idInDB);
    if (cursor.moveToFirst()){
        long idDB = cursor.getLong(DBHelper.COL_ROWID);
        String name = cursor.getString(DBHelper.COL_label);
        int cost = cursor.getInt(DBHelper.COL_cost);
        budDb.updateRow(idDB, name, cost);
    }
    cursor.close();
    populateListViewFromDB();
}

private void displayToastForId(long idInDB){
    Cursor cursor = budDb.getRow(idInDB);
    if (cursor.moveToFirst()){
        long idDB = cursor.getLong(DBHelper.COL_ROWID);
        String label = cursor.getString(DBHelper.COL_label);
        int cost = cursor.getInt(DBHelper.COL_cost);

        String message = "ID: " + idDB + "\n" + "Category: " + label + "\n" + "Cost: " + cost;
        Toast.makeText(Draft_Budget.this, message, Toast.LENGTH_LONG).show();
    }
    cursor.close();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    super.onCreateOptionsMenu(menu);
    CreateMenu(menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item){
    return MenuChoice(item);
}

private void CreateMenu(Menu menu)
{
    MenuItem mnu1 = menu.add(0, 0, 0, "Item 1");
    {
        mnu1.setIcon(R.drawable.ic_action_overflow);
        mnu1.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
    }
}

private boolean MenuChoice(MenuItem item)
{
    switch (item.getItemId()) {
        case 0:
            Toast.makeText(this, "You clicked on Item 1", Toast.LENGTH_LONG).show();
            return true;
    }
    return false;
}

public void done(View view) {
    Intent done = new Intent(this, Home_page.class);
    done.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(done);
}

数据库提供者:

public class DBHelper  {
private static final String TAG = "DBHelper";

public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
public static final String KEY_label = "Label";
public static final String KEY_cost = "Cost";

public static final int COL_label = 1;
public static final int COL_cost = 2;

public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_label, KEY_cost};

public static final int DATABASE_VERSION = 5;
public static final String DATABASE_NAME = "Expense.db";
public static final String DATABASE_TABLE = "expenseTable";
public static final String DATABASE_CREATE_SQL = "create table " + DATABASE_TABLE + " (" + KEY_ROWID + " integer primary key autoincrement, "
        + KEY_label + " text not null, " + KEY_cost + " integer not null" + ");";

final Context context;
DatabaseHelper myDBHelper;
SQLiteDatabase db;

public DBHelper(Context ctx){
    this.context = ctx;
    myDBHelper = new DatabaseHelper(context);
}



private static class DatabaseHelper extends SQLiteOpenHelper
{
    DatabaseHelper(Context context){
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase _db){
        try {
            _db.execSQL(DATABASE_CREATE_SQL);
        } catch (SQLException e){
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase _db, int oldversion, int newversion) {
        Log.w(TAG, "Upgarding application's database from version " + oldversion + " to " + newversion + " , which will destroy all old data!");

        //Destroy
        _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

        //Recreate database
        onCreate(_db);
    }

}
public DBHelper open(){
    db = myDBHelper.getWritableDatabase();
    return this;
}

public void close(){
    myDBHelper.close();
}

//Add set of values to database
public long insertRow(int Cost, String Label) {
    db = myDBHelper.getWritableDatabase();
    ContentValues intialvalues = new ContentValues();
    intialvalues.put(KEY_label, Label);
    intialvalues.put(KEY_cost, Cost);
    return db.insert(DATABASE_TABLE, null, intialvalues);
}

//Delete
public boolean deleteRow(long rowId){
    return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}

public void deleteAll(){
    Cursor c = getAllRows();
    long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
    if (c.moveToFirst()) {
        do {
            deleteRow(c.getLong((int) rowId));
        } while (c.moveToNext());
    }
    c.close();
}

//Return data
public Cursor getAllRows() throws SQLException{
    db = myDBHelper.getReadableDatabase();
    return db.query(DATABASE_TABLE, ALL_KEYS , null, null, null, null, null);
}

//Get specific row
public Cursor getRow(long rowId) throws SQLException{
    Cursor c = db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID, KEY_label, KEY_cost}, KEY_ROWID + "=" + rowId, null, null, null, null, null);
    if (c != null){
        c.moveToFirst();
    }
    return c;
}

//Change row to equal new data
public boolean updateRow(long rowId, String Label, int Cost){
    db = myDBHelper.getWritableDatabase();
    ContentValues newvalues = new ContentValues();
    newvalues.put(KEY_label, Label);
    newvalues.put(KEY_cost, Cost);
    return db.update(DATABASE_TABLE, newvalues, KEY_ROWID + "=" + rowId, null) > 0;
}

活动的布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">


    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/Expense"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:background="#939393"
        android:textColor="#ffffff" />

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="+Add Expense"
        android:id="@+id/button2"
        android:onClick="add_expense"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:nestedScrollingEnabled="false" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/Income"
        android:id="@+id/textView2"
        android:textColor="#ffffff"
        android:background="#939393"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="+Add Income"
        android:textSize="6pt"
        android:id="@+id/button3"
        android:onClick="Set_income"
        android:layout_below="@+id/textView2"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />


<Spinner
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/spinner2"
    android:drawSelectorOnTop="true"
    android:layout_above="@+id/button"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Done"
    android:id="@+id/button"
    android:onClick="done"
    android:layout_alignParentBottom="true" />

<ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/list_expense"
    android:layout_below="@+id/button2"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_above="@+id/textView2" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Clear expenses:"
    android:id="@+id/clearexp"
    android:onClick="clearexp"
    android:layout_below="@+id/textView"
    android:layout_toRightOf="@+id/button2"
    android:layout_toEndOf="@+id/button2"
    android:layout_marginLeft="92dp"
    android:layout_marginStart="92dp" />


</RelativeLayout>

和listview:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:id="@+id/expense_Id"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:visibility="gone"/>

<TextView
    android:id="@+id/expense_name"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="6dip"
    android:paddingTop="6dip"
    android:textSize="14pt"/>
<TextView
    android:id="@+id/expense_cost"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingRight="6dip"
    android:paddingBottom="6dip"
    android:textSize="14pt"/>

</LinearLayout>

任何想法如何解决这个问题?

*编辑,日志:

06-10 14:56:51.098    2110-2110/com.example.thomaseleutheriades.personalwallet E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.thomaseleutheriades.personalwallet, PID: 2110
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.thomaseleutheriades.personalwallet/com.example.thomaseleutheriades.personalwallet.Draft_Budget}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2429)
        at android.app.ActivityThread.access$800(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1342)
        at android.os.Handler.dispatchMessage(Handler.java:110)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:5341)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at com.example.thomaseleutheriades.personalwallet.Draft_Budget.populateListViewFromDB(Draft_Budget.java:89)
        at com.example.thomaseleutheriades.personalwallet.Draft_Budget.onCreate(Draft_Budget.java:37)
        at android.app.Activity.performCreate(Activity.java:5343)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
        at 

1 个答案:

答案 0 :(得分:1)

在此budDb致电populateListViewFromDB();之前,您似乎没有初始化budDb is null