如何在android中的活动之间传递集合

时间:2014-04-11 05:58:32

标签: java android android-intent

我想做什么 ::

  • 我正在尝试将一个集合从一个活动传递到另一个活动,并在日志
  • 中显示收到的集合
  • 我知道这可以使用意图实现,所以我使用它们

我无法做什么 ::

  • 如何在hashmap中接收Screen1.java将其显示在日志中

MainActivity.java

public class MainActivity extends Activity implements OnClickListener{

    HashMap<String, String> objColl;
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        objColl=new HashMap<String, String>();
        objColl.put("1", "USA");
        objColl.put("2", "Canada");
        objColl.put("3", "Africa");
        objColl.put("4", "England");

        btn=(Button) findViewById(R.id.button1);

        btn.setOnClickListener(this);

    }

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

        switch(v.getId())
        {
        case R.id.button1:
            Intent intent=new Intent(MainActivity.this,Screen1.class);
            intent.putExtra("key1", objColl);
            startActivity(intent);
            break;
        }   
    }
}

Screen1.java

public class Screen1 extends Activity {

    HashMap<String, String> objColl;
    TextView txtVw;
    String res;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        txtVw=(TextView) findViewById(R.id.textView1);
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();

    }
}

日志 ::

3 个答案:

答案 0 :(得分:3)

发件人活动:

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

接收者活动:

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

答案 1 :(得分:1)

获取Extras你需要使用Bundle

Intent mIntent = getIntent();
        if(mIntent != null){
            Bundle mBudle = mIntent.getExtras();
            HashMap<String, String> mMap = (HashMap<String, String>) mBudle.get("key1");
        }

答案 2 :(得分:0)

使用bundle -

将集合传递给intent
Bundle extras = new Bundle();
extras.putSerializable("HashMap",Hash_Map);
intent.putExtras(extras);

&安培;在其他活动中 -

Bundle bundle = this.getIntent().getExtras();
 if(bundle!=null){
   Hash_Map= bundle.getSerializable("HashMap");