错误:只有创建视图层次结构的原始线程才能触摸其视图

发布于 2024-10-19 02:07:00 字数 4147 浏览 4 评论 0原文

您好,感谢您查看我的问题。 我是 C 语言的中级程序员,但 Android 新手。我一直在尝试让聊天程序正常工作。假设下面代码中的其他所有内容都工作正常。我想问的一个问题是,当我尝试从运行的线程中 setText() 时,我得到了上面的异常。我看了很多很多网站,也在这里。发现了很多东西,但我真的不明白。请以最简单的方式向我解释,或者如果可能的话,为我提供一些简单的修复。

非常感谢!!

public class chatter extends Activity {

private String name = "Unknown User";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);



    final EditText msgToServer = (EditText) findViewById(R.id.msgBox);
    final EditText chatFromServer = (EditText) findViewById(R.id.chatBox); 

    final Button MsgToServer = (Button) findViewById(R.id.sendButton);

    Socket socket = null;
    String ipAddress = "192.168.1.103";
    try {
        InetAddress serverAddr = InetAddress.getByName(ipAddress);
        Socket socketMain = new Socket(serverAddr, 4444);
        socket = socketMain;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.e("TCP", "error", e);
    }

    final OutMsg outMsg = new OutMsg(socket);
    Thread msgSenderThread = new Thread(outMsg);
    msgSenderThread.start();

    //chatFromServer.post(new InMsg(socket, chatFromServer));
    Thread msgReceiverThread = new Thread(new InMsg(socket, chatFromServer));
    msgReceiverThread.start();

    MsgToServer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String msgToServerString; 
            msgToServerString = msgToServer.getText().toString();
            outMsg.message = name + ": " + msgToServerString;
            outMsg.readyToSend = true;
            msgToServer.setText("");
        }
    });
}

public void updateResultsInUi (String msg)
{
    final EditText chatFromServer = (EditText) findViewById(R.id.chatBox); 
    chatFromServer.setText(msg); 
}

public class InMsg implements Runnable {

    Socket socket;
    EditText chatFromServer;
    public InMsg(Socket socket, EditText chatFromServer)
    {
        this.socket = socket;
        this.chatFromServer = chatFromServer;
    }

    public void run(){
        try {
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String str = "FIRSTMESSAGEFROMSERVER";
            while (true)
            {
                if (str.equals("FIRSTMESSAGEFROMSERVER"))
                    str = in.readLine();
                else
                    str = str + "\n" + in.readLine();
                Log.e("TCP", "got the message: " + str);
     //Here is where went wrong******************
                chatFromServer.setText(str);
     //******************************************
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.e("TCP", "error in receiving", e);
        }
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.setNameMenu:
        setname();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

public void populateChatBox (String msgFromS)
{
    Log.e("TCP", "going in to popC");
    final EditText textNameInput = (EditText) findViewById(R.id.nameBox);
    Log.e("TCP", " popC");
    textNameInput.setText(msgFromS);
    Log.e("TCP", "going out from popC");
}

public void setname()
{
    setContentView(R.layout.custom_dialog);
    final EditText textNameInput = (EditText) findViewById(R.id.nameBox);
    Button submitNameButton = (Button) findViewById(R.id.submitNameButton);
    submitNameButton.setOnClickListener(new OnClickListener() {
    @Override
        public void onClick(View v) {
        String nameinput = textNameInput.getText().toString();
            if (!name.equals(""))
                name = nameinput;
            setContentView(R.layout.main);
        }
    });
}
}

Hi and thank you for looking at my question.
I am an intermediate programmer in C but an Android newbie. I have been trying to get a chat programming working. Assuming everything else in the code below works perfectly. The one question I like to ask is when I try to setText() from a thread running, I get an exception above. I looked at many many websites and here too. Found many things, but I really do not understand. Please explain to me in the most simple way or offer me some simple fix if possible.

Thank you very much!!

public class chatter extends Activity {

private String name = "Unknown User";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);



    final EditText msgToServer = (EditText) findViewById(R.id.msgBox);
    final EditText chatFromServer = (EditText) findViewById(R.id.chatBox); 

    final Button MsgToServer = (Button) findViewById(R.id.sendButton);

    Socket socket = null;
    String ipAddress = "192.168.1.103";
    try {
        InetAddress serverAddr = InetAddress.getByName(ipAddress);
        Socket socketMain = new Socket(serverAddr, 4444);
        socket = socketMain;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.e("TCP", "error", e);
    }

    final OutMsg outMsg = new OutMsg(socket);
    Thread msgSenderThread = new Thread(outMsg);
    msgSenderThread.start();

    //chatFromServer.post(new InMsg(socket, chatFromServer));
    Thread msgReceiverThread = new Thread(new InMsg(socket, chatFromServer));
    msgReceiverThread.start();

    MsgToServer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String msgToServerString; 
            msgToServerString = msgToServer.getText().toString();
            outMsg.message = name + ": " + msgToServerString;
            outMsg.readyToSend = true;
            msgToServer.setText("");
        }
    });
}

public void updateResultsInUi (String msg)
{
    final EditText chatFromServer = (EditText) findViewById(R.id.chatBox); 
    chatFromServer.setText(msg); 
}

public class InMsg implements Runnable {

    Socket socket;
    EditText chatFromServer;
    public InMsg(Socket socket, EditText chatFromServer)
    {
        this.socket = socket;
        this.chatFromServer = chatFromServer;
    }

    public void run(){
        try {
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String str = "FIRSTMESSAGEFROMSERVER";
            while (true)
            {
                if (str.equals("FIRSTMESSAGEFROMSERVER"))
                    str = in.readLine();
                else
                    str = str + "\n" + in.readLine();
                Log.e("TCP", "got the message: " + str);
     //Here is where went wrong******************
                chatFromServer.setText(str);
     //******************************************
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.e("TCP", "error in receiving", e);
        }
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.setNameMenu:
        setname();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

public void populateChatBox (String msgFromS)
{
    Log.e("TCP", "going in to popC");
    final EditText textNameInput = (EditText) findViewById(R.id.nameBox);
    Log.e("TCP", " popC");
    textNameInput.setText(msgFromS);
    Log.e("TCP", "going out from popC");
}

public void setname()
{
    setContentView(R.layout.custom_dialog);
    final EditText textNameInput = (EditText) findViewById(R.id.nameBox);
    Button submitNameButton = (Button) findViewById(R.id.submitNameButton);
    submitNameButton.setOnClickListener(new OnClickListener() {
    @Override
        public void onClick(View v) {
        String nameinput = textNameInput.getText().toString();
            if (!name.equals(""))
                name = nameinput;
            setContentView(R.layout.main);
        }
    });
}
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

爱已欠费 2024-10-26 02:07:00

在你的 run() 方法中:

Message msg = new Message();
String textTochange = "text";
msg.obj = textTochange;
mHandler.sendMessage(msg);

在你的 UI 线程中创建 mHandler;

Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String text = (String)msg.obj;
            //call setText here
        }
};

In your run() method:

Message msg = new Message();
String textTochange = "text";
msg.obj = textTochange;
mHandler.sendMessage(msg);

Create the mHandler in your UI thread;

Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String text = (String)msg.obj;
            //call setText here
        }
};
深陷 2024-10-26 02:07:00

设置文本时您不在 UI 线程上。如果您想处理 UI 项目,则需要使用 UI。在 UI 线程上创建一个消息处理程序,将消息发布到其中,然后从 UI 线程上的处理程序调用 setText。

You are not on the UI thread when setting the text. You need to be on UI if you want to work on UI items. Create a message handler on the UI thread, post your messages to it and call setText from the handler on the UI thread.

睡美人的小仙女 2024-10-26 02:07:00

每当你在一个线程中时,你都可以这样做:

msgToServer.post(new Runnable() {
    public void run() {
        msgToServer.setText("your text here");
    }
}

you can do this whenever you are in a thread:

msgToServer.post(new Runnable() {
    public void run() {
        msgToServer.setText("your text here");
    }
}
莳間冲淡了誓言ζ 2024-10-26 02:07:00

您的问题是,某些交互只能在 UI 线程上进行。这是其中之一。

看起来您可能想使用 AsyncTask

http://developer.android.com/reference /android/os/AsyncTask.html

基本上,您可以将 Runnable 改为 AsyncTask,并在 onProgressUpdate 中执行 setText,该操作在 UIThread 上运行。

Your problem is that there are certain interactions that you can only do on the UI thread. This is one of them.

Looks like you might want to use AsyncTask

http://developer.android.com/reference/android/os/AsyncTask.html

Basically you could make your Runnable an AsyncTask instead and do the setText in onProgressUpdate, which gets run on the UIThread.

孤蝉 2024-10-26 02:07:00

如果您想使用 AsyncTask 在后台运行,我会这样做:

public class UpdateTextProgress_Task extends AsyncTask<Void,String,Void> {
    Socket socket;
    EditText chatFromServer;    

    UpdateTextProgress_Task(EditText chatFromServer, Socket socket){
            this.socket = socket;
            this.chatFromServer = chatFromServer;
}

    @Override
    protected Void doInBackground(Void... params) {
       try {
               BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
               String str = "FIRSTMESSAGEFROMSERVER";

               while(true){
                    if (str.equals("FIRSTMESSAGEFROMSERVER")){
                         str = in.readLine();
                    }
                    else{
                         str = str + "\n" + in.readLine();
                    }
                    Log.e("TCP", "got the message: " + str);

              publishProgress(str); // calls the onProgressUpdate method
          }catch (IOException e) {
        Log.e("UpdateTextProgress", e.getMessage());
    }
    return null;
}

@Override
protected void onProgressUpdate(String... progress) {
    chatFromServer.setText(progress[0]); //now we are on the UI thread so we can update our EditText

}

@Override
protected void onPostExecute(Void result) {
    super.onPostExecute(result);
    Log.e("UpdateTextProgress", "Finished");
}

}

执行代码:

UpdateTextProgress_Task task = new UpdateTextProgress_Task(chatFromServer,socket);
task.execute();

If you would like to use an AsyncTask to run in the background this is how I would do it:

public class UpdateTextProgress_Task extends AsyncTask<Void,String,Void> {
    Socket socket;
    EditText chatFromServer;    

    UpdateTextProgress_Task(EditText chatFromServer, Socket socket){
            this.socket = socket;
            this.chatFromServer = chatFromServer;
}

    @Override
    protected Void doInBackground(Void... params) {
       try {
               BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
               String str = "FIRSTMESSAGEFROMSERVER";

               while(true){
                    if (str.equals("FIRSTMESSAGEFROMSERVER")){
                         str = in.readLine();
                    }
                    else{
                         str = str + "\n" + in.readLine();
                    }
                    Log.e("TCP", "got the message: " + str);

              publishProgress(str); // calls the onProgressUpdate method
          }catch (IOException e) {
        Log.e("UpdateTextProgress", e.getMessage());
    }
    return null;
}

@Override
protected void onProgressUpdate(String... progress) {
    chatFromServer.setText(progress[0]); //now we are on the UI thread so we can update our EditText

}

@Override
protected void onPostExecute(Void result) {
    super.onPostExecute(result);
    Log.e("UpdateTextProgress", "Finished");
}

}

To execute the code:

UpdateTextProgress_Task task = new UpdateTextProgress_Task(chatFromServer,socket);
task.execute();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文