java 'Bundle.GetParcelable(字符串?)'已过时:'已过时'

cx6n0qe3  于 2022-10-30  发布在  Java
关注(0)|答案(1)|浏览(582)

所以我在使用VS 2022 Xamarin和android api 33时遇到了这个过时的问题(Triamisu),我不想使用[Obsolete]关键字,因为尽管该应用程序在我的三星S21上运行良好(Android V13)手机,最终所有对Android早期版本的支持都会下降,无论如何我都将不得不更新我所有的代码。所以为了赶在这之前,我把问题摆在那里。
目前我的代码是:

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

我将用户数据从一个活动移动到另一个活动,这样就不必再次调用数据库,我阅读了文章here,但实际上不知道需要什么语法来纠正代码。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。我很困惑。有人能给我解释一下吗?

holgip5t

holgip5t1#

快速浏览源代码(在线提供)可以确认您所遇到的问题:

/* @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;

相关问题