跨Activity调用模型类getter返回null 非Intent传值解决方案
问题根因
你当前代码拿不到值的核心原因有两个:
- 两个Activity中分别
new出来的UserName是完全独立的内存对象,不存在数据关联:你在MainActivity中实例化的对象仅在MainActivity的作用域内有效,跳转到MainActivity2时没有把这个对象传递过去,后者自己创建的新对象自然拿不到前者赋值的属性。 - MainActivity2中调用的是无参构造方法
new UserName(),这个构造方法没有对name、userId两个属性做任何赋值操作,对象创建后两个属性本身就是默认值null,调用getter返回null完全符合预期。
无Intent.putExtra的实现方案
以下两种方案都是Android开发中同进程跨页面共享对象的常用实现,按需选择即可:
- 方案1:单例模式存储全局实例
修改UserName类,增加静态单例持有逻辑,保证全应用范围内可以访问到同一个实例:
public class UserName { String name,userId; // 持有全局唯一实例 private static UserName instance; public UserName(String name, String userId) { this.name = name; this.userId = userId; } public UserName() {} // 对外提供获取实例的方法 public static UserName getInstance() { return instance; } // 对外提供设置实例的方法 public static void setInstance(UserName target) { instance = target; } public String getName() { return name; } public String getUserId() { return userId; } }
修改MainActivity的初始化逻辑,实例化完成后把对象存入单例:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); UserName userName=new UserName("UnknownPerson","7dfgdufdbid_bjd"); // 存入全局单例 UserName.setInstance(userName); Log.d("Test",userName.getName()+" "+userName.getUserId()); findViewById(R.id.button).setOnClickListener(v -> { startActivity(new Intent(this,MainActivity2.class)); }); }
修改MainActivity2的取值逻辑,不要自己新建对象,直接从单例取:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); // 直接取全局存储的实例 UserName userName=UserName.getInstance(); Log.d("Test",userName.getName()+" "+userName.getUserId()); }
注意:单例持有的对象在应用被系统后台回收时会被清空,仅适合存储轻量临时数据,不要存大对象避免内存泄漏。
- 方案2:自定义Application类存储
自定义全局Application类,用它的生命周期持有共享对象,稳定性比普通单例更高:
// 自定义Application类 public class App extends Application { private UserName userName; public UserName getUserName() { return userName; } public void setUserName(UserName userName) { this.userName = userName; } @Override public void onCreate() { super.onCreate(); } }
在AndroidManifest.xml的application标签下添加name属性,绑定自定义的Application类:
<application android:name=".App" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.MyApp"> <!-- 原有Activity声明保持不变 --> </application>
MainActivity中初始化完成后把对象存入Application:
UserName userName=new UserName("UnknownPerson","7dfgdufdbid_bjd"); ((App)getApplicationContext()).setUserName(userName);
MainActivity2中直接从Application取值即可:
UserName userName = ((App)getApplicationContext()).getUserName();
如果需要持久化存储数据(应用杀进程重启后依然能拿到),以上两种方案都不适用,需要改用SharedPreferences、本地数据库、文件存储等持久化方案。
内容的提问来源于stack exchange,提问作者nothing
相关产品推荐
相关产品推荐

