-1

I get a error of NetworkOnMainThreadException in the line of AVObject brandObj = query.getFirst(); After did some searches about the error, I think I should use something like Asynctask. But couldn't figure out how to do it.

AVObject is same as ParseObject

public class Product {
    Product(AVObject object) {
        try {
            AVObject brandObj = query.getFirst(); // this one is making network request
        } catch (AVException e) {
            e.printStackTrace();
        }
    }
}

Should I extends AsyncTask<AVObject, Void, AVObject>

Then

@Override
protected AVObject doInBackground(AVObject... objects) {
    return null;
} 

But not sure what should I write in doInBackground

Any suggestions?

Pak Ho Cheung
  • 1,382
  • 6
  • 22
  • 52

2 Answers2

1

NetworkOnMainThreadException is thrown when an application attempts to perform a networking operation on its main thread. This is only thrown for applications targeting the Honeycomb SDK or higher.

You cannot perform any networking on your main thread because it may block the UI. Hence, you should do everything in a separate thread.

AsyncTask is one of the easier solutions. Setup your AsyncTask (follow some tutorials/guides) and put your networking code into doInBackground() method, which runs on a separate thread.

Sergey Emeliyanov
  • 5,158
  • 6
  • 29
  • 52
1

Ideally, an object's constructor does not perform disk I/O or network I/O. In your case, it does.

So, every piece of code that is calling new Product(...) needs to be put into a background thread (plain thread, RxJava chain, JobIntentService, AsyncTask, etc.). Product itself would not change.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491