Java – Use an adapter from another class/activity

Use an adapter from another class/activity… here is a solution to the problem.

Use an adapter from another class/activity

How do I use the ArrayAdapter in another activity? I tried doing the following in MyListActivity.onCreate():

setListAdapter(SomeOtherActivity.myAdapter);

where myAdapter is defined and initialized in SomeOtherActivity. However, I get an empty list, even though I verify by calling SomeOtherActivity.myAdapter that it is fully populated:

SomeOtherActivity.myAdapter.getCount();

If I define and initialize my own adapter with setListAdapter(myLocalAdapter) in MyListActivity, it works. Once I switched it to setListAdapter(SomeOtherActivity.myAdapter), I got an empty list. I debugged it and found that the adapter’s getView() wasn’t even called.

Please help? Thank you.

在 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

noticed that I can’t run myAdapter.notifyDataSetChanged() in a Runnable thread( with a runtime error), but if I run it using runOnUiThread(), I can run it in runnable; I guess all method calls to the adapter need to be done in the same UI thread?

Solution

Check the accessibility of myAdapter in currentActivity.
You seem to have been using it before the adapter was initialized.

@share Code: to get the right solution

Related Problems and Solutions