2013-07-19 57 views
0

我(擁有平庸的開發技能)實際上嘗試將Sugar用作我的Android項目的數據庫包裝器。 因此,我沿着「入門指南」(http://satyan.github.io/sugar/getting-started.html),儘快做好準備。嘗試執行Sugar數據庫CRUD操作時出錯

我創造了我的實體類,稱爲DataSet.java:

import com.orm.SugarRecord; 

public class DataSet extends SugarRecord{ 
    int someData; 
    double evenMoreData; 

    public DataSet(Context ctx){ 
     super(ctx); 
    } 

public DataSet(Context ctx, 
     int someData, 
     long evenMoreData) { 
    super(ctx); 
    this.someData = someData; 
    this.evenMoreData = evenMoreData; 
    } 
} 

我調用類的方式如下:

someGreatClass something; 
someMoreGreatCode somemore; 

DataSet dataSet = new DataSet(
      ctx,       // Here Eclipse throws the error 
      something.method(), 
      somemore.anothermethod()); 
DataSet.save(); 

當我嘗試建立這一點,並推到我的設備時,Eclipse拒絕編譯並拋出這個錯誤:

ctx cannot be resolved to a variable 

考慮的事實是,我重新對於Android開發來說,這個錯誤可能很明顯,我希望得到一個小技巧來解決這個問題。

P.S:另外,我不完全得到開發者的聲明中得到-開始-注:

Please retain one constructor with Context argument. (This constraint will be removed in subsequent release.) 

非常感謝您!

//編輯:的確從LocationDataSet編輯類名來的數據進行澄清設置

+0

您是否添加(或擴展)了SugarApplication? – IncrediApp

回答

0

首先,在獲得啓動的音符告訴你,你需要一個構造函數只有一個環境參數,你這樣做這裏,所以也沒什麼

public DataSet(Context ctx){ 
    super(ctx); 
} 

ctx cannot be resolved to a variable 

我想你沒有一個變量稱爲CTX,我不知道你是否熟悉Android的背景? (基本上上下文是服務或活動),如果您在活動或服務中使用此代碼,只需使用「this」關鍵字而不是ctx變量

您提供的代碼並不真實顯示你在做什麼,但是你向我們展示了'DataSet'的代碼,但是這個錯誤發生在一個LocationDataSet中?你打電話保存DataSet? 必須在對象上調用save方法,而不是類。

另外不要忘記,糖需要在清單

更新與示例中的特殊應用類:

你的數據集類(sugarrecord)應該是這樣的,這是在你的代碼確定據我可以看到

public class DataSet extends SugarRecord<DataSet>{ 

private String someData; 

public DataSet(Context c){ 
    super(c); 
} 

    public DataSet(Context c, String someData){ 
    super(c); 
    this.someData = someData; 
} 

} 

使用記錄應該是這樣的

public class SomeActivity extends Activity { 

    public void someMethodThatUsesDataSet(){ 
     // Create a dataset object with some data you want the save and a context 
     // The context we use here is 'this', this is the current instance of SomeActivity, 
     // you absolutely need this, I think this is what you're doing wrong, 
     // you can't use ctx here because that's not a known variable at this point 
     DataSet example = new DataSet(this, "data you want to save"); 

     // Tell Sugar to save this record in the database 
     example.save(); 
    } 
} 
012的活動
+0

LocationDataSet是我的代碼中的類的原始名稱,我忘了它將其更改爲DataSet。 – Miller

+0

使用「this」是什麼意思?如果我只是用「this」替換「ctx」,Eclipse立即拋出錯誤「構造函數DataSet(ShowLocationActivity,long,long,double,double,float,float,String,boolean,int,int,String,int)未定義「(如果我在給班級打電話時使用它) – Miller

+0

如果你的ShowLocationActivity擴展了Activity,它是一個有效的上下文。你確定構造函數的其他參數的類型是正確的嗎? – Quentin

相關問題