Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

java - 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 B I 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();
}
question from:https://stackoverflow.com/questions/65601761/pass-an-interface-between-activities-in-intent

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...