Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何在服务中使用SQLiteOpenHelper_Android_Sqlite_Service - Fatal编程技术网

Android 如何在服务中使用SQLiteOpenHelper

Android 如何在服务中使用SQLiteOpenHelper,android,sqlite,service,Android,Sqlite,Service,通常,在活动中,我像这样使用SQLiteOpenHelper DatabaseHandler mDbHelper = new DatabaseHandler(getBaseContext()); 现在,我想在服务中使用SQLite。但是,当我在服务类的方法中使用上述代码时,它会导致NullPointerException错误 这是我的服务课 public class MyService extends Service{ public void LoadDB()

通常,在活动中,我像这样使用SQLiteOpenHelper

DatabaseHandler mDbHelper = new DatabaseHandler(getBaseContext());
现在,我想在服务中使用SQLite。但是,当我在服务类的方法中使用上述代码时,它会导致NullPointerException错误

这是我的服务课

    public class MyService extends Service{     
        public void LoadDB(){
            DatabaseHandler mDbHelper = new DatabaseHandler(getBaseContext());
            ArrayList <MyPosition> positionlist = mDbHelper.getAllPositions();   **//error here**   
        }
        private final IBinder mBinder = new LocalBinder();
        public class LocalBinder extends Binder {
            MyService getService() {
                // Return this instance of LocalService so clients can call public methods
                return MyService.this;
            }
        }

        @Override
        public IBinder onBind(Intent intent) {
            return mBinder;
        }
    }

This is the code that I call Service in MainActivity class

        public class MainActivity extends Activity {
            MyService mService;
            boolean mBound = false;
            @Override
            protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            activity  = this;       

            mService = new MyService();
            doBindService();
            if (mBound){
                mService.LoadDB();
            }
         }

      private ServiceConnection mConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName className, IBinder service) {
                  LocalBinder binder = (LocalBinder) service;
                  mService = binder.getService();
                  mBound = true;
            }

            @Override
            public void onServiceDisconnected(ComponentName arg0) {
                 mBound = false;
            }
      };

            void doBindService() {
                bindService(new Intent(MainActivity.this, MyService.class), mConnection, Context.BIND_AUTO_CREATE);
                mBound = true;
            }

            void doUnbindService() {
                if (mBound) {
                    // Detach our existing connection.
                    unbindService(mConnection);
                    mBound = false;
                }
            }
        }
}
公共类MyService扩展服务{
公共void LoadDB(){
DatabaseHandler mDbHelper=新的DatabaseHandler(getBaseContext());
ArrayList positionlist=mDbHelper.getAllPositions();***//此处出错**
}
private final IBinder mBinder=new LocalBinder();
公共类LocalBinder扩展了Binder{
MyService getService(){
//返回此LocalService实例,以便客户端可以调用公共方法
返回MyService.this;
}
}
@凌驾
公共IBinder onBind(意向){
返回mBinder;
}
}
这是我在MainActivity类中调用服务的代码
公共类MainActivity扩展了活动{
MyService-mService;
布尔mBound=false;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
活动=此;
mService=newmyservice();
doBindService();
如果(mBound){
mService.LoadDB();
}
}
专用ServiceConnection mConnection=新ServiceConnection(){
@凌驾
服务连接上的公共无效(组件名称类名称,IBinder服务){
LocalBinder=(LocalBinder)服务;
mService=binder.getService();
mBound=true;
}
@凌驾
ServiceDisconnected上的公共无效(组件名称arg0){
mBound=假;
}
};
void doBindService(){
bindService(新意图(MainActivity.this、MyService.class)、mConnection、Context.BIND\u AUTO\u CREATE);
mBound=true;
}
void doUnbindService(){
如果(mBound){
//断开现有连接。
解除绑定服务(mConnection);
mBound=假;
}
}
}
}
我的DatabaseHandler类

package com.example.example10;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;

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

public class DatabaseHandler extends SQLiteOpenHelper{
    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

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

    // Position table name
    private static final String TABLE_POSITIONS = "positions";

    // Position Table Columns names
    public static final String KEY_ROWID = "_id";
    private static final String KEY_ADDRESS = "address";
    private static final String KEY_LONG = "longPos";
    private static final String KEY_LAT = "latPos";
    private static final String KEY_LASTVISITED = "lastVisited";
    private static final String KEY_IMAGE = "image";

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

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_POSITIONS_TABLE = "CREATE TABLE " + TABLE_POSITIONS + "(" + KEY_ROWID 
                + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_ADDRESS + " TEXT," 
                + KEY_LONG + " REAL, " + KEY_LAT + " REAL, " + KEY_LASTVISITED + " TEXT, " 
                + KEY_IMAGE + " BLOB" +")";
        db.execSQL(CREATE_POSITIONS_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_POSITIONS);

        // Create tables again
        onCreate(db);
    }

    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    // Adding new position
    void addPosition(MyPosition position) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_ADDRESS, position.GetAddress()); 
        values.put(KEY_LONG, position.GetLongPos()); 
        values.put(KEY_LAT, position.GetLatPos());
        values.put(KEY_LASTVISITED, position.GetLastVisited()); 
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        position.GetImage().compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] imageInByte = stream.toByteArray();
        values.put(KEY_IMAGE, imageInByte); 

        // Inserting Row
        db.insert(TABLE_POSITIONS, null, values);
        db.close(); // Closing database connection
    }

    // Getting All Positions
    public ArrayList <MyPosition> getAllPositions() {
        ArrayList <MyPosition> position_list = new ArrayList <MyPosition>();
        // Select All Query
        String selectQuery = "SELECT * FROM " + TABLE_POSITIONS;

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

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                MyPosition position = new MyPosition();
                position.SetAddress(cursor.getString(1));
                position.SetLongPos(cursor.getFloat(2));
                position.SetLatPos(cursor.getFloat(3));
                position.SetLastVisited(cursor.getString(4));
                byte[] imagebyte = cursor.getBlob(5);
                Bitmap image = BitmapFactory.decodeByteArray(imagebyte, 0, imagebyte.length);
                position.SetImage(image);

                // Adding position to list
                position_list.add(position);
            } while (cursor.moveToNext());
        }

        // return position list
        return position_list;
    }

    // Updating single position
    public int updatePosition(MyPosition position, int index) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_ADDRESS, position.GetAddress()); 
        values.put(KEY_LONG, position.GetLongPos()); 
        values.put(KEY_LAT, position.GetLatPos());
        values.put(KEY_LASTVISITED, position.GetLastVisited()); 
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        position.GetImage().compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] imageInByte = stream.toByteArray();
        values.put(KEY_IMAGE, imageInByte); 

        // updating row
        return db.update(TABLE_POSITIONS, values, KEY_ROWID + "=" + (index + 1), null);
    }

    // Deleting single position
    public void deletePosition(MyPosition position, int index) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_POSITIONS, KEY_ROWID + "=" + (index + 1), null);
        db.close();
    }


    // Getting position Count
    public int getPositionCount() {
        String countQuery = "SELECT * FROM " + TABLE_POSITIONS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        int count = cursor.getCount();
        cursor.close();

        // return count
        return count;
    }

    // Getting single position
    MyPosition getPosition(int index) {
        SQLiteDatabase db = this.getReadableDatabase(); 
        Cursor cursor = db.query(TABLE_POSITIONS, new String[] { KEY_ADDRESS, KEY_LONG, KEY_LAT,  KEY_LASTVISITED, KEY_IMAGE}, 
                KEY_ROWID + "=?", new String[] { String.valueOf(index) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Bitmap image = BitmapFactory.decodeByteArray(cursor.getBlob(5), 0, cursor.getBlob(5).length);
        MyPosition position = new MyPosition(cursor.getString(1), cursor.getDouble(2), cursor.getDouble(3), 
                                cursor.getString(4), image);
        // return contact
        return position;
    }

}
package com.example.example10;
导入java.io.ByteArrayOutputStream;
导入java.util.ArrayList;
导入android.content.ContentValues;
导入android.content.Context;
导入android.database.Cursor;
导入android.database.sqlite.SQLiteDatabase;
导入android.database.sqlite.SQLiteOpenHelper;
导入android.graphics.Bitmap;
导入android.graphics.BitmapFactory;
公共类DatabaseHandler扩展了SQLiteOpenHelper{
//所有静态变量
//数据库版本
私有静态最终int数据库_VERSION=1;
//数据库名称
私有静态最终字符串数据库\u NAME=“ListPosition”;
//位置表名称
私有静态最终字符串表_POSITIONS=“POSITIONS”;
//定位表列名称
公共静态最终字符串键_ROWID=“_id”;
私有静态最终字符串密钥\u ADDRESS=“ADDRESS”;
私有静态最终字符串键\u LONG=“longPos”;
私有静态最终字符串密钥\u LAT=“latPos”;
私有静态最终字符串密钥\u LASTVISITED=“LASTVISITED”;
私有静态最终字符串键\u IMAGE=“IMAGE”;
公共数据库处理程序(上下文){
super(上下文、数据库名称、null、数据库版本);
}
//创建表
@凌驾
public void onCreate(SQLiteDatabase db){
字符串CREATE_POSITIONS_TABLE=“CREATE TABLE”+TABLE_POSITIONS+”(“+KEY_ROWID
+整数主键自动递增,“+键地址+”文本
+键长+“实”,“键宽+“实”,“键上次访问+”文本,“
+键_IMAGE+“BLOB”+”;
db.execSQL(创建位置表);
}
//升级数据库
@凌驾
public void onUpgrade(SQLiteDatabase db,int-oldVersion,int-newVersion){
//删除旧表(如果存在)
db.execSQL(“如果存在删除表”+表位置);
//再次创建表
onCreate(db);
}
/**
*所有CRUD(创建、读取、更新、删除)操作
*/
//增加新职位
无效添加位置(我的位置){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues=新的ContentValues();
value.put(KEY_ADDRESS,position.GetAddress());
value.put(KEY_LONG,position.GetLongPos());
value.put(KEY_LAT,position.GetLatPos());
value.put(KEY_LASTVISITED,position.GetLastVisited());
ByteArrayOutputStream=新建ByteArrayOutputStream();
position.GetImage().compress(Bitmap.CompressFormat.PNG,100,stream);
字节[]imageInByte=stream.toByteArray();
值.put(键图像,imageInByte);
//插入行
db.insert(表位置、空值、值);
db.close();//关闭数据库连接
}
//获取所有位置
公共阵列列表getAllPositions(){
ArrayList position_list=新的ArrayList();
//选择所有查询
String selectQuery=“SELECT*FROM”+表格位置;
SQLiteDatabase db=this.getWritableDatabase();
Cursor Cursor=db.rawQuery(selectQuery,null);
//循环遍历所有行并添加到列表
if(cursor.moveToFirst()){
做{
MyPosition位置=新的MyPosition();
position.SetAddress(cursor.getString(1));
position.SetLongPos(cursor.getFloat(2));
position.SetLatPos(cursor.getFloat(3));
position.SetLastVisited(cursor.getString(4))
public class MyService extends Service{     
  public void LoadDB(){
    DatabaseHandler mDbHelper = new DatabaseHandler(this);  
  }...
Intent i = new Intent(this, YourService.class);
startService(i);
public class YourService  extends Service {

    private DatabaseHelper dbHeper;
    private User user;
    private String userName;

    @Override
    public void onCreate() {
        dbHeper = new DatabaseHelper(getApplicationContext());
        user = dbHeper.getUser(1);
        userName = user.getUserName();
        System.out.println("User Name: " + userToken);
    }

}