0

Normally I do this:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //initialize variables, set values from argument bundle, etc
    List<SomeObject> list = someIntenseDataLoadingProcess();
    adapter = new Adapter(list);
}

@Nullable
@Override
public void onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.some_layout, container, false);
    recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
    recyclerView.setLayoutManager(getLinearLayoutManager());
    recyclerView.setAdapter(adapter);
    return view;
}

(I'm going from memory here but that should capture the gist of it).

However if I wrap the list/adapter initialization in a new Thread call, sometimes the result is empty by the time the view is created, or it throws errors in some cases depending on what's going on.

Do I just have the order wrong or something? Where should I be applying the thread?

KaliMa
  • 1,970
  • 6
  • 26
  • 51
  • Only wrap the someIntenseLoading in thread, and at the end of it recyclerview.setAdapter(new Adapter(list)) – X3Btel Nov 15 '16 at 21:00
  • @X3Btel Can you be more explicit, what do you mean exactly? Just wrapping it in a thread doesn't solve the problem – KaliMa Nov 15 '16 at 21:09
  • Its best to initialize your views in your case recycler view when the activity start, then start your asynctask/thread and when its finished you update the view with the result- in your case recyclerView.setAdapter – X3Btel Nov 15 '16 at 21:14

2 Answers2

0

You can use AsyncTask to do work in background and then execute code on the UI thread:

final List<SomeObject> list;
        new AsyncTask<Void,Void,Void>(){
            @Override
            protected Void doInBackground(Void... voids) {
            list[0] = someIntenseDataLoadingProcess();
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                recyclerView.setAdapter(new Adapter(list[0]));
            }
        };
X3Btel
  • 1,408
  • 1
  • 13
  • 21
  • Problem with asynctask is when you rotate the screen in the middle of it – KaliMa Nov 15 '16 at 22:00
  • @KaliMa http://stackoverflow.com/a/16305144/4810277 or the not so optimal variant to stop the task onPause and start it start it anew in onResume – X3Btel Nov 15 '16 at 22:26
0

Do I just have the order wrong or something?

You call the someIntenseDataLoadingProcess() from the onCreate() method and that's a bad practice as it blocks the UI Thread. Any method that runs in the UI thread should do as little work as possible.

Loaders are the way to go as they provide asynchronous loading of data.

Have a look at the Loaders guides.

You may find this answer useful.

Community
  • 1
  • 1
kws
  • 926
  • 7
  • 11