简体   繁体   中英

Cannot refer to a non-final variable str inside an inner class defined in a different method - How to fix this?

BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String str;
while ((str = rd.readLine()) != null) {
    runOnUiThread(new Runnable() {
        public void run() {
            TextView newMsg = new TextView(getApplicationContext());
            newMsg.setText(str);

            newMsg.setLayoutParams(new LayoutParams (
                                                LayoutParams.MATCH_PARENT,
                                                LayoutParams.WRAP_CONTENT));
                                        m_receivedMessagesLayout.addView(newMsg);
            }
    });
}

Here is the code. If I try to bring the loop into the UI thread, then it won't work because Android doesn't allow sockets on the main thread. I need the str as I need it to be a variable so can't make it final. What's a clean solution to get rid of this problem?

You can simply declare another variable inside your while loop which is final and gets assigned the value of str . This variable is local to the while loop and will get recreated on each iteration. You can then use that variable in your Runnable 's run() method.

while ((str = rd.readLine()) != null) {
    final String value = str;
    runOnUiThread(new Runnable() {
        public void run() {
            TextView newMsg = new TextView(getApplicationContext());
            newMsg.setText(value);

            newMsg.setLayoutParams(new LayoutParams (
                                                LayoutParams.MATCH_PARENT,
                                                LayoutParams.WRAP_CONTENT));
                                        m_receivedMessagesLayout.addView(newMsg);
            }
    });
}

not allowed to create socket in activity you Should use

AsyncTask<..,..,..>

to implement your code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM