我從兩個文本字段獲取用戶輸入並將它們存儲到哈希映射中。我已經檢查過這些值是否正確地插入散列映射中。他們是。一旦我嘗試使用Intent.putExtra傳遞它,我得到這個錯誤。將哈希映射傳遞給intent
Unable to start activity ComponentInfo{com.example.test.retrofit/com.example.test.retrofit.SearchActivity}: java.lang.ClassCastException: java.lang.String cannot be cast to java.util.HashMap
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3253)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.access$1100(ActivityThread.java:221)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7225)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.util.HashMap
at com.example.abdulhakim.retrofit.SearchActivity.onCreate(SearchActivity.java:42)
at android.app.Activity.performCreate(Activity.java:6876)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.access$1100(ActivityThread.java:221)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7225)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
這裏是我在MainActivity代碼:
Map<String, String> data = new HashMap<String,String>();
input1 = (EditText) findViewById(R.id.term);
input2 = (EditText) findViewById(R.id.column);
ImageView =(ImageButton)findViewById(R.id.search);
ImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SearchActivity.class);
k=input1.getText().toString();
t= input2.getText().toString();
data.put("key",k);
data.put("term",t);
Log.v("HashMapTest KEY", data.get("key"));
Log.v("HashMapTest TERM", data.get("term"));
intent.putExtra("hash",data);
startActivity(intent);
}
});
,這裏是我的第二個活動:
Intent intent = getIntent();
HashMap<String, String> data = (HashMap<String, String>)intent.getSerializableExtra("hash");
if (data.isEmpty()) {
Toast.makeText(getApplicationContext(), "nope! I didnt get the hashmap", Toast.LENGTH_LONG).show();
return;
}
嘗試'intent.putSerializableExtra(「hash」,data)' – IsuruKusumal