Issue
i have an activity where i have a text view. I am also using an sdk which has some events. Within on of these events i need to display some data at the TextView. The events are in an external class and i got them via some interfaces. The interfaces iam implementing within the Activity. I am using Handler and Message to set the text into the TextView within the implementation of the interface. I would like to know if there is another way to set the text within the the interfaces except Handler and Message.
Here is that code:
public class MyActivity extends AppCompatActivity {
private TextView nameTextView;
// some code
// implementing interfaces of external class
Service.ServiceEvents events = new Service.ServiceEvents() {
@Override
public void onSomeEvent(String name) {
nameTextView.setText(name); // not working
Message m = myHandler.obtainMessage(0, nameTextView);
m.sendToTarget();
}
Handler myHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message message) {
String s = message.obj.toString();
nameTextView.setText(s);
}
};
}
} // end of activity
Is there another way to set the text in the TextView? Please Help.
Solution
What to use
You can do it by using an interface.
How to implement
Create a new
interface
and give it a name whatever u like.(Here it isSampleInterface
).Add some void methods to like this
void onSomeEvent(String name);
Create a object of it in the class where you get the data from the sdk and add this listener in its constructor. Something like this
public YourJavaClassName(SampleInterface sampleInterface) { this.sampleInterface= sampleInterface; }
When you receive an update in the sdk, you can call it like this
void onDataReceived(String name){// I don't know how you get the value from the sdk so I wrote this sampleInterface.onSomeEvent(name); }
You are done with implementing it in the sdk receiver class. Now you need to add to the main activity to receive and update data.
Create the object of the class where you receive the data from the sdk.Like this
MySDKReceiverClass mysdkreceiverclass; mysdkreceiverclass = new MySDKReceiverClass(this);
Implement the interface in the activity and there you ge the values and you can set it in the textview.
Note: You need not add any runnable or handler or anything.Whenever there is a value change, the listener is called and the value is set.
Answered By - Sambhav Khandelwal
Answer Checked By - Marilyn (JavaFixing Volunteer)