0

在 Android 中,我使用 jexcel api 编写一个 excel 文档:

package com.xls;

import android.app.Activity;
import android.os.Bundle;
import java.io.*;
import jxl.*;
import jxl.write.*; 
import jxl.write.biff.RowsExceededException;

public class ExcelActivity extends Activity {
    WritableWorkbook workbook;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        try {
            workbook = Workbook.createWorkbook(new File("output.xls"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        WritableSheet sheet = workbook.createSheet("First Sheet", 0);  
       //nullPointerException here
    }
}

由于 NullPointerException 无法启动 Activity,为什么?

FATAL EXCEPTION: main
ERROR/AndroidRuntime(455): java.lang.RuntimeException: Unable to start activity 
ComponentInfo{com.xls/com.xls.ExcelActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1748)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1764)
at android.app.ActivityThread.access$1500(ActivityThread.java:122)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1002)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:132)
at android.app.ActivityThread.main(ActivityThread.java:4025)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:491)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
at dalvik.system.NativeStart.main(Native Method)

是什么导致了这个错误?

4

1 回答 1

0

根据堆栈跟踪,您的代码似乎试图取消引用空指针,因此出现 NullPointerException。按照堆栈跟踪中的建议查看第 26 行。我相信这是以下内容:

WritableSheet sheet = workbook.createSheet("First Sheet", 0); 

您是否检查Workbook.createWorkbook(new File("output.xls"))过在此之前返回一个非空对象?

于 2012-06-05T19:10:23.720 回答