简体   繁体   中英

Pass an interface between activities in intent

I have this situation: a Class A (that implements interface I), a Modal and a Class B (that implements interface I).

The Class A open the modal, and from the modal I go to class B. In class BI want to return to the Class A with the Modal updated (Not implemented yet).

I'm trying to pass an interface between the two activities but I recive this error (I already extends Serializable in Interface):

 Caused by: java.io.NotSerializableException: com.google.android.material.textview.MaterialTextView

Class A

@Override
public void showList() {
            Intent intent = new Intent(this, SelectMethod.class);
            intent.putExtra("iHome", this);
            startActivity(intent);
    }

Modal

 # Function when click button and go to the class B
 btn_select_method.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            iHome.showList();
        }
    });

Class B (SelectMethod)

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
     intent.getSerializableExtra("iHome");
}

Interface

public interface Ihome extends Serializable {
    void showList();
}

To a class be serializable all of this fields need to be serializable (can write/read keeping state), any class that extends View have fields that are not serializable like Contexts and Listeners, those are instances.

You should not try to pass the activity/views/fragments instances trough intents since it breaks android lifecycle behaviour.

Since you using a Activity with modal theme, you may use

startActivityForResult(intent, 25 /*any number */)

Then into SelectMethod instead of calling a method from the FirstActivity you setResult then finish

The result is read from FirstActivity into:

@Override public void onActivityResult

See more: https://developer.android.com/training/basics/intents/result#kotlin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM