'Bundle.GetParcelable(string?)'已过时:'deprecated'



所以我在使用VS 2022 Xamarin和安卓api 33(Triamisu(时遇到了这个过时问题,我不想使用[Obsolete]关键字,因为尽管该应用程序在我的三星S21(安卓v13(手机上运行良好,但最终对安卓早期版本的所有支持都会下降,无论如何我都必须更新所有代码。因此,为了赶在前面,我提出了这个问题。

目前我的代码是:

User MyUser = new User("", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");
MyUser = bundlee.GetParcelable("MyUser") as User;

我将用户数据从一个活动移动到另一个活动,这样我就不必再调用数据库了,希望能节省时间。我读了这里的文章,真的不知道我需要什么语法来纠正代码。User是我的代码中定义的一个类,我用用户的数据填充该类的一个实例。我将数据从一个活动移动到另一个活动,如下所示:

Intent intent = new Intent(this, typeof(Menu));
Bundle bundlee = new Bundle();
bundlee.PutParcelable("MyUser", MyUser); // Persist user class to next activity
intent.PutExtra("TheBundle", bundlee);
StartActivity(intent);

现在显然情况正在发生变化,我不知道如何使我的代码适应这种变化。没有太多信息,因为这是最近的一次更改,我在这里阅读了android开发者文档,但没有太大帮助。在这种情况下,我使用什么class clazz?我创建了在c#中传递的类,所以它不是java。我很困惑。有人能帮我清理一下吗?

快速查看源代码(在线提供(可以确认您正在经历的情况:

/* @deprecated Use the type-safer {@link #getParcelable(String, Class)} starting from Android
*      {@link Build.VERSION_CODES#TIRAMISU}.
*/
@Deprecated
@Nullable
public <T extends Parcelable> T getParcelable(@Nullable String key) {
//Implementation here
}

正如你所看到的,评论建议你使用另一种(类型更安全(方法:

/**
* Returns the value associated with the given key or {@code null} if:
* <ul>
*     <li>No mapping of the desired type exists for the given key.
*     <li>A {@code null} value is explicitly associated with the key.
*     <li>The object is not of type {@code clazz}.
* </ul>
*
* <p><b>Note: </b> if the expected value is not a class provided by the Android platform,
* you must call {@link #setClassLoader(ClassLoader)} with the proper {@link ClassLoader} first.
* Otherwise, this method might throw an exception or return {@code null}.
*
* @param key a String, or {@code null}
* @param clazz The type of the object expected
* @return a Parcelable value, or {@code null}
*/
@SuppressWarnings("unchecked")
@Nullable
public <T> T getParcelable(@Nullable String key, @NonNull Class<T> clazz) {
// The reason for not using <T extends Parcelable> is because the caller could provide a
// super class to restrict the children that doesn't implement Parcelable itself while the
// children do, more details at b/210800751 (same reasoning applies here).
return get(key, clazz);
}

新方法甚至有一条注释,说明您为什么要使用它。

特别注意:

  • @param-clazz所需对象的类型

所以,为了回答你的问题,看起来你应该这样做来获得对象:

User MyUser = new User("", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");
MyUser = bundlee.GetParcelable("MyUser", Java.Lang.Class.FromType(typeof(User))) as User;

或者:

MyUser = bundlee.GetParcelable("MyUser", Java.Lang.Class.FromType(MyUser.GetType())) as User;

最新更新