Transfer data from one Activity to Another Activity Using Intents

后端 未结 8 1587
花落未央
花落未央 2020-11-29 06:36

I would like to be able to transfer data from one activity to another activity. How can this be done?

相关标签:
8条回答
  • 2020-11-29 07:25

    You just have to send extras while calling your intent

    like this:

    Intent intent = new Intent(getApplicationContext(), SecondActivity.class); intent.putExtra("Variable Name","Value you want to pass"); startActivity(intent);

    Now on the OnCreate method of your SecondActivity you can fetch the extras like this

    If the value u sent was in "long"

    long value = getIntent().getLongExtra("Variable Name which you sent as an extra", defaultValue(you can give it anything));

    If the value u sent was a "String"

    String value = getIntent().getStringExtra("Variable Name which you sent as an extra");

    If the value u sent was a "Boolean"

    Boolean value = getIntent().getStringExtra("Variable Name which you sent as an extra",defaultValue);

    0 讨论(0)
  • 2020-11-29 07:30

    When you passing data from one activity to another activity perform like this

    In Parent activity:

    startActivity(new Intent(presentActivity.this, NextActivity.class).putExtra("KEY_StringName",ValueData)); 
    

    or like shown below in Parent activity

    Intent intent  = new Intent(presentActivity.this,NextActivity.class);     
    intent.putExtra("KEY_StringName", name);   
    intent.putExtra("KEY_StringName1", name1);   
    startActivity(intent);
    

    In child Activity perform as shown below

    TextView tv = ((TextView)findViewById(R.id.textViewID))
    tv.setText(getIntent().getStringExtra("KEY_StringName"));
    

    or do like shown below in child Activity

    TextView tv = ((TextView)findViewById(R.id.textViewID));
    TextView tv1 = ((TextView)findViewById(R.id.textViewID1))
    
    /* Get values from Intent */
    Intent intent = getIntent();         
    String name  = intent.getStringExtra("KEY_StringName");
    String name1  = intent.getStringExtra("KEY_StringName1");
    
    tv.setText(name);
    tv.setText(name1);
    
    0 讨论(0)
提交回复
热议问题