I have a layout with a TextView say mainTextView.
My activity file looks something like :
public class SecondActivity extends AppCompatActivity {
private static Integer i = 0;
private TextView tv = null;
@override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
tv = (TextView) findViewById(R.id.mainTextView);
new MyThread().execute();
}
private void notifyAChange () {
tv.setText(i.toString());
}
private class MyThread extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground (String... params) {
while (true) {
try {
i++;
Thread.sleep(1000);
notifyAChange();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
This returns a FATAL EXCEPTION on runtime. I know I can't touch a view from another Thread except the original one but in that case I am touching the view from the main thread so what is wrong ?