Cómo usar putExtra () y getExtra () para datos de cadena


Puede alguien por favor decirme cómo usar exactamente getExtra() y putExtra() para la Intención. Realmente tengo una variable de cadena decir str, que almacena algunos datos de cadena. Ahora quiero enviar estos datos de una actividad a la otra actividad.

  Intent i = new Intent(FirstScreen.this, SecondScreen.class);   
  String keyIdentifer  = null;
  i.putExtra(strName, keyIdentifer );

Y luego en la segunda pantalla.java

 public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.table);
        TextView userName = (TextView)findViewById(R.id.userName);
        Bundle bundle = getIntent().getExtras();

        if(bundle.getString("strName")!= null)
        {
            //TODO here get the string stored in the string variable and do 
            // setText() on userName 
        }

    }

Sé que es una pregunta muy básica, pero desafortunadamente estoy atrapado aquí. Por favor, ayuda.

Gracias,

Editado: Aquí la cadena que estoy tratando de pasar de una pantalla a la otra es dinámico. Es decir, tengo un EditText donde obtengo una cadena de cualquier tipo de usuario. Luego con la ayuda de myEditText.getText().toString() . Estoy obteniendo el valor ingresado como una cadena, luego tengo que pasar estos datos.

Author: astuter, 2011-03-11

13 answers

Use esto para "poner" el archivo...

Intent i = new Intent(FirstScreen.this, SecondScreen.class);   
String strName = null;
i.putExtra("STRING_I_NEED", strName);

Entonces, para recuperar el valor intente algo como:

String newString;
if (savedInstanceState == null) {
    Bundle extras = getIntent().getExtras();
    if(extras == null) {
        newString= null;
    } else {
        newString= extras.getString("STRING_I_NEED");
    }
} else {
    newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
 361
Author: Will Tate,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-21 21:30:46

Primera Pantalla.java

text=(TextView)findViewById(R.id.tv1);
edit=(EditText)findViewById(R.id.edit);
button=(Button)findViewById(R.id.bt1);

button.setOnClickListener(new OnClickListener() {
    public void onClick(View arg0) {
        String s=edit.getText().toString();

        Intent ii=new Intent(MainActivity.this, newclass.class);
        ii.putExtra("name", s);
        startActivity(ii);
    }
});

Segunda Pantalla.java

public class newclass extends Activity
{
    private TextView Textv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.intent);
        Textv = (TextView)findViewById(R.id.tv2);
        Intent iin= getIntent();
        Bundle b = iin.getExtras();

        if(b!=null)
        {
            String j =(String) b.get("name");
            Textv.setText(j);
        }
    }
}
 61
Author: ReemaRazdan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-18 15:17:30

El Mejor Método...

SendingActivity

Intent intent = new Intent(SendingActivity.this, RecievingActivity.class);
intent.putExtra("keyName", value);  // pass your values and retrieve them in the other Activity using keyName
startActivity(intent);

RecievingActivity

 Bundle extras = intent.getExtras();
    if(extras != null)
    String data = extras.getString("keyName"); // retrieve the data using keyName 

/// el camino más corto para recibir datos..

String data = getIntent().getExtras().getString("keyName","defaultKey");

/ / Esto requiere api 12. //el segundo parámetro es opcional . Si KeyName es null, utilice defaultkey como datos.

 43
Author: Xar E Ahmer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-29 12:22:39

Esto es lo que he estado usando, con esperanza ayuda a alguien.. simple y afectivo.

Enviar datos

    intent = new Intent(getActivity(), CheckinActivity.class);
    intent.putExtra("mealID", meal.Meald);
    startActivity(intent);

Obtener datos

    int mealId;

    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();

    if(bundle != null){
        mealId = bundle.getInt("mealID");
    }

Salud!

 14
Author: Sindri Þór,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-15 22:33:48

Es muy fácil implementar intent en Android.. Te lleva pasar de una actividad a otra actividad, tenemos dos métodos putExtra(); y getExtra(); Ahora te estoy mostrando el ejemplo..

    Intent intent = new Intent(activity_registration.this, activity_Login.class);
                intent.putExtra("AnyKeyName", Email.getText().toString());  // pass your values and retrieve them in the other Activity using AnyKeyName
                        startActivity(intent);

Ahora tenemos que obtener el valor del parámetro AnyKeyName, el código mencionado a continuación ayudará a hacer esto

       String data = getIntent().getExtras().getString("AnyKeyName");
        textview.setText(data);

Podemos establecer fácilmente el valor de recepción desde Intent, donde sea que lo necesitemos.

 6
Author: عاقب انصاری,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-18 20:17:10

Un pequeño anexo: usted no tiene que crear su propio nombre para la clave, Android proporciona estos, f.ex. Intent.EXTRA_TEXT. Modificando la respuesta aceptada:

Intent i = new Intent(FirstScreen.this, SecondScreen.class);   
String strName = null;
i.putExtra(Intent.EXTRA_TEXT, strName);

Entonces, para recuperar el valor intente algo como:

String newString;
Bundle extras = getIntent().getExtras();
if(extras == null) {
    newString= null;
} else {
    newString= extras.getString(Intent.EXTRA_TEXT);
}
 5
Author: serv-inc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-21 11:14:19
Intent intent = new Intent(view.getContext(), ApplicationActivity.class);
                        intent.putExtra("int", intValue);
                        intent.putExtra("Serializable", object);
                        intent.putExtra("String", stringValue);
                        intent.putExtra("parcelable", parObject);
                        startActivity(intent);

ApplicationActivity

Intent intent = getIntent();
Bundle bundle = intent.getExtras();

if(bundle != null){
   int mealId = bundle.getInt("int");
   Object object = bundle.getSerializable("Serializable");
   String string = bundle.getString("String");
   T string = <T>bundle.getString("parcelable");
}
 4
Author: Samet öztoprak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-11 17:55:19

Más simple

Lado del remitente

Intent i = new Intent(SourceActiviti.this,TargetActivity.class);
i.putExtra("id","string data");
startActivity(i)

Lado receptor

Intent i = new Intent(SourceActiviti.this,TargetActivity.class);
String strData = i.getStringExtra("id");
 2
Author: David Untama,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-11 11:03:15

Función Put

etname=(EditText)findViewById(R.id.Name);
        tvname=(TextView)findViewById(R.id.tvName);

        b1= (ImageButton) findViewById(R.id.Submit);

        b1.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                String s=etname.getText().toString();

                Intent ii=new Intent(getApplicationContext(), MainActivity2.class);
                ii.putExtra("name", s);
                Toast.makeText(getApplicationContext(),"Page 222", Toast.LENGTH_LONG).show();
                startActivity(ii);
            }
        });



getfunction 

public class MainActivity2 extends Activity {
    TextView tvname;
    EditText etname;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_activity2);
        tvname = (TextView)findViewById(R.id.tvName);
        etname=(EditText)findViewById(R.id.Name);
        Intent iin= getIntent();
        Bundle b = iin.getExtras();

        if(b!=null)
        {

          String j2 =(String) b.get("name");

etname.setText(j2);
            Toast.makeText(getApplicationContext(),"ok",Toast.LENGTH_LONG).show();
        }
    }
 1
Author: Habeeb Rahman kalathil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-08 09:34:17

Datos push

import android.content.Intent;

    ...

    Intent intent = 
        new Intent( 
            this, 
            MyActivity.class );
    intent.putExtra( "paramName", "paramValue" );
    startActivity( intent );

El código anterior podría estar dentro del main activity. "MyActivity.class" es el segundo Activity que queremos lanzar; debe incluirse explícitamente en su archivo AndroidManifest.xml.

<activity android:name=".MyActivity" />

Pull Data

import android.os.Bundle;

    ...

    Bundle extras = getIntent().getExtras();
    if (extras != null)
    {
        String myParam = extras.getString("paramName");
    }
    else
    {
        //..oops!
    }

En este ejemplo, el código anterior estaría dentro de su archivo MyActivity.java.

Gotchas

Este método solo puede pasar strings. Así que digamos que necesita pasar un ArrayList a su ListActivity; una posible solución es pasar un cadena separada por comas y luego divídala en el otro lado.

Soluciones alternativas

Use SharedPreferences

 1
Author: Habeeb Rahman kalathil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-17 13:28:10

Simple, En la primera Actividad -

    EditText name= (EditText) findViewById(R.id.editTextName);
    Button button= (Button) findViewById(R.id.buttonGo);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(MainActivity.this,Main2Activity.class);
            i.putExtra("name",name.getText().toString());
           startActivity(i);
          }
    });

En la segunda Actividad-

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    TextView t = (TextView) findViewById(R.id.textView);
    Bundle bundle=getIntent().getExtras();
    String s=bundle.getString("name");
    t.setText(s);
}

Puede agregar condiciones if/else si lo desea.

 1
Author: Srinivas Nallapu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-14 11:16:24

Poner cadena primero

Intent secondIntent = new Intent(this, typeof(SecondActivity));
            secondIntent.PutExtra("message", "Greetings from MainActivity");

Recuperarlo después de eso

var message = this.Intent.GetStringExtra("message");

Eso Es Todo;)

 0
Author: shyam_,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-27 13:53:22

Android ha introducido nuevos métodos en la clase Intent .

  • Use hasExtra() para verificar si intent tiene datos en clave.
  • Ahora puedes usar getStringExtra() directamente.

Datos de paso

intent.putExtra(USER_NAME, "user");

Obtener Datos

String userName;
if (getIntent().hasExtra(USER_NAME)) {
    userName = getIntent().getStringExtra(USER_NAME);
}

Siempre pongo las claves en constantes para las mejores prácticas (para evitar errores manuales)

public interface PutExtraConstants {
    String USER_NAME = "USER_NAME";
}
 0
Author: Khemraj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-11 12:54:54