Android:NullPointerException 无法将数据库加载到片段内的列表视图中

Posted

技术标签:

【中文标题】Android:NullPointerException 无法将数据库加载到片段内的列表视图中【英文标题】:Android: NullPointerException Unable to load database into listview within a fragment 【发布时间】:2015-06-15 05:36:20 【问题描述】:

我一直在寻找一段时间,试图找到如何使用 mysqlite 数据库中的信息填充列表视图。现在,当我想我终于找到了一些信息时,我想出了 NullPointers。

这是我的代码(HomeFragment.java):

package zygs.com.seniorproject.fragments;

import android.app.Fragment;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

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

import zygs.com.seniorproject.R;
import zygs.com.seniorproject.database.DatabaseHandler;
import zygs.com.seniorproject.database.Inventory;

public class HomeFragment extends Fragment 

// Initializing Variables
Button Item_Button;
Button Display_Button;
EditText Box_Item_Des;
EditText Box_Item_Quant;
EditText Box_Item_ID;
final DatabaseHandler db = new DatabaseHandler(getActivity());


public HomeFragment()

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 

    setHasOptionsMenu(true);

    final View rootView = inflater.inflate(R.layout.fragment_home, container, false);
    ListView listContent = (ListView)rootView.findViewById(R.id.inventory_list);

    Item_Button = (Button)rootView.findViewById(R.id.add_item);
    Display_Button = (Button)rootView.findViewById(R.id.display_button);
    Box_Item_Des = (EditText)rootView.findViewById(R.id.Item_Des);
    Box_Item_ID = (EditText)rootView.findViewById(R.id.Item_ID);
    Box_Item_Quant = (EditText)rootView.findViewById(R.id.Item_Quant);

    Item_Button.setOnClickListener(
            new View.OnClickListener() 
                public void onClick(View view) 

                    // Grab Information from Text Boxes
                    String Item_Des = Box_Item_Des.getText().toString();
                    int Item_Quantity = Integer.parseInt(Box_Item_Quant.getText().toString());
                    int Item_ID = Integer.parseInt(Box_Item_ID.getText().toString());

                    db.addItem(new Inventory(Item_ID, Item_Des, Item_Quantity));
                
            
    );

    Display_Button.setOnClickListener(
            new OnClickListener() 
                public void onClick(View view)

                    Log.d("Reading: ", "Reading all Inventory");
                    List<Inventory> inventoryList = db.getAllItems();

                    for (Inventory in : inventoryList) 
                        String log = "Id: " + in.getItemID() + ", Name: " + in.getItemName() + " , Quantity: " + in.getItemQuant();

                        //Write List to Log
                        Log.d("Name:", log);
                    

                
            
    );

    List<Inventory> inv_list = getAllInventory();
    ArrayAdapter adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, inv_list);
    listContent.setAdapter(adapter);



    return rootView;


public List<Inventory> getAllInventory() 

    List<Inventory> contactList = new ArrayList<Inventory>();

    String selectQuery = "SELECT * FROM Inventory";
    SQLiteDatabase data = db.getWritableDatabase();

    Cursor cursor = data.rawQuery(selectQuery, null);

    if (cursor.moveToFirst()) 
        do 
            Inventory inventory = new Inventory();
            inventory.setItemID(Integer.parseInt(cursor.getString(0)));
            inventory.setItemName(cursor.getString(1));
            inventory.setItemQuant(Integer.parseInt(cursor.getString(2)));
         while (cursor.moveToNext());
    
    return contactList;



我正在使用来自 AndroidHive 的数据库处理程序

代码如下:

package zygs.com.seniorproject.database;

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

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

public class DatabaseHandler extends SQLiteOpenHelper 

//Logcat Tag
private static final String LOG = "DatabaseHelper";

//Database Version
private static final int DATABASE_VERSION = 2;

//Database Name
private static final String DATABASE_NAME = "InventoryManager";

//Tables
private static final String TABLE_INVENTORY = "Inventory";
private static final String TABLE_KITS = "Kits";

// Common Keys
private static final String KEY_ITEM_ID = "item_id";

//Kits Table Columns Name
private static final String KEY_ID = "_id";
private static final String KEY_KIT_ID = "kit_id";
private static final String KEY_KIT_NAME = "kit_name";

//Inventory Tables Columns Names
private static final String KEY_ITEM_NAME = "item_name";
private static final String KEY_ITEM_QUANT = "item_quant";

public DatabaseHandler(Context context) 
    super(context, DATABASE_NAME, null, DATABASE_VERSION);


//Creating Tables Strings
private static final String CREATE_INVENTORY_TABLE = "CREATE TABLE " + TABLE_INVENTORY + "(" + KEY_ITEM_ID + " INTEGER PRIMARY KEY," + KEY_ITEM_NAME + " TEXT," + KEY_ITEM_QUANT + " INTEGER" + ");";
private static final String CREATE_KIT_TABLE = "CREATE TABLE " + TABLE_KITS + "(" + KEY_ID + " AUTOINCREMENT INTEGER PRIMARY KEY," + KEY_KIT_ID + " INTEGER," + KEY_KIT_NAME + " TEXT," + KEY_ITEM_ID + " INTEGER" + ");";


//Create Tables
@Override
public void onCreate(SQLiteDatabase db) 

    db.execSQL(CREATE_INVENTORY_TABLE);
    db.execSQL(CREATE_KIT_TABLE);


//Upgrading Database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
    //Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_INVENTORY);

    // Create Tables again;
    onCreate(db);



/////////////////////////////////////////
/////// CREATE READ UPDATE DELETE //////
///////////////////////////////////////

//Add a new record
public void addItem(Inventory inventory) 
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_ITEM_NAME, inventory.getItemName());     // Item Name
    values.put(KEY_ITEM_ID, inventory.getItemID());         // Item ID
    values.put(KEY_ITEM_QUANT, inventory.getItemQuant());   //Item Quantity

    //Insert Row
    db.insert(TABLE_INVENTORY, null, values);
    db.close();



// Query a single Item
//public Inventory getItemID(int id) 

//Query All Items
public List<Inventory> getAllItems() 
    List<Inventory> inventoryList = new ArrayList<Inventory>();

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

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

    //Looping through all rows and adding to list
    if (cursor.moveToFirst()) 
        do 
            Inventory inventory = new Inventory();
            inventory.setItemID(Integer.parseInt(cursor.getString(0)));
            inventory.setItemName(cursor.getString(1));
            inventory.setItemQuant(Integer.parseInt(cursor.getString(2)));

            //Adding Inventory to List
            inventoryList.add(inventory);
         while (cursor.moveToNext());
    

    //Return Inventory List
    return inventoryList;





// Query Item Count
//public int getItemCount() 

//Update Single Item
//public int updateItem(Inventory inventory) 

//Delete Single Item
//public void deleteItem(Inventory inventory)



我得到的错误日志如下:

04-09 13:34:54.187    6393-6393/zygs.com.seniorproject E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: zygs.com.seniorproject, PID: 6393
    java.lang.RuntimeException: Unable to start activity ComponentInfozygs.com.seniorproject/zygs.com.seniorproject.MainActivity: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2693)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
            at android.app.ActivityThread.access$900(ActivityThread.java:177)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:5942)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference
            at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
            at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
            at zygs.com.seniorproject.fragments.HomeFragment.getAllInventory(HomeFragment.java:97)
            at zygs.com.seniorproject.fragments.HomeFragment.onCreateView(HomeFragment.java:83)
            at android.app.Fragment.performCreateView(Fragment.java:2114)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:904)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1082)
            at android.app.BackStackRecord.run(BackStackRecord.java:833)
            at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
            at android.app.Activity.performStart(Activity.java:6328)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2656)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
            at android.app.ActivityThread.access$900(ActivityThread.java:177)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:5942)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)

感谢您为我提供的任何帮助。

【问题讨论】:

What is a Null Pointer Exception, and how do I fix it?的可能重复 【参考方案1】:

final DatabaseHandler db = new DatabaseHandler(getActivity()); 行在您的类的顶部声明,因此您的 Fragment getActivity() 的创建将返回一个空引用。

如果你在 onCreate() 方法中移动它,你将拥有一个 Activity 引用,你的 db 处理程序可以使用。

【讨论】:

以上是关于Android:NullPointerException 无法将数据库加载到片段内的列表视图中的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Android 中处理 NullPointerException?

<WebLogicServer; <BEA-000386; <Server subsystem failed. Reason: java.lang.NullPointerExcept

Maven打包时出现“Show Console View”错误弹出框,错误详情为“An internal error has occurred. java.lang.NullPointerExcept

Maven打包时出现“Show Console View”错误弹出框,错误详情为“An internal error has occurred. java.lang.NullPointerExcept

Android proguard 混淆代码实际上不应该导致 NullPointerException

RecyclerView的坑