[英]Android passing JsonArray from one intent to another
已經嘗試了一段時間了。 我正在嘗試將 JsonArray 從一個意圖傳遞到另一個意圖。 這是我的代碼。
Intent intent = new Intent(this, DownloadService.class);
Bundle bundle = new Bundle();
JSonArrayParser jSonArrayParser = new JSonArrayParser(dealTypeList);
bundle.putParcelable("jsonArray", jSonArrayParser);
intent.putExtra("deals_list", bundle);
this.startService(intent);
JSonArrayParser 實現 Parcelable。
在將 JSonArrayParser 傳遞給 Bundle 之前,我已經檢查過是否按預期使用 Jsonarray 填充了 JSonArrayParser。
問題是當我以另一個意圖讀出它時。 我為 JsonArray 返回了 null。
這是我到目前為止所擁有的。
if(intent.hasExtra("jsonArray"))
{
JSonArrayParser jSonArrayParser = null;
Bundle bundle = intent.getParcelableExtra("jsonArray");
if (bundle != null) {
jSonArrayParser = bundle.getParcelable("deals_list");
String jsonMyObject = bundle.getString("deals_list");
jSonArrayParser = intent.getParcelableExtra("deals_list");
if(jSonArrayParser != null)
{
JSONArray jsonArray = jSonArrayParser.getJsonArray();
String ssad = "";
}
}
}
我嘗試了很多不同的變體來嘗試讀取值,但似乎 JSONArray 始終是 null。
在發帖之前已經在 inte.net 上搜索過了。 如果有人可以提供幫助,那就太好了。
提前致謝。
編輯:
我試過將 JSonArray 作為字符串傳遞如下,但這似乎根本沒有啟動意圖。
Intent intent = new Intent(your_activity.this, new_activity.class);
intent.putExtra("jsonArray", dealTypeList.toString());
startActivity(intent);
我這樣工作。 請您以這種方式檢查。
Bundle extras = getIntent().getExtras();
userName = extras.getString("user_name");
Intent logIntent = new Intent(HomePage.this, LogIn.class);
startActivity(logIntent);
檢索其他類中的數據。
private Bundle extraslogin = getIntent().getExtras();
userName = extraslogin.getString("user_name");
並且您還檢查了數據分配部分。我認為,這可能對您有所幫助。 您嘗試在“ onCreat”方法內檢索其他類的數據。 直接像上面的代碼。
我認為您使用了錯誤的鍵...請檢查..
您正在使用鍵“ deal_list”將捆綁包放入Intent。 並且在捆綁中,您有帶有鍵“ jsonArray”的jsonarray。
因此,首先您應該檢查鍵“ deal_list”,因為您將其(捆綁)放在了Intent中。 然后從包中獲取鍵“ jsonArray”。
一次檢查您的代碼。 捆綁包bundle = intent.getParcelableExtra(“ jsonArray”);
在這里,您做錯了,直接從Intent中獲取jsonArray,而不是先從intent中獲取Bundle,然后再從jsonArray中獲取。
檢查此鏈接,了解我們如何在Intent中使用bundle。 通過捆綁包傳遞值並在另一個活動中獲取其值
您可以使用簡單的putExtra傳遞json數組,例如:
Intent intent = new Intent(your_activity.this, new_activity.class);
intent.putExtra("jsonArray", mJsonArray.toString());
startActivity(intent);
其中, mJsonArray
是您的json數組。
現在,在您的new_activity.java中 :
Intent intent = getIntent();
String jsonArray = intent.getStringExtra("jsonArray");
try {
JSONArray array = new JSONArray(jsonArray);
System.out.println(array.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
我已經嘗試過了,但出於某種原因它沒有啟動其他活動。 僅當我刪除 putExtra 時才開始。 這就是我嘗試 Parcable 方式的原因
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.