Skip to content Skip to sidebar Skip to footer

How To Send Data From List Adapter To Activity In Android?

I have a custom list adapter I would like to pass values from this list adapter to an activity where I set the adapter. This is my Adapter code. public class RoleList extends Array

Solution 1:

Your Activity :

publicclassMainActivityextendsAppCompatActivityimplementsYourCustomAdapter.MyActionCallback {

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // or something like thatListViewlistView= findViewById(R.id.my_list_view);
    listView.setAdapter(newYourCustomAdapter(this));
}



@OverridepublicvoidonActionPerformed(int position) {
    //do here something with your data

}

Your adapter :

publicclassYourCustomAdapterextendsBaseAdapter {

publicYourCustomAdapter(
        MyActionCallback actionCallback) {
    mActionCallback = actionCallback;
}

private MyActionCallback mActionCallback;

@OverridepublicintgetCount() {
    return0;
}

@Overridepublic Object getItem(int position) {
    returnnull;
}

@OverridepubliclonggetItemId(int position) {
    return0;
}

@Overridepublic View getView(finalint position, View convertView, ViewGroup parent) {
    // your case specific code// don't forget to implement view re-using properly,// don't inflate view each time
    delete.setOnClickListener(newView.OnClickListener() {
        @OverridepublicvoidonClick(View v)
        {
            name.remove(position);
            username.remove(position);
            password.remove(position);
            role.remove(position);
            //pass position of deleted object or any other thing you want
            mActionCallback.onActionPerformed(position);
            notifyDataSetChanged();
        }
    });
    returnnull;
}

publicinterfaceMyActionCallback{
    voidonActionPerformed(int position);
}

Also you can use the Event Bus, Otto for example, but I think for your case just a custom callback will be enough. It depends.

Post a Comment for "How To Send Data From List Adapter To Activity In Android?"