DolDurma
DolDurma

Reputation: 17331

Android use DatabaseHandler out of Activity

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:

enter image description here

Upvotes: 0

Views: 109

Answers (1)

Seshu Vinay
Seshu Vinay

Reputation: 13588

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.

Upvotes: 3

Related Questions