您好,登錄后才能下訂單哦!
要實現TextView文本內容與數據庫實時同步,可以通過以下步驟:
public class DatabaseHelper extends SQLiteOpenHelper {
// Database creation and upgrade code
public List<String> getData() {
List<String> dataList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM your_table", null);
while(cursor.moveToNext()) {
String data = cursor.getString(cursor.getColumnIndex("your_column"));
dataList.add(data);
}
cursor.close();
db.close();
return dataList;
}
}
public class MainActivity extends AppCompatActivity {
private DatabaseHelper dbHelper;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new DatabaseHelper(this);
textView = findViewById(R.id.text_view);
updateTextView();
}
private void updateTextView() {
List<String> dataList = dbHelper.getData();
StringBuilder stringBuilder = new StringBuilder();
for(String data : dataList) {
stringBuilder.append(data).append("\n");
}
textView.setText(stringBuilder.toString());
}
}
private final Handler handler = new Handler();
private final Runnable updateTextRunnable = new Runnable() {
@Override
public void run() {
updateTextView();
handler.postDelayed(this, 1000); // 1秒刷新一次
}
};
@Override
protected void onResume() {
super.onResume();
handler.post(updateTextRunnable);
}
@Override
protected void onPause() {
super.onPause();
handler.removeCallbacks(updateTextRunnable);
}
通過以上步驟,就可以實現TextView文本內容與數據庫實時同步的效果。當數據庫中的數據發生變化時,TextView的內容也會實時更新。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。