我在使用IntentService时如何操作SQLite?

时间:2013-11-08 01:23:16

标签: android android-sqlite

在创建对象时似乎SQLiteOpenHelper需要传递Context参数,因此我在Main中传递PublicPar.myContext=getApplicationContext()(扩展了Activity)。

但在IntentService中,没有用户界面,也没有活动,也许我无法使用getApplicationContext()。当我使用IntentService时,我该如何操作SQLite?

public class Main extends Activity {    
   @Override
   protected void onCreate(Bundle savedInstanceState) {
        ...
        PublicPar.myContext=getApplicationContext();
    RuleMain dBMainHelper=new RuleMain(PublicPar.myContext);
    return dBMainHelper.ListAllRuleMain();
        ...
   }
}

助手:

package dal;

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

import model.MPublicPar.IncomingType;
import model.MRule;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class RuleMain  extends SQLiteOpenHelper {

    private final static String DBName="smsforwardrulemain.db";
    private final static String TableRuleMain="rulemain";     

    public RuleMain(Context context) {
        super(context, DBName, null, DBPublicPar.DBVersion);  
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        String sql = "Create table " 
                + TableRuleMain
                + " (ruleID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
                + "enabled INTEGER NOT NULL," 
                + "incomingType INTEGER NOT NULL," 
                + "name TEXT NOT NULL" 
                + ");";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        String sql=" DROP TABLE IF EXISTS "+TableRuleMain;
        db.execSQL(sql); 
        onCreate(db);
    }   


    public List<MRule> ListAllRuleMain(){   
        SQLiteDatabase db = this.getWritableDatabase(); 
        Cursor cursor = db.rawQuery("SELECT * FROM "+TableRuleMain, null);  
        List<MRule> myRuleMainList=GetMRuleListFromCursor(cursor);
        cursor.close();
        db.close();
        return myRuleMainList;      
    }   

}

0 个答案:

没有答案