-2

I was trying to setText for two views while parsing JSON from server but it gives me error when run. Here is my code:

protected void onPostExecute(String result) {
            super.onPostExecute(result);
            textView.setText(result);
            newTextView.setText(result);
        }

Here is my error:

FATAL EXCEPTION: main
    java.lang.NullPointerException
    at com.musicianfocus.ben.wordedfm.MainActivity$JSONTask.onPostExecute(MainActivity.java:254)
    at com.musicianfocus.ben.wordedfm.MainActivity$JSONTask.onPostExecute(MainActivity.java:208)
    at android.os.AsyncTask.finish(AsyncTask.java:631)
    at android.os.AsyncTask.access$600(AsyncTask.java:177)
    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4745)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    at dalvik.system.NativeStart.main(Native Method)
    06
Omal Perera
  • 2,971
  • 3
  • 21
  • 26
Benfight
  • 73
  • 10

1 Answers1

0

It is bad practice to access views from an AsyncTask. Thing is, by the time that AsyncTask is finished, your activity might be dead and you would try to access inexisting views. Instead, I would suggest that you use a library called EventBus from here: https://github.com/greenrobot/EventBus

The idea is the following: You post an event in onPostExecute with the correct values to set. Then you catch that event in your activity or fragment and update your views from there. This is an architecturally much better solution.

Robert K.
  • 1,043
  • 1
  • 8
  • 20
  • OnPostExecute runs on the UI thread, though. Even if you used event bus, the view would still be null when the Activity is gone – OneCricketeer Jun 04 '17 at 23:25
  • That is true. But in case of the Eventbus, you will not receive the event in your activity. Consequently, you can not have this error at all. – Robert K. Jun 05 '17 at 08:34