2014-08-30 62 views
0

大家好我是Android新手,這個應用程序是我第一個使用數據庫的應用程序。在我的應用我有DatabaseHandler類這種簡單的結構Android使用DatabaseHandler出活動

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

現在在其他類如姓名TSMS我可以填寫字段ReceivedFields爲:

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類函數來填充沒有任何錯誤,我想將其保存到數據庫:

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

現在我想保存記錄到數據庫到for我敢確定DatabaseHandler db = new DatabaseHandler(this);,如此我得到這個錯誤之前,我無法解析:

enter image description here

+0

你是否在活動中初始化你的數據庫處理器類?或只在一個Java類? – Ranjit 2014-08-30 06:59:26

+0

@RanjitPati只是一個java類 – 2014-08-30 07:00:21

+1

然後你必須使用應用程序標籤上下文..或傳遞上下文的結構.. – Ranjit 2014-08-30 07:01:03

回答

3

你有上下文傳遞給數據庫處理器類。所以你可以使用Activity,Service或Broadcast Receiver來完成。所以這個構造器

public ReceiveFields(){ 

    } 

改爲從活動,服務或接收器

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

傳遞上下文,你可以使用ctx,而不是this