Reputation: 109
I know that this is most likely going to be marked a duplicate, but this is extremely frustrating me. I cannot, for the life of me, figure out a way to modify a textview from an AsyncTask. This is my function that is in the MainActivity class:
public void updateTextView(String data){
TextView textview = (TextView)findViewById(R.id.TextView1);
textview.setText(data);
}
and then in my AsyncTask i have
@Override
protected void onPostExecute(String result) {
MainActivity ma = new MainActivity();
ma.updateTextView(result);
}
However, after running this code and any modifications that involve attempting to modify the TextView from the AsyncTask, I get:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
However when calling the same exact function from the main thread, it runs fine.
Any help would be greatly appreciated.
Upvotes: 0
Views: 1317
Reputation: 36
you connot make a new object from an activity and work with it. try to get a reference to the activity
add this code to your AsyncTask class
MainActivity activity;
public void setContext(MainActivity activity){
this.activity = activity;
}
also edit this
@Override
protected void onPostExecute(String result) {
activity.updateTextView(result);
}
call this method when you create your AsyncTask object in your activity
//at is the object you created from your AsyncTask Class
at.setContext(this);
Upvotes: 2