使用Apache POI读取xlsx文件并向List添加内容时出现NullPointerException错误

时间:2015-10-23 09:39:58

标签: android apache-poi

我在我的资源文件夹中放置了一个xlsx文件,如下图所示: Image of where xlsx files are found within assets folder

但是我的活动遇到了问题,因为检索到的HashMap是Null。

活动:

    public class meal extends Activity {
HashMap<String, List<String>> Meal_category;
List<String> Meal_list;
ExpandableListView Exp_list;
MealAdapter adapter;
dataGenerator dg;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_meal);
    Exp_list = (ExpandableListView) findViewById(R.id.exp_list);
    String pth = "menuaa.xlsx";
    try {
        Meal_category = dg.getMenu(pth);
    } catch (Exception e) {
        e.printStackTrace();
    }
    Meal_list = new ArrayList<String>(Meal_category.keySet());
    adapter = new MealAdapter(this, Meal_category, Meal_list);
    Exp_list.setAdapter(adapter);
}

}

创建Meal_list时到达NullPointerException。这是我在dg.getMenu中的getMenu类的代码,它通常应包含其中的内容。我知道这是因为我在NetBeans上运行了一个测试,我以这种方式轻松地引用了“menuaa.xlsx”,它运行得很好:

    FileInputStream file = null;
    try {
        file = new FileInputStream(new File(mpath));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    //creating a workbook instance that can refer to .xls file
    XSSFWorkbook wb=null;
    try {
         wb = new XSSFWorkbook(file);
    } catch (IOException e) {
        e.printStackTrace();
    }

    //create a sheet object
    XSSFSheet sheet = wb.getSheetAt(0);

    //that is for evaluate the cell type
    FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();

我无法以与Android Studio中相同的方式引用它,因此将其添加到我的资源文件中,如上所示。我从dataGenerator类访问此文件,如下所示。

     public HashMap<String, List<String>> getMenu(String mpath) throws Exception
{

    HashMap<String, List<String>> MealDetails = new HashMap<String, List<String>>();
    List<String> Chinese_Food = new ArrayList<String>();
    List<String> Muslim_Food = new ArrayList<String>();
    List<String> WesternSet_Food = new ArrayList<String>();
    List<String> MuslimSpecial_Food = new ArrayList<String>();

    InputStream caInput = new BufferedInputStream(context.getAssets().open(
            mpath));

    XSSFWorkbook workbook = new XSSFWorkbook(caInput);

    //create a sheet object
    XSSFSheet sheet = workbook.getSheetAt(0);

    //that is for evaluate the cell type
    FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();

    for(Row row : sheet){
        for(Cell cell : row){

            switch(formulaEvaluator.evaluateInCell(cell).getCellType())
            {

                //if cell is a numeric format
                case Cell.CELL_TYPE_NUMERIC:
                    break;
                case Cell.CELL_TYPE_STRING:
                    Log.d("MyMessage", "entered cell string type");
                    if(cell.getStringCellValue().contains("Chinese Meal")){
                        //store name of meal in list
                        int columnNumber = cell.getColumnIndex();
                        int rowNumber = cell.getRow().getRowNum();


                        int foodNumber = rowNumber+1;
                        CellReference mealCell = new CellReference(foodNumber,columnNumber);
                        Row r = sheet.getRow(mealCell.getRow());
                        Cell c = r.getCell(mealCell.getCol());
                        String mealName = c.getStringCellValue();
                        Log.w("MyClassName", mealName);
                        //add name of meal to Chinese Food list
                        Chinese_Food.add(mealName);
                    }

                    //search document for all cells that contain "Muslim Meal"
                    if(cell.getStringCellValue().contains("Muslim Meal")){
                        //store name of meal in list
                        int columnNumber = cell.getColumnIndex();
                        int rowNumber = cell.getRow().getRowNum();


                        int foodNumber = rowNumber+1;
                        CellReference mealCell = new CellReference(foodNumber,columnNumber);
                        Row r = sheet.getRow(mealCell.getRow());
                        Cell c = r.getCell(mealCell.getCol());
                        String mealName = c.getStringCellValue();
                        System.out.println(mealName);
                        Muslim_Food.add(mealName);
                    }

                    //search document for all cells that contain "Western Set Meal"
                    if(cell.getStringCellValue().contains("Western Set Meal")){
                        //store name of meal in list
                        int columnNumber = cell.getColumnIndex();
                        int rowNumber = cell.getRow().getRowNum();


                        int foodNumber = rowNumber+1;
                        CellReference mealCell = new CellReference(foodNumber,columnNumber);
                        Row r = sheet.getRow(mealCell.getRow());
                        Cell c = r.getCell(mealCell.getCol());
                        String mealName = c.getStringCellValue();
                        System.out.println(mealName);
                        WesternSet_Food.add(mealName);
                    }

                    //search document for all cells that contain "Muslim Special"
                    if(cell.getStringCellValue().contains("Muslim Special")){
                        //store name of meal in list
                        int columnNumber = cell.getColumnIndex();
                        int rowNumber = cell.getRow().getRowNum();
                        int foodNumber = rowNumber+1;
                        CellReference mealCell = new CellReference(foodNumber,columnNumber);
                        Row r = sheet.getRow(mealCell.getRow());
                        Cell c = r.getCell(mealCell.getCol());
                        String mealName = c.getStringCellValue();
                        MuslimSpecial_Food.add(mealName);
                    }
                    break;
            }
        }
    }

    MealDetails.put("Chinese Meal", Chinese_Food);
    MealDetails.put("Muslim Meal", Muslim_Food);
    MealDetails.put("Western Special Set", WesternSet_Food);
    MealDetails.put("Muslim Special", MuslimSpecial_Food);

    return MealDetails;
}

最后,这是我的jar文件,如果你想要更多内容:P Used dependencies

我已经遵循了很多线索,但无济于事,每一个让我回到原点。我知道,很多.jar。我为我的程序设置了一个multiDex。

我的Stacktrace:

10-23 16:58:19.594  28881-28881/com.raphaelharel.thoughtforfood W/System.err﹕ java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.HashMap com.raphaelharel.thoughtforfood.dataGenerator.getMenu(java.lang.String)' on a null object reference
10-23 16:58:19.604  28881-28881/com.raphaelharel.thoughtforfood W/System.err﹕ at com.raphaelharel.thoughtforfood.meal.onCreate(meal.java:33)
10-23 16:58:19.604  28881-28881/com.raphaelharel.thoughtforfood W/System.err﹕ at android.app.Activity.performCreate(Activity.java:5977)
10-23 16:58:19.604  28881-28881/com.raphaelharel.thoughtforfood W/System.err﹕ at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
10-23 16:58:19.604  28881-28881/com.raphaelharel.thoughtforfood W/System.err﹕ at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2258)
10-23 16:58:19.604  28881-28881/com.raphaelharel.thoughtforfood W/System.err﹕ at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2367)
10-23 16:58:19.604  28881-28881/com.raphaelharel.thoughtforfood W/System.err﹕ at android.app.ActivityThread.access$800(ActivityThread.java:148)
10-23 16:58:19.604  28881-28881/com.raphaelharel.thoughtforfood W/System.err﹕ at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
10-23 16:58:19.604  28881-28881/com.raphaelharel.thoughtforfood W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:102)
10-23 16:58:19.604  28881-28881/com.raphaelharel.thoughtforfood W/System.err﹕ at android.os.Looper.loop(Looper.java:135)
10-23 16:58:19.605  28881-28881/com.raphaelharel.thoughtforfood W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5274)
10-23 16:58:19.605  28881-28881/com.raphaelharel.thoughtforfood W/System.err﹕ at java.lang.reflect.Method.invoke(Native Method)
10-23 16:58:19.605  28881-28881/com.raphaelharel.thoughtforfood W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:372)
10-23 16:58:19.605  28881-28881/com.raphaelharel.thoughtforfood W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
10-23 16:58:19.605  28881-28881/com.raphaelharel.thoughtforfood W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
10-23 16:58:19.609  28881-28881/com.raphaelharel.thoughtforfood D/AndroidRuntime﹕ Shutting down VM
10-23 16:58:19.613  28881-28881/com.raphaelharel.thoughtforfood E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.raphaelharel.thoughtforfood, PID: 28881
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.raphaelharel.thoughtforfood/com.raphaelharel.thoughtforfood.meal}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Set java.util.HashMap.keySet()' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2367)
            at android.app.ActivityThread.access$800(ActivityThread.java:148)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5274)
            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:909)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Set java.util.HashMap.keySet()' on a null object reference
            at com.raphaelharel.thoughtforfood.meal.onCreate(meal.java:37)
            at android.app.Activity.performCreate(Activity.java:5977)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2258)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2367)
            at android.app.ActivityThread.access$800(ActivityThread.java:148)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5274)
            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:909)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)

我绝对认为这是我从Android Studio访问xlsx文件的问题。非常感谢任何帮助!

编辑:我在没有Excel读取的情况下运行该类(手动输入值到List),并且可以确认问题在于我无法正确读取文件。

1 个答案:

答案 0 :(得分:1)

您的dataGenerator为空。

NullpointerException在这里:

Meal_category = dg.getMenu(pth);

首先创建一个dataGenerator的新对象:

dataGenerator = new dataGenerator();
Meal_category = dg.getMenu(pth);

然后它应该工作。