[英]Android: SetText in handler doesn't change text in TextView
我有一個連接到藍牙並顯示收到的信息的應用程序。 按下時,活動沒有被殺死,我可以 go 回到活動,一切都是一樣的。 該活動在后台收集數據,一切都很好我有一個按鈕,按下時會殺死所有活動(包括顯示數據的活動)。 當我嘗試再次創建該活動時,數據不斷涌現,我仍然可以處理它並將其寫入文件,但它不會在 UI 中顯示。 在第二次創建活動后,處理程序中的 setText function 似乎不起作用(setText 確實在處理程序之外工作)。
如果第二次創建活動,則synced
的 boolean 值為真。 這是OnCreate
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
loading_panel = findViewById(R.id.loadingPanel);
loading_panel.setVisibility(View.GONE);
connectionButton = (Button) findViewById(R.id.connection_button);
gsrTextView = (TextView) findViewById(R.id.gsr_textview);
emgTextView = (TextView) findViewById(R.id.emg_textview);
adxlTextView = (TextView) findViewById(R.id.adxl_textview);
fsrTextView = (TextView) findViewById(R.id.fsr_textview);
textviews_set=true;
if(synced)
{
setConnected(currMac);
manageConnection();
Button sync_button = (Button) findViewById(R.id.sync_button);
sync_button.setText(R.string.synced_text);
}
// more code
}
OnBackPressed
的實現:
@Override
public void onBackPressed() {
Intent i = new Intent(AdminActivity.this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
}
這是處理程序的(部分):
@SuppressLint("HandlerLeak")
public final Handler handler = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
switch (msg.what) {
//a lot of code for other cases
case READ_SUCCESS:
String s = (String) msg.obj;
showData(s);
break;
}
}
}
這是(部分) showData
: private void showData(String s) { // todo: 1.parse the json; 2.在 textViews 上顯示數據(json 組件)
try {
//Log.d(LOG_TAG, "the new string is " + s);
JSONObject json = new JSONObject(s);
// Collect the sensors measurements
String gsrMeasure = json.getString("gsr");
String emgMeasure = json.getString("emg");
String adxlMeasure = json.getString("adxl");
String fsrMeasure = json.getString("fsr");
String time_str = json.getString("time");
// Show the data
if(textviews_set) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d(LOG_TAG, "ABOUT TO SET TEXT");
gsrTextView.setText(gsrMeasure);
emgTextView.setText(emgMeasure);
adxlTextView.setText(adxlMeasure);
fsrTextView.setText(fsrMeasure);
}
});
}
//more code
}
}
我什至確保我在 UI 線程上運行 setText,即使它在沒有runOnUiThread
的活動的第一次運行時工作我還認為可能在調用findViewByID
之前調用了處理程序,但我使用了 boolean 變量textviews_set
確保它不會發生
值得一提的是,當我第一次創建活動時,藍牙設備沒有連接,因此處理程序沒有運行,所以問題很可能就在那里。 我只是不知道到底在哪里,或者如何解決它。
根據提供的信息,以下是最好的建議。
所以在textviews_set=true;
之前在onCreate()
中嘗試以下操作;
gsrTextView.setText(" ");
emgTextView.setText(" ");
adxlTextView.setText(" ");
fsrTextView.setText(" ");
希望這能解決問題。
參考:
如果有人遇到同樣的問題,我發現了問題所在。 我將所有文本視圖聲明為非靜態的,因此在第二次創建活動時,由於某種原因,處理程序仍然引用了活動第一個實例的文本視圖。 我所要做的就是將 class 中的 textviews 聲明為static
,所以當我第二次創建活動時,textviews 已經聲明並引用了 Z0F635D0E0F3874FFFA8B7ZE 中的實際 textviews。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.