我正在尝试使用以下功能在Android应用中设置TextView的文本:
@Override
public void onOSSubscriptionChanged(OSSubscriptionStateChanges stateChanges) {
if (!stateChanges.getFrom().getSubscribed() && stateChanges.getTo().getSubscribed()) {
new AlertDialog.Builder(this)
.setMessage("You have successfully subscribed to push notifications!")
.show();
// Get player ID and output to Main Activity
TextView playerIdView = findViewById(R.id.playerIdView);
playerIdView.setText(stateChanges.getTo().getUserId());
}
Log.i("Debug", "onOSPermissionsChanged: " + stateChanges);
}
这使用https://github.com/request/request#forms获取用户的唯一ID,该ID作为字符串返回。经过一些调试后,我意识到TextView
方法之外无法更改onCreate()
的内容。但是,需要stateChanges
参数,该参数仅存在于onOSSubscriptionChanged
中。有什么办法可以解决这个问题?
编辑:错误在其他地方。 stateChanges.getTo().getUserId()
返回了null
。
答案 0 :(得分:1)
您需要在UI线程上进行设置
playerIdView.post(new Runnable() {
public void run() {
playerIdView.setText(stateChanges.getTo().getUserId());
}
});
或
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = new Runnable() {
@Override
public void run() {
playerIdView.setText(stateChanges.getTo().getUserId());}
};
mainHandler.post(myRunnable);
答案 1 :(得分:1)
您需要在textview
方法中初始化onCreateView()
,此后,只要在UI线程中,几乎可以在任何地方使用该textView
。因此,将您的代码更改为以下内容:
全局声明textview
,以便您可以在活动实例的任何地方使用它。
TextView playerIdView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
playerIdView = findViewById(R.id.playerIdView);
}
,然后在您的onSSubscription
方法中执行以下操作:
@Override
public void onOSSubscriptionChanged(OSSubscriptionStateChanges stateChanges) {
if (!stateChanges.getFrom().getSubscribed() && stateChanges.getTo().getSubscribed()) {
new AlertDialog.Builder(this)
.setMessage("You have successfully subscribed to push notifications!")
.show();
// Get player ID and output to Main Activity
playerIdView.setText(stateChanges.getTo().getUserId());
}
Log.i("Debug", "onOSPermissionsChanged: " + stateChanges);
}
答案 2 :(得分:0)
尝试一下
runOnUiThread(new Runnable(){
@override
public void run() {
playerIdView.setText(stateChanges.getTo().getUserId());
}
})