1

创建对象时似乎SQLiteOpenHelper需要传递Context参数,所以我传入PublicPar.myContext=getApplicationContext()Main(扩展Activity)。

但是在IntentService里面,没有UI,也没有Activity,可能我用不了getApplicationContext()。使用时如何操作 SQLite IntentService

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;      
    }   

}
4

0 回答 0