【问题标题】:TextView setText() called in callbacks from wrong context [duplicate]在来自错误上下文的回调中调用 TextView setText() [重复]
【发布时间】:2021-04-15 13:37:18
【问题描述】:

成功注册后,我尝试实现网络服务发现并将名称设置为 textView。但我得到了一个android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. 异常。我的基本结构如下所示:

NsdManager.RegistrationListener mRegistrationListener;

onCreate() {
    mRegistrationListener = new NsdManager.RegistrationListener() {
        onServiceRegistered(serviceInfo) {
            TextView textView = (TextView) findViewById(R.id.nsdServiceNameText);
            textView.setText(serviceInfo.getServiceName());
        }
    }
    
    mNsdManager = (NsdManager) this.getBaseContext().getSystemService(Context.NSD_SERVICE);

    mNsdManager.registerService(
        serviceInfo,
        NsdManager.PROTOCOL_DNS_SD,
        mRegistrationListener);
}

对我来说,我可能在错误的上下文中编辑视图是有道理的,但我是如何到达那里的,更重要的是我该如何解决这个问题?

【问题讨论】:

  • 有些东西让你离开了主线程。那是什么,我不知道。如何修复它,提供链接:)
  • 在 UI 线程上调用 setText()。

标签: java android callback textview


【解决方案1】:

如果您在此处阅读NsdManager 的文档:https://developer.android.com/reference/android/net/nsd/NsdManager

上面写着:

API 是异步的,响应来自应用程序的请求 在单独的内部线程上进行侦听器回调。

因此,它会远离您应该更新 UI 的 UI 线程,正如 cmets 中指出的那样:

runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    textView.setText(serviceInfo.getServiceName());
                }
            });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多