所以我在使用 VS 2022 Xamarin 和 android api 33 (Triamisu) 時遇到了這個過時問題,我不想使用[Obsolete]關鍵字,因為盡管該應用程式在我的三星 S21 (Android v13) 手機上運行良好,但最終都支持早期版本android 將下降,無論如何我將不得不更新我的所有代碼。所以為了搶先一步,我把問題放在那里。
目前我的代碼是:
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。我很困惑。誰能幫我解決這個問題?
uj5u.com熱心網友回復:
快速查看源代碼(可在線獲得)可以確認您所遇到的情況:
/* @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;
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/528305.html
