Android use DatabaseHandler out of Activity

好久不见. 提交于 2019-12-11 21:05:37

问题


Hi all i'm new in Android and this application is my first app for use database. in my application i have DatabaseHandler class with this simple structure

public class DatabaseHandler extends SQLiteOpenHelper{
        private static String DB_PATH                   = "";
        private static final String DATABASE_NAME       = "tsms";
        private static String RECEIVE_FIELDS_TABLE      = "ReceiveFields";
        private static final String COLUMN_ID           = "id";

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

now in other class as name TSMS i can fill Fields ReceivedFields as :

public class ReceiveFields {
    public long lastId;
    public String smsNumber;
    public String mobileNumber;
    public String senderName;
    public String smsBody;
    public DateTimeD1 receiveDate;

    public ReceiveFields(){

    }
    public ReceiveFields(long lastId, String smsNumber, String mobileNumber, String senderName, String smsBody, DateTimeD1 receiveDate) {
        this.lastId = lastId;
        this.smsNumber = smsNumber;
        this.mobileNumber = mobileNumber;
        this.senderName = senderName;
        this.smsBody = smsBody;
        this.receiveDate = receiveDate;
    }

TSMS class function to fill without any error and i want to save it to database:

for (int i = 0; i <= strings.length - 1; i++) {
                String[] str1 = WSDLHelper.convert3(strings[i]);
                try {
                    receiveArray.add(new ReceiveFields(
                            Long.valueOf(str1[0]),
                            str1[1],
                            str1[2],
                            URLDecoder.decode(str1[3], "UTF-8"),
                            URLDecoder.decode(str1[4], "UTF-8"),
                            WSDLHelper.convertDate(str1[5])));
                }
                catch (UnsupportedEncodingException ex) {
                    throw new TException(PublicErrorList.NOT_EXIST_ERROR_DETAIL);
                }
            }

now i want to save records to database into for i'm define DatabaseHandler db = new DatabaseHandler(this); before that so i'm getting this error and i can not resolve that:


回答1:


You have to pass context to DatabaseHandler class. So you can do it with Activity, Service or Broadcast Receiver. So change this contructor

public ReceiveFields(){

    }

to

 public ReceiveFields(Context ctx){
    this.ctx=ctx; //create a field Context ctx;
    }

Pass context from activity, service or receiver and you can use ctx instead of this.



来源:https://stackoverflow.com/questions/25579837/android-use-databasehandler-out-of-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!