2011-01-12 57 views
2

我創建了一個函數,用於更新我需要在多個視圖上使用的數據庫中的某些值。現在每個類都有自己的代碼副本。基本上我讀了值,然後想更新文本視圖。如何從另一個類調用引用(TextView)findViewById

我爲DisplayTop做了一個類,它完成了這項工作,並且它在本地非常棒。但不知何故,我需要通過我認爲的函數發送(TextView)findViewById。我希望我說得對。那麼對此的調用以及如何解決(TextView)findViewById。謝謝你的幫助!

public void DisplayTop2() 
{ 


    int UserID = 1; 
    String D=Fun.getCurrentDateString(); 
    String Sql; 

    Double a = 0.0; 
    Double b = 0.0; 

    SQLiteDatabase Db; 

    String myPath = DB_PATH + DB_NAME; 
    Db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); 



    Sql =" SELECT a,b " + 
    " FROM test " + 
    " where Dte = '" + D + "' and UserID = " + UserID; 

    try { 
    Cursor c = Db.rawQuery(Sql, null); 

    if (c != null) { 
    if (c.moveToFirst()) { 
    do { 


     a += (c.getDouble(c.getColumnIndex("a"))); 

     b += (c.getDouble(c.getColumnIndex("b"))); 

    }while (c.moveToNext()); 
    } 
    } 

    c.close(); 
    } catch (Exception e) { 

    } 
    Db.close(); 

    // Here is where the problem is. The real app has 5 fields. 
    // I can pass the R.id.a 
    // But how do I pass the reference to findViewById to the activity that called this 

    TextView tvt4 = (TextView)findViewById(R.id.a); 
    D = Fun.round(a,1,BigDecimal.ROUND_HALF_UP); 
    tvt4.setText(D) ; 

    tvt4 = (TextView)findViewById(R.id.b); 
    D = Fun.round(b,1,BigDecimal.ROUND_HALF_UP); 
    tvt4.setText(D) ; 



}; 

回答

3

我想我會嘗試讓自己的Activity內的所有用戶界面的更新,而不是繞過TextView對象。爲什麼不創建一個Bean來填充並返回到調用活動?例如:

public class Mybean { 
    private String fieldA; 
    private String fieldB; 
    // create constructor and getters and setters here 
} 

然後填充並返回數據庫代碼中的bean。

public MyBean DisplayTop2() { 
    ... 
    MyBean bean = new MyBean(); 
    bean.setFieldA(Fun.round(a,1,BigDecimal.ROUND_HALF_UP)); 
    bean.setFieldB(Fun.round(b,1,BigDecimal.ROUND_HALF_UP)); 
    return bean; 
} 

然後填充在Activity的UI:

... 
MyBean bean = MyDBClass.DisplayTop2(); 
TextView txtA = (TextView)findViewById(R.id.mytextviewA); 
TextView txtB = (TextView)findViewById(R.id.mytextviewB); 
txtA.setText(bean.getFieldA()); 
txtB.setText(bean.getFieldB()); 

這樣可以使你的所有UI代碼分開你的數據庫代碼。

+0

另一個騙子的方法是從活動中傳遞上下文,但是你的解決方案要乾淨得多。 – sgarman 2011-01-12 16:30:22