Cómo administrar 'startActivityForResult' en Android?
En mi actividad, estoy llamando a una segunda actividad de la actividad principal por startActivityForResult
. En mi segunda actividad hay algunos métodos que terminan esta actividad (tal vez sin resultado), sin embargo, solo uno de ellos devuelve un resultado.
Por ejemplo, desde la actividad principal llamo a una segunda. En esta actividad estoy comprobando algunas características del teléfono, como tiene una cámara. Si no tiene entonces voy a cerrar esta actividad. Además, durante la preparación de MediaRecorder
o MediaPlayer
si ocurre un problema, entonces Cerraré esta actividad.
Si su dispositivo tiene una cámara y la grabación se realiza por completo, luego de grabar un video si un usuario hace clic en el botón hecho, enviaré el resultado (dirección del video grabado) a la actividad principal.
¿Cómo puedo comprobar el resultado de la actividad principal?
9 answers
Desde su FirstActivity
llame al SecondActivity
usando el método startActivityForResult()
Por ejemplo:
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);
En su SecondActivity
establezca los datos que desea devolver a FirstActivity
. Si no quieres regresar, no establezcas ninguna.
Por ejemplo: En SecondActivity si desea devolver datos:
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();
Si no desea devolver datos:
Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();
Ahora en su clase FirstActivity escriba el siguiente código para el método onActivityResult()
.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("result");
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}//onActivityResult
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-12 12:29:59
Cómo comprobar el resultado de la actividad principal?
Necesitas anular Activity.onActivityResult()
a continuación, compruebe sus parámetros:
-
requestCode
identifica qué aplicación devolvió estos resultados. Esto es definido por usted cuando llamastartActivityForResult()
. -
resultCode
le informa si esta aplicación tuvo éxito, falló o algo diferente -
data
contiene cualquier información devuelta por esta aplicación. Esto puede sernull
.
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-05-13 05:03:27
Complementando la respuesta de @Nishant, la mejor manera de devolver el resultado de la actividad es:
Intent returnIntent = getIntent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();
Estaba teniendo problemas con
new Intent();
Entonces descubrí que la forma correcta es usar
getIntent();
Para obtener la intent actual
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-05-26 20:40:47
Ejemplo
Para ver todo el proceso en contexto, aquí hay una respuesta suplementaria. Ver mi respuesta más completa para más explicación.
MainActivity.java
public class MainActivity extends AppCompatActivity {
// Add a different request code for every activity you are starting from here
private static final int SECOND_ACTIVITY_REQUEST_CODE = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// "Go to Second Activity" button click
public void onButtonClick(View view) {
// Start the SecondActivity
Intent intent = new Intent(this, SecondActivity.class);
startActivityForResult(intent, SECOND_ACTIVITY_REQUEST_CODE);
}
// This method is called when the second activity finishes
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check that it is the SecondActivity with an OK result
if (requestCode == SECOND_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) { // Activity.RESULT_OK
// get String data from Intent
String returnString = data.getStringExtra("keyName");
// set text view with string
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(returnString);
}
}
}
}
Segunda actividad.java
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
// "Send text back" button click
public void onButtonClick(View view) {
// get the text from the EditText
EditText editText = (EditText) findViewById(R.id.editText);
String stringToPassBack = editText.getText().toString();
// put the String to pass back into an Intent and close this activity
Intent intent = new Intent();
intent.putExtra("keyName", stringToPassBack);
setResult(RESULT_OK, intent);
finish();
}
}
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-01-17 17:50:33
Si desea actualizar la interfaz de usuario con el resultado de la actividad, no puede usar this.runOnUiThread(new Runnable() {}
Al hacer esto, la interfaz de usuario no se actualizará con un nuevo valor. En su lugar, puedes hacer esto:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) {
return;
}
global_lat = data.getDoubleExtra("LATITUDE", 0);
global_lng = data.getDoubleExtra("LONGITUDE", 0);
new_latlng = true;
}
@Override
protected void onResume() {
super.onResume();
if(new_latlng)
{
PhysicalTagProperties.this.setLocation(global_lat, global_lng);
new_latlng=false;
}
}
Esto parece tonto, pero funciona bastante bien.
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-03-08 13:54:56
Para aquellos que tienen problemas con código de solicitud incorrecto en onActivityResult
Si está llamando a startActivityForResult()
desde su Fragment
, el Código de solicitud es cambiado por la Actividad que posee el Fragmento.
Si desea obtener el código de resultado correcto en su actividad, intente esto:
Cambio:
startActivityForResult(intent, 1);
A:
getActivity().startActivityForResult(intent, 1);
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:34:53
Primero usa startActivityForResult()
con parámetros en first Activity
y si desea enviar datos desde second Activity
a first Activity
luego pase el valor usando Intent
con el método setResult()
y obtenga esos datos dentro del método onActivityResult()
en first Activity
.
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-20 11:57:38
Problema Muy común en android
se puede dividir en 3 partes
1) iniciar la Actividad B (Ocurre en la Actividad A)
2) Establecer los datos solicitados (Sucede en activty B)
3) Recibir los datos solicitados (Ocurre en la actividad A)
1) Actividad inicial B
Intent i = new Intent(A.this, B.class);
startActivity(i);
2) Conjunto de datos solicitados
En esta parte usted decide si desea enviar datos de vuelta o no cuando ocurre un evento en particular.
Eg: En la actividad B hay es un EditText y dos botones b1, b2.
Al hacer clic en el botón b1, los datos se devuelven a actvity A
Al hacer clic en el botón b2 no se envía ningún dato.
Envío de datos
b1......clickListener
{
Intent resultIntent = new Intent();
resultIntent.putExtra("Your_key","Your_value");
setResult(RES_CODE_A,resultIntent);
finish();
}
No enviar datos
b2......clickListener
{
setResult(RES_CODE_B,new Intent());
finish();
}
El usuario hace clic en el botón atrás
De forma predeterminada, el resultado se establece con Actividad.RESULT_CANCEL response code
3) Recuperar resultado
Para ese método override onActivityResult
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RES_CODE_A) {
// b1 was clicked
String x = data.getStringExtra("RES_CODE_A");
}
else if(resultCode == RES_CODE_B){
// b2 was clicked
}
else{
// back button clicked
}
}
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-12-22 09:54:47
El anwser de @Nishant es correcto. En mi caso, el onActivityResult nunca fue llamado debido a la configuración en AndroidManifest. Asegúrate de que tu segunda actividad (o el remitente) no haya establecido esta línea en el manifiesto de Android.
<activity android:name=".SecondViewActivity"
android:parentActivityName=".FirstActivity"/>
En caso afirmativo, suprímase android:parentActivityName=".FirstActivity"
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-27 12:26:46