如何在数据库中更新数据时更新网格布局数据?我想在服务中广播一条消息,并在数据库中更新数据时在此Acitivty上接收。但是,如果我在接收广播接收器上调用updateSummary()
,它会将新子节点添加到现有的gridLyout子节点。如何替换现有子节点并定期刷新网格布局?
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
updateSummary();
}
public void updateSummary()
{
gridLayout=(GridLayout)findViewById(R.id.newgrid);
DBHelper dbHelper = new DBHelper(this);
SQLiteDatabase mySummaryDB = dbHelper.getWritableDatabase();
if (mySummaryDB != null) {
String mycols=DBConstants.ID+","+DBConstants.NUMBER+","+DBConstants.DATE+","+DBConstants.TIME;
Cursor c0 = mySummaryDB.rawQuery("select distinct("+DBConstants.NUMBER+") from "+DBConstants.MASTER_DATA_TABLE+"", null);
if(c0!=null)
{
if(c0.moveToFirst())
{
do
{
String number = c0.getString(c0.getColumnIndex(DBConstants.NUMBER));
Cursor c1 = mySummaryDB.rawQuery("select "+mycols+" from "+DBConstants.MASTER_DATA_TABLE+" where "+DBConstants.NUMBER+"='"+NUMBER+"' order by "+DBConstants.MYDATETIME+" desc limit 1", null);
Log.i("summary",Integer.toString(c1.getCount()));
if(c1!=null)
{
if(c1.moveToFirst())
{
int increment=0;
do
{
String id = c1.getString(c1.getColumnIndex(DBConstants.ID));
String date = c1.getString(c1.getColumnIndex(DBConstants.DATE));
String time = c1.getString(c1.getColumnIndex(DBConstants.TIME));
Cursor c2 = mySummaryDB.query(DBConstants.MYDATA_TABLE,new String[]{DBConstants.NAME}, DBConstants.NUMBER+"=?", new String[]{number}, null, null, null);
String name="";
if(c2!=null)
{
if(c2.moveToFirst())
{
name = c2.getString(c2.getColumnIndex(DBConstants.NAME));
Log.i("summary", "name->"+name);
}
}
c2.close();
TextView nameTV = new TextView(this);
nameTV.setText(name);
gridLayout.addView(nameTV);
TextView dateTV = new TextView(this);
dateTV.setText(date);
gridLayout.addView(dateTV);
TextView timeTV = new TextView(this);
timeTV.setText(time);
gridLayout.addView(timeTV);
}
increment=increment+1;
}
while(c1.moveToNext());
}
}
}
while(c0.moveToNext());
}
}
dbHelper.close();
}
答案 0 :(得分:1)
我不是100%确定我是否知道你想做什么,但在我看来好像你想在你的GridLayout中有三个TextViews,当调用方法updateSummary时应该更新它们。如果是这样,您应该在活动的xml布局文件中定义它们并为其指定ID。在您的活动中使用函数textView = (TextView) findViewById(R.id.id_of_your_component)
,您可以通过id访问java代码中的TextViews,然后您可以使用textView.setText("your text")
更新这三个组件的文本,因为这似乎是您真正的想做。每次调用方法updateSummary时都会创建新的TextView,并将它们添加到GridLayout,但您只需要实例化它们一次(最好用xml布局),然后在方法中更新它们。
答案 1 :(得分:0)
我不确定它的Cursor部分,但一般来说这是你可以用来更新GridView的方法。
参考文献: 1. Building Layouts with an Adapter 2. Hold View Objects in a View Holder