I have a Thread nested in the main activity:
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
new Thread(new Runnable(){
public void run() {
int myInt = 1;
// Code below works fine and shows me myInt
TextView textView = (TextView) findViewById(R.id.text_view);
textView.setText(myInt);
}
}).start();
// Code below doesn't work at all
TextView textView = (TextView) findViewById(R.id.text_view);
textView.setText(myInt);
}
I’m not sure if this structure is correct at all. How should I pass myInt variable to the MainActivity so it will become recognizable and operable outside the Thread?
You would first want a global variable for the integer that is already set before you try setting the textview that’s outside of your thread (on the main thread). It needs to be set beforehand because the new thread you start will simply be started and move along to the next lines of code, so myInt won’t have been set yet.
Then, use the predetermined global integer value for the textview on the main thread, at least initially. If you would like to change it from within the thread you started, then create a method in your class like setIntValue() which will pass in the integer from the thread and set the global variable to that value. I can update with code examples later if you’d like.
UPDATE: example code
Note: If you only wish to be able to reset the textview, as opposed to having a global, operable variable, I would suggest changing the method to just pass in the new integer and set the textview, rather than storing a global variable, like this:
If you do the above, make sure when you call the method from within the thread, call it on the UI thread like so:
runOnUiThread(new Runnable()){
public void run(){
//update UI elements
}
}