How call reference (TextView)findViewById from another class
I have created a function that updates some values from a database that I need to use on multiple views. Right now each class has its own copy of the code. Basically I read the values and then want to update the text views.
I made a class for the DisplayTop which does the work, and locally its great. But somehow I need to get the (TextView)findViewById sent over the the function I think. I hope I am saying this right. So what is the call to this and how to I resolved the (TextView)findViewById. thanks for any help!
public void DisplayTop2()
{
int UserID = 1;
String D=Fun.getCurrentDateString();
String Sql;
Double a = 0.0;
Double b = 0.0;
SQLiteData开发者_如何学Cbase 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 ) ;
};
I think I would try and keep all the UI updates within my Activity
, rather than passing around TextView
objects. Why not create a Bean
to populate and return to the calling activity? Something like:
public class Mybean {
private String fieldA;
private String fieldB;
// create constructor and getters and setters here
}
Then populate and return the bean in your database code.
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;
}
Then populate the UI in your Activity
:
...
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());
This keeps all your UI code separate from your DB code.
精彩评论