Android开发在Service操作SQLite数据库出现NullPointerException空指针异常

时间:2022-01-11 08:19:30
新手小白最近入手安卓开发,想在Service中写一个数据库来不断保存从网口读到的数据,但是在获取数据库对象的时候就遇到了空指针异常,求各位大神解惑~
首先是异常的Logcat:
Android开发在Service操作SQLite数据库出现NullPointerException空指针异常

然后是我的DataBaseHelper类
public class DataBaseHelper extends SQLiteOpenHelper {
    private static final String DB_NAME = "send.db";
    private static final int DB_VERSION = 1;

    private static final String TABLE_SEND_CREATE = "create table sendtable(_id integer primary key autoincrement,msg varchar(100))";
    private static final String TABLE_RECEIVE_CREATE = "create table receivetable(_id integer primary key autoincrement,destId integer," +
                                                              "srcId integer,msg varchar(255),time integer,priority integer,location varchar(255))";

    private static SQLiteDatabase db;
    private static DataBaseHelper DBHelper;

    public DataBaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,
                          int version) {
        super(context, name, factory, version);
        // TODO Auto-generated constructor stub
    }

    public DataBaseHelper(Context context, String name) {
        this(context, DB_NAME, DB_VERSION);
        DBHelper = new DataBaseHelper(context, DB_NAME, null, DB_VERSION);
    }

    public DataBaseHelper(Context context, String name, int version) {
        this(context, DB_NAME, null, DB_VERSION);
        DBHelper = new DataBaseHelper(context, DB_NAME, null, DB_VERSION);
    }


    @Override
    public void onCreate(SQLiteDatabase db){
        db.execSQL(TABLE_SEND_CREATE);
        db.execSQL(TABLE_RECEIVE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){
        db.execSQL("drop table if exists sendtable");
        db.execSQL("drop table if exists receivetable");
        onCreate(db);
    }

    public static void DBwriter(Context context,String data){
        DataBaseHelper sendDBhelper = new DataBaseHelper(context,"send.db",null,1);
        SQLiteDatabase db =sendDBhelper.getReadableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("msg",data);
        db.insert("sendtable",null,cv);
        db.close();
    }

    public static List<String> DBreader(Context context){
        List<String> dataread = new ArrayList<String>();
        DataBaseHelper sendDBhelper = new DataBaseHelper(context,"send.db",null,1);
        SQLiteDatabase db =sendDBhelper.getReadableDatabase();
        Cursor cursor = null;
        cursor = db.query("sendtable",new String[]{"msg"},null,null,null,null,null);
        while (cursor.moveToNext()){
            dataread.add(cursor.getString(cursor.getColumnIndex("msg")));
        }
        if (cursor != null){
            cursor.close();
        }
        return dataread;
    }
}


接下来是我的Service类

public class UdpService extends Service {

    DataBaseHelper dataBaseHelper = new DataBaseHelper(this,"send.db");
    SQLiteDatabase db = dataBaseHelper.getReadableDatabase();

    int sendPort = 5005;
    int receivePort = 5005;

    UdpRelay.PacketReceivedListener listener = new UdpRelay.PacketReceivedListener() {


        @Override
        public void onReceive(MyPacket packet) {
            ContentValues cv = new ContentValues();
            cv.put("msg",packet.getMessage());
            cv.put("priority",packet.getPrioriry());
            cv.put("srcId",packet.getSrcId());
            cv.put("destId",packet.getDestId());
            cv.put("time",packet.getTime());
            cv.put("location",packet.getLocation());
            //db.insert("receivetable",null,cv);
        }
    };

    UdpRelay relay = new UdpRelay(sendPort, receivePort, listener);


    /**
     * 绑定服务时才会调用
     * 必须要实现的方法
     */
    @Nullable
    @Override
    public IBinder onBind(Intent intent){
        return null;
    }

    /**
     * 首次创建服务时,系统将调用此方法来执行一次性设置程序(在调用 onStartCommand() 或 onBind() 之前)。
     * 如果服务已在运行,则不会调用此方法。该方法只被调用一次
     */
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("myservicecreate","create");
    }

    /**
     * 每次通过startService()方法启动Service时都会被回调。
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("myservicestart","start");
        relay.start();
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 服务销毁时的回调
     */
    @Override
    public void onDestroy() {
       //db.close();
       super.onDestroy();
    }
}


MainActiviy中关于启动Service的代码:
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_main);

        //启动Service
        Intent myudpservice = new Intent(this,UdpService.class);
        startService(myudpservice);


希望各位大神指点迷津,感激不尽

3 个解决方案

#1


忘了说,报错的是Service类中一开始的两句
    DataBaseHelper dataBaseHelper = new DataBaseHelper(this,"send.db");
    SQLiteDatabase db = dataBaseHelper.getReadableDatabase();

#2


已经解决了,将数据库的初始化
DataBaseHelper dataBaseHelper = new DataBaseHelper(this,"send.db");
    SQLiteDatabase db = dataBaseHelper.getReadableDatabase();

放到Service的onCreate()里就行了

#3


你的问题和这个人一样 https://bbs.csdn.net/topics/392351527 Android开发在Service操作SQLite数据库出现NullPointerException空指针异常

#1


忘了说,报错的是Service类中一开始的两句
    DataBaseHelper dataBaseHelper = new DataBaseHelper(this,"send.db");
    SQLiteDatabase db = dataBaseHelper.getReadableDatabase();

#2


已经解决了,将数据库的初始化
DataBaseHelper dataBaseHelper = new DataBaseHelper(this,"send.db");
    SQLiteDatabase db = dataBaseHelper.getReadableDatabase();

放到Service的onCreate()里就行了

#3


你的问题和这个人一样 https://bbs.csdn.net/topics/392351527 Android开发在Service操作SQLite数据库出现NullPointerException空指针异常