Answer the question
In order to leave comments, you need to log in
How to solve the problem with the textview handler?
There was a following problem.
There is a TextView and a Handler to it (for output to it). I create a thread in which I pull the handler with some interval. Everything is going fine (all entries are displayed in the textView). But as soon as I turn the phone, new records stop being added (but the created thread continues to work). Although they are displayed in the log (in the Handler).
package com.example.abcd;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class MyActivity extends Activity {
public static final String LOG_D="MyDebug:";
public boolean b=false;
public Handler handler;
public TextView chat;
public String text;
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("bool",true);
Log.d(LOG_D,"Save");
}
public static Message getMessageFromString(String str, String key) {
Bundle messageBundle = new Bundle();
messageBundle.putString(key, str);
Message message = new Message();
message.setData(messageBundle);
return message;
}
@Override
public Object onRetainNonConfigurationInstance() {
return text;
}
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text="";
chat = (TextView)findViewById(R.id.chat);
handler = new Handler() {
public void handleMessage (final Message msg) {
MyActivity.this.runOnUiThread(new Runnable() {
public void run() {
String chatLine = msg.getData().getString("msg");
Log.d(LOG_D,chatLine);
chat.append(chatLine);
chat.append("\n");
chat.setVisibility(View.VISIBLE);
text+=chatLine+'\n';
}
});
}
};
if(savedInstanceState!=null){
b = savedInstanceState.getBoolean("bool");
text = (String)getLastNonConfigurationInstance();
handler.sendMessage(getMessageFromString(text,"msg"));
text="";
}
if(!b){
new Thread(new Runnable() {
@Override
public void run() {
int i=0;
while(true){
try {
Thread.currentThread().sleep(6000);
handler.sendMessage(getMessageFromString("text"+i,"msg"));
i++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
}
Answer the question
In order to leave comments, you need to log in
If your activity is recreated after a flip (default behavior), then the thread will access the handler from the past object, and post to it, and not to the new one. You have a memory leak here, old objects are not deleted by GC because your thread keeps references on them.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question