Reputation: 1
I am trying to create an example to know how Handlers work. As shown in the code belwo, I created a workerThread that runs for ever and increment the variable i. within the run() method, i want to pass the value of the incremented variable to a TextView as shown in the body of the Handler class.
The problem is, the line in which there is "new Handler()" and "handler.sendMessage(m)" are marked with red
please let me know how to solve this problem
MainActivity
public class MainActivity extends AppCompatActivity {
private final static String TAG = MainActivity.class.getClass().getSimpleName();
private TextView mtvIncr = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.mtvIncr = (TextView) findViewById(R.id.tvValue);
new WorkerThread().start();
}
Handler handler =new Handler() {//ERROR
@Override
public void handleMessage(Message msg) {
int sentInt = msg.getData().getInt("what");
mtvIncr.setText("r:"+Integer.toString(sentInt));
}
};
class WorkerThread extends Thread {
private int i = 0;
android.os.Handler mHandler = null;
@Override
public void run() {
super.run();
Looper.prepare();
while(true) {
Log.d(TAG, SubTag.bullet("WorkerThread", "i: " + (i++)));
SystemClock.sleep(1000);
Message m = new Message();
Bundle b = new Bundle();
b.putInt("what", i); // for example
m.setData(b);
handler.sendMessage(m);//ERROR
}
}
}
}
Upvotes: 0
Views: 719
Reputation: 2322
Use Message.obtain()
to get a Message object
While the constructor of Message is public, the best way to get one of these is to call Message.obtain() or one of the Handler.obtainMessage() methods, which will pull them from a pool of recycled objects.
And use obj
attribute msg.obj = b;
obj: An arbitrary object to send to the recipient.
Info from:
https://developer.android.com/reference/android/os/Message.html
Example:
Handler handler =new Handler() {
@Override
public void handleMessage(Message msg) {
int sentInt = ((Bundle)msg.obj).getInt("what");
mtvIncr.setText("r:"+Integer.toString(sentInt));
}
};
class WorkerThread extends Thread {
private int i = 0;
android.os.Handler mHandler = null;
@Override
public void run() {
super.run();
Looper.prepare();
while(true) {
Log.d(TAG, SubTag.bullet("WorkerThread", "i: " + (i++)));
SystemClock.sleep(1000);
Message msg = Message.obtain();
Bundle b = new Bundle();
b.putInt("what", i); // for example
msg.obj = b;
handler.sendMessage(msg);
}
}
}
Upvotes: 0