我正在尝试将自定义对象从一个 Activity 传递到另一个 Activity 。所以我使用了下面的代码:
在welcomeActivity.java中:(实现了可序列化,QuestionRepository.java也实现了可序列化)
Intent intent = new Intent(WelcomeActivity.this,QuestionActivity.class);
intent.putExtra("category", 1);
intent.putExtra("qustionRepository", questionRepository);
startActivity(intent);
在questionActivity.java中:
questionRepository = (QuestionRepository) getIntent().getSerializableExtra("questionRepository");
在运行时,我收到此错误:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.loginactivity, PID: 16608
java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.example.user.repository.QuestionRepository)
at android.os.Parcel.writeSerializable(Parcel.java:1316)
at android.os.Parcel.writeValue(Parcel.java:1264)
at
...
Caused by: java.io.NotSerializableException: com.example.user.repository.BaseRepository_Impl$4
at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1364)
at
...
BaseRepository 是一个扩展了可序列化的接口(interface)。
@Dao
public interface BaseRepository extends Serializable {
@Query("SELECT * FROM User")
List<User> getAllUserScores();
@Query("SELECT * FROM user where first_name LIKE :firstName AND last_name LIKE :lastName")
User findUserByName(String firstName, String lastName);
@Insert
void insertUser(User user);
@Delete
void deleteUser(User user);
@Insert
void insertQuestion(Question question);
@Delete
void deleteQuestion(Question question);
@Query("Select * from Question")
List<Question> getAllQuestions();
}
正如我从研究中发现的那样,实现可序列化足以在 Activity 之间传递对象,但显然我错过了一些东西。我哪里做错了?谢谢
最佳答案
implementing serializable is enough to pass objects between activites
是的,但是要实现Serialized
,Java 类在字段中保存的所有内容本身都必须是Serialized
。在本例中,您没有编写 Java 类 — 它是由 Room 为您生成的代码。
拥有BaseRepository
的RoomDatabase
应该是一个单例;然后,两个 Activity 都可以访问该单例以使用 BaseRepository
。
一般来说,通过 Intent
extras 传递任意对象是一种代码味道。 Android 必须为这些对象制作 2 个以上的副本,作为启动其他组件(在本例中为启动 Activity )的一部分,并且这些副本在操作系统进程之间传递。
关于在 Activity 之间传递对象时出现 java.io.NotSerializedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49601834/