¿Cómo obtengo datos adicionales de intent en Android?


¿Cómo puedo enviar datos de una actividad (intent) a otra?

Uso este código para enviar datos:

Intent i=new Intent(context,SendMessage.class);
i.putExtra("id", user.getUserAccountId()+"");
i.putExtra("name", user.getUserFullName());
context.startActivity(i);
Author: Peter Mortensen, 2010-11-20

15 answers

Primero, obtenga la intent que ha iniciado su actividad utilizando el método getIntent():

Intent intent = getIntent();

Si sus datos adicionales se representan como cadenas, entonces puede usar el método intent.getStringExtra(String name). En su caso:

String id = intent.getStringExtra("id");
String name = intent.getStringExtra("name");
 1044
Author: Malcolm,
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
2012-09-05 15:18:56

En la actividad receptora

Bundle extras = getIntent().getExtras(); 
String userName;

if (extras != null) {
    userName = extras.getString("name");
    // and get whatever type user account id is
}
 172
Author: NickT,
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
2010-11-20 17:12:16
//  How to send value using intent from one class to another class
//  class A(which will send data)
    Intent theIntent = new Intent(this, B.class);
    theIntent.putExtra("name", john);
    startActivity(theIntent);
//  How to get these values in another class
//  Class B
    Intent i= getIntent();
    i.getStringExtra("name");
//  if you log here i than you will get the value of i i.e. john
 29
Author: Sumit Sharma,
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-08-11 18:27:35

Add-up

Conjunto de datos

String value = "Hello World!";
Intent intent = new Intent(getApplicationContext(), NewActivity.class);
intent.putExtra("sample_name", value);
startActivity(intent);

Obtener datos

String value;
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
    value = bundle.getString("sample_name");
}
 23
Author: phi,
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-08-24 07:26:06

En lugar de inicializar otra nueva Intent para recibir los datos, simplemente haga esto:

String id = getIntent().getStringExtra("id");
 16
Author: r_allela,
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-11-22 11:52:22

Si se usa en una FragmentActivity, pruebe esto:

La primera página extiende FragmentActivity

Intent Tabdetail = new Intent(getApplicationContext(), ReceivePage.class);
Tabdetail.putExtra("Marker", marker.getTitle().toString());
startActivity(Tabdetail);

En el fragmento, solo tienes que llamar getActivity() primero,

La segunda página se extiende Fragmento:

String receive = getActivity().getIntent().getExtras().getString("name");
 11
Author: Bundit Ng,
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-11-22 11:52:01

Si está tratando de obtener datos adicionales en fragmentos, puede intentar usar:

Coloque los datos usando:

Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER);

Obtener datos usando:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


  getArguments().getInt(ARG_SECTION_NUMBER);
  getArguments().getString(ARG_SECTION_STRING);
  getArguments().getBoolean(ARG_SECTION_BOOL);
  getArguments().getChar(ARG_SECTION_CHAR);
  getArguments().getByte(ARG_SECTION_DATA);

}
 6
Author: star18bit,
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-01-24 22:43:55

Puede obtener cualquier tipo de datan extra de intent , sin importar si se trata de un objeto o una picadura o de un dato anytype.

Bundle extra = getIntent().getExtras();
if (extra != null){
    String str1 = (String) extra.get("obj"); // get a object

    String str2 =  extra.getString("string"); //get a string
}
 2
Author: Hasib Akter,
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-05-29 19:02:57

Solo una sugerencia:

En lugar de usar "id" o "nombre" en su i.putExtra("id".....), sugeriría, cuando tenga sentido, usar los campos estándar actuales que se pueden usar con putExtra (), es decir, Intent.Algo extra.

Una lista completa se puede encontrar en Intención (Desarrolladores de Android).

 1
Author: eva,
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-11-22 12:15:54

Podemos hacerlo por medios simples:

En Primeractividad:

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("uid", uid.toString());
intent.putExtra("pwd", pwd.toString());
startActivity(intent);

En Secondactividad:

    try {
        Intent intent = getIntent();

        String uid = intent.getStringExtra("uid");
        String pwd = intent.getStringExtra("pwd");

    } catch (Exception e) {
        e.printStackTrace();
        Log.e("getStringExtra_EX", e + "");
    }
 1
Author: sam,
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-05-15 10:39:32

También puedes hacer esto
// poner valor en la intención

    Intent in = new Intent(MainActivity.this, Booked.class);
    in.putExtra("filter", "Booked");
    startActivity(in);

/ / obtener valor de intent

    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();
    String filter = bundle.getString("filter");
 0
Author: Savita Sharma,
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-04-21 11:22:19

Obtener Diferentes Tipos de Extra de Intent

Para acceder a los datos de Intent debes saber dos cosas.

  • CLAVE
  • Tipo de datos de sus datos.

Hay diferentes métodos en la clase Intent para extraer diferentes tipos de datos. Se ve así

GetIntent ().XXXX (CLAVE) o intent.XXX (CLAVE);


Así que si conoces el tipo de datos de tu varibale que estableces en otherActivity puedes usar el método respectivo.

Ejemplo para recuperar la cadena de tu Actividad desde Intent

String profileName = getIntent().getStringExtra("SomeKey");

Lista de diferentes variantes de métodos para diferentes tipos de datos

Puede ver la lista de métodos disponibles en la Documentación Oficial de Intent.

 0
Author: Rohit Singh,
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-09-20 12:53:22

Esto es para el adaptador, para la actividad solo necesita cambiar mContext para su nombre Activty y para fragment necesita cambiar mContext a getActivity()

 public static ArrayList<String> tags_array ;// static array list if you want to pass array data

      public void sendDataBundle(){
            tags_array = new ArrayList();
            tags_array.add("hashtag");//few array data
            tags_array.add("selling");
            tags_array.add("cityname");
            tags_array.add("more");
            tags_array.add("mobile");
            tags_array.add("android");
            tags_array.add("dress");
            Intent su = new Intent(mContext, ViewItemActivity.class);
            Bundle bun1 = new Bundle();
            bun1.putString("product_title","My Product Titile");
            bun1.putString("product_description", "My Product Discription");
            bun1.putString("category", "Product Category");
            bun1.putStringArrayList("hashtag", tags_array);//to pass array list 
            su.putExtras(bun1);
            mContext.startActivity(su);
        }
 0
Author: Android Geek,
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-02-03 05:20:20

Pase la intent con valor a la Primera Actividad:

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("uid", uid.toString());
intent.putExtra("pwd", pwd.toString());
startActivity(intent);

Recibir la intención de segunda Actividad; -

Inetent intent=getIntent();
String User=intent.getStringExtra("uid");
String Pass=intent.getStringExtra("pwd");

Generalmente usamos dos métodos en intent para enviar el valor y para obtener el valor. Para enviar el valor usaremos intent.putExtra("Key",Value); y durante recibir intent en otra actividad usaremos intent.getStringExtra("Key"); , Aquí key puede ser cualquier palabra clave para identificar el valor significa que qué valor está compartiendo. Espero que funcione para usted.

 0
Author: Pradeep Sheoran,
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-08-18 08:19:55

Acabo de publicar una respuesta aquí que cubre este tema con un poco más de detalle, incluyendo algunas alternativas.

Utiliza Vapor API, un nuevo framework Android inspirado en jQuery que escribí para simplificar Android dev. Echa un vistazo al ejemplo en esa respuesta para saber cómo puedes pasar datos fácilmente entre actividades.

También demuestra VaporIntent, que le permite encadenar llamadas a métodos y utilizar el método overloaded .put(...):

$.Intent().put("data", "myData").put("more", 568)...

Puede pasar datos fácilmente alrededor de toda su aplicación usando API de vapor , así que espero que sea útil para usted y otros durante el desarrollo de la aplicación.

 -2
Author: Darius,
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-05-23 12:02:50