Reputation: 2811
I have two classes: a and b. In class a i have thread that increments the variable x by one while it's value is smaller than 1000. In class b(Activity class), i have a EditText named ed. Everytime x increments by one in class a, i want to set the text of ed from class b to x. How can this be done? See code below.
public Class a
{
int x = 0;
private void startThread()
{
MyThread = new Thread(new Runnable()
{
public void run()
{
while(x<1000)
{
x++;
//Change the text of ed from class b to x!!!!
sleep(100);
}
}
});
MyThread.start();
}
}
Class b extends Activity{
EditText ed;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ed =(EditText)findViewById(....);
}
}
Upvotes: 0
Views: 420
Reputation: 5055
I don't know your application, but I have 2 suggestions:
Class A
(class names always start with a capital letter), should keep a reference to class B
, e. g. private final B reference
There should be anoter class that provides a reference toclass B
.
EDIT
As suggested in the comment, you should use MVC. It solves your problem by nature.
Upvotes: 0
Reputation: 24848
public Class a
{
int x = 0;
private void startThread()
{
MyThread = new Thread(new Runnable()
{
public void run()
{
while(x<1000)
{
x++;
b.notifyEdittext(x);
sleep(100);
}
}
});
MyThread.start();
}
}
Class b extends Activity{
EditText ed;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ed =(EditText)findViewById(....);
}
public static void notifyEdittext(int counter){
if(ed!=null){
ed.setText(ed.getText()+counter);
}
}
}
Upvotes: 0
Reputation: 17622
IMO, you should be using Observer pattern, where class A
is Observer and class B
is Subject
Upvotes: 2