I am building an Android app in Kotlin, which has a button on the main activity to "Add Players" opening another activity. In this "Add Player" activity, you can choose to manually add a player, which brings up a 3rd "popup" activity. The person enters the info, then hits add. On that click, I want to immediately create a new "Player" object and update the list view of active players on the main activity.
I read to use the adapter.notifyDataSetChanged()
, but the problem is, I can't find a way to get a reference to that adapter (ArrayAdapter) object. If this was Java, I would just make the adapter globally available, or public static, something like that. However, this is Kotlin where everything is confusing as heck for me. I can't make the adapter globally available because I can't initialize the adapter because the "context" parameter which everyone passes "this" doesn't work. I can't make any function changing it to public or static. I also can't lateinit the variable either because Kotlin is mad at me for some reason.
I spent like 2 hours trying to update a stupid ListView for my app. It is pretty disheartening when I try to practice making apps and get caught up in small stuff like this.
I'm sure I have a major misunderstanding, but if someone could point me in the right direction, that would be great!
Thank you very much guys,
JT
Do not make your adapter/View/ActivityContext global variable, otherwise, you will get a really big memory issue.
You should try to use Local BroadCast receiver. From Activity A which has Adapter, you can register a Local BroadCast receiver
in onCreate
to listen to any changing-adapter action. Here's the example:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("YourAdapaterChangeAction.");
LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
// check your action with if/else
//adapter.notify....
}
},intentFilter);
Afterward, you can just fire LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("YourAdapaterChangeAction"));
from any activity to update your adapter.
P/s: another option is to use startActivityForResult
.