[英]Why not update UI elemnts in Android
在我的应用程序中,我应该使用socket.io并且我想要什么时候收到我的事件更新UI元素!
我写了下面的代码,我收到了我的事件显示日志,但没有更新任何 UI!
我想在收到事件时,检查这个获胜者是否是用户,然后更新我的用户界面。
在logCat 中显示我的logs
但不更新任何UI 元素!
我的代码:
public void onsocketFinishRecieve(final JSONObject ob) {
try {
((BaseActivity) context).runOnUiThread(() -> {
try {
cancelTimer();
final FinishResponse finishResponse = new Gson().fromJson(ob.toString(), FinishResponse.class);
if (finishResponse.getRes().getWinnerName().equals("not user") || finishResponse.getRes().getWinnerName().equals("not winner")) {
winnerNameWhenFinished = "Not winner";
} else {
winnerNameWhenFinished = finishResponse.getRes().getWinnerName();
}
if (detail.getId() != null) {
if (detail.getId() == finishResponse.getRes().getId()) {
//Set new winner layouts
//Register in auction
if (Constants.profileResponse != null) {
if (Constants.profileResponse.getRes() != null) {
if (Constants.profileResponse.getRes().getUser() != null) {
//Winner
if (Constants.profileResponse.getRes().getUser().getId().equals(finishResponse.getRes().getUserId())) {
Log.e("FinishedSocket", "1");
detailPage_bottomWinnerRateTxt.setVisibility(View.GONE);
detailPage_bottomWinnerBuyTxt.setText("Show basket");
detailPage_bottomWinnerBuyTxt.setOnClickListener(v -> {
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("OPEN_CART_IN_MAIN", "true");
startActivity(intent);
});
} else {
Log.e("FinishedSocket", "2");
//Loser
detailPage_bottomWinnerBuyTxt.setText("Awesome offers");
}
}
}
}
}
}
} catch (Exception e) {
Log.e("DetailResErr", e.getMessage());
}
});
} catch (Exception e) {
Log.e("DetailResErr", e.getMessage());
}
}
Logcat 消息:
2020-03-08 13:37:37.399 E/FinishedSocket: 2
在logcat
显示我上面的消息,为什么不运行这一行: detailPage_bottomWinnerBuyTxt.setText("Awesome offers");
??
我该如何解决?
尝试像这样在主线程上运行它。
someActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
//Your code to run in GUI thread here
detailPage_bottomWinnerBuyTxt.setText("Awesome offers");
}
});
套接字在 IOThread 上工作,而其他端 UI 在称为 UI 线程的单独线程上工作。 因此,更新 UI 线程上的 UI 元素。 使用注解:
@UiThread
public abstract void setText(@NonNull String text) { ... }
如需了解更多注释,请查看以下博客: https : //medium.com/@gurwindersingh_37022/android-annotations-30b4a2850d0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.