Using an adapter from another class / activity

How can I use an ArrayAdapter from another action? I tried to do the following in MyListActivity.onCreate ():

setListAdapter(SomeOtherActivity.myAdapter); 

where myAdapter is defined and initialized to SomeOtherActivity. However, I get an empty list, although I checked that SomeOtherActivity.myAdapter is completely populated with a call:

 SomeOtherActivity.myAdapter.getCount(); 

If I define and initialize my own adapter in MyListActivity using setListAdapter (myLocalAdapter), it works. As soon as I switch it to setListAdapter (SomeOtherActivity.myAdapter), I get an empty list. I debugged it and found that the getView () adapter is not even being called.

Help me please? Thanks.

In MainActivity.onCreate ()

 listIsDone = false; myList = new ArrayList<ItemInfo>(); init = new Runnable() { public void run() { myList = generate(); // generate the list, takes a while Collections.sort(myList, new CustomComparator()); // sorts the list myAdapter = new MyInfoAdapter(MainActivity.this, R.layout.row, myList); synchronized(this) { listIsDone = true; notifyAll(); } } }; Thread thread = new Thread(null, init, "Background"); thread.start; 

In my SubActivity.onCreate ()

 setListAdapter(MainActivity.myAdapter); doStuff = new Runnable() { public void run() { synchronized(MainActivity.init) { if (!MainActivity.getListDone()) { try { MainActivity.init.wait(); // wait for list/adapter to be initialized } catch (InterruptedException e) { } } } } }; Thread thread = new Thread(null, doStuff, "Background"); thread.start(); 

I notice that I cannot run myAdapter.notifyDataSetChanged () in the Runnable thread (I get a runtime error), but I can do it in runnable if I run it with runOnUiThread (); I assume that all method calls for the adapter should be made in the same user interface thread?

+4
source share
1 answer

Please check the availability of myAdapter in currentActivity. It seems you are using the adapter before initializing it.

@share code .. for the right solution

0
source

Source: https://habr.com/ru/post/1390384/


All Articles