开发者

Android - How to pass HashMap<String,String> between activities?

How to pass the detail HashMap to another Activity?

HashMap<String,String> detail = new HashMap<String, String>();
detail.add("name","paresh");
detail.add("surname","mayani");
detail.add("phone","开发者_StackOverflow社区99999");
......
......


This is pretty simple, All Collections objects implement Serializable (sp?) interface which means they can be passed as Extras inside Intent

Use putExtra(String key, Serializable obj) to insert the HashMap and on the other Activity use getIntent().getSerializableExtra(String key), You will need to Cast the return value as a HashMap though.


Solution:

Sender Activity:

HashMap<String, String> hashMap= adapter.getItem(position);
Intent intent = new Intent(SourceActivity.this, DestinationActivity.class);
intent.putExtra("hashMap", hashMap);
startActivity(intent);

Receiver Activity:

Intent intent = getIntent();    
HashMap<String, String> hashMap = (HashMap<String, String>) intent.getSerializableExtra("hashMap");


i used this to pass my HashMap

startActivity(new Intent(currentClass.this,toOpenClass.class).putExtra("hashMapKey", HashMapVariable));

and on the receiving activity write

HashMap<String,String> hm = (HashMap<String,String>) getIntent().getExtras().get("hashMapKey");

cuz i know my hashmap contains string as value.


An alternative is if the information is something that might be considered "global" to the application, to then use the Application class. You simply extend it and then define your custom class in your manifest using the <application> tag. Use this sparingly, though. The urge to abuse it is high.


Here I am showing sample code for your reference. I just tried this code, it works fine for me. Check this :

MainActivity :

    final HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
    hashMap.put(1, "Hi");

    button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub              

            Intent intent = new Intent(MainActivity.this, SecondActivity.class);
            intent.putExtra("h", hashMap);
            startActivity(intent);

        }
    });

SecondActivity :

Toast.makeText(SecondActivity.this,"Hi " +  getIntent().getSerializableExtra("h").toString(),Toast.LENGTH_SHORT).show();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜