How to transfer data from multiple activities on AndroidStudio?

I'm new on Android and java and I'm trying to develop an app that needs multiple activities.

The first activity is a main menu, the second is an alarm and the third is for settings.

The problem is that I want to start the second activity from the first, but I want to check the password to stop the alarm from the third one.

I've checked many tutorials and it seems I need to send the data in the third activity to the second, but as I create the second on the first, I don't know how to get that "Intend" object to send the data, and if I create another one with the same reference it crashes.

I've tried to send the second intend from the first to the third activity, but I don't know how to recieve it, as it isn't neither a String, Int... and I can't do "bundle.getString".

As you may see i'm a bit confused and it may be easier than what I think. I will thank you for any answer.

First Activity (Main):

package com.example.robert.savemob;

import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class Main extends AppCompatActivity {

    Intent i1;
    Intent i2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        i1 = new Intent(this, Alarma.class );
        i2 = new Intent(this, Opciones.class);
    }

    public void Alarm(View view) {
        startActivity(i1);
    }
    public void Settings(View view) {
        startActivity(i2);
    }
}

Second Activity (Alarma)

package com.example.robert.savemob;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class Alarma extends AppCompatActivity {

    private EditText et1;
    String clavecorrecta;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarma);

        et1=(EditText)findViewById(R.id.et1);
        Bundle bundle = getIntent().getExtras();
        clavecorrecta = bundle.getString("clavecorrecta");
    }

    public void Parar(View v) {
        String clave=et1.getText().toString();
        if (clave.length()==0) {
            Toast notificacion= Toast.makeText(this,"Introduce la clave", Toast.LENGTH_LONG);
            notificacion.show();
        }
        else if (clave.equals(clavecorrecta)) {
            finish();
        }
        else {
            Toast notificacion= Toast.makeText(this,"Clave incorrecta", Toast.LENGTH_LONG);
            notificacion.show();
        }
    }
}

Third Activity (Opciones)

package com.example.robert.savemob;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;

public class Opciones extends AppCompatActivity {

    private EditText et2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.opciones);

        et2=(EditText)findViewById(R.id.et2);

        i1.putExtra("clavecorrecta", et2.getText().toString()); //I want to send it but can't acces to that i1
    }

}

Upvotes: 0

Views: 1437

Answers (3)

Waqas
Waqas

Reputation: 151

You can send primitive types as well as POJO objects to other activities. To send any POJO you must implement Serializable or Parcellable.

For example, to send data to Second Activity do something like this:

    Intent intent = new Intent(context, SingleFragmentHostActivity.class);
    Bundle extras = new Bundle();
    extras.putString("key_title", "Title");
    extras.putSerializable("pojo", new Car()); // Car class must implemente Serializable
    intent.putExtras(extras);
    startActivity(intent);

If you want to receive some data back from second activity you will have to use startActiivtyForResult instead of startActivity like this:

   public final static int REQUEST_CODE = 0001; // integer of your choice

   startActivityForResult(intent, REQUEST_CODE);

Then you must override onActivityResult method in the activity that called startActivityForResult. Something like this:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == REQUEST_CODE) {
        if(resultCode == RESULT_OK) {
            if(data != null && data.getExtras() != null) {      
                data.getExtras().getBoolean("key_is_success", false)
            }
        } else if(resultCoee == RESULT_CANEL){
           // Your logic in case user cancelled the operation or something.
        }
    }
}

For example from Second Activity you want to send a boolean back to First Activity. You can do something like this:

    Intent intent = new Intent();
    intent.putExtra("key_is_success", true);
    setResult(RESULT_OK, intent);
    finish();

Same sort of logic applies if you want to send some data back from Third Activity to Second Activity and Second Activity will send it back to First Activity.

You can also use Intent.FLAG_ACTIVITY_FORWARD_RESULT when launching Third Activity from Second Activity. According to documentation:

If set and this intent is being used to launch a new activity from an existing one, then the reply target of the existing activity will be transfered to the new activity. This way the new activity can call setResult(int) and have that result sent back to the reply target of the original activity.

Read this link for more details: https://developer.android.com/training/basics/intents/result.html

I hope it helps you out. Cheers!

Upvotes: 0

Nirup Iyer
Nirup Iyer

Reputation: 1225

You can do this. In your Opciones activity, declare a static String variable. Store EditText data into string and you can reference the string from the second activity.

Third Activity

public static String claveCorrecta = "";
claveCorrecta = et2.getText.toString();

Now in Second Activity you can reference the String by

Opciones.claveCorrecta

Upvotes: 0

Walter Palladino
Walter Palladino

Reputation: 479

Depending of the data you need to share, you can send bundles between activities, use shared preferences or implement your own singleton class with data shared between all the app. When I need to share data which needs to be known at any point of the app for different activities, I prefer a singleton like this:

public class AppData {

    private static AppData ourInstance = new AppData ();

    private String deviceId = null; //  Device
    private String coupon = null;   //  Coupon used to chack a valid event



    public static AppData getInstance () {
        return ourInstance;
    }

}

And used like:

AppData.getInstance().deviceId = "sample device Id";

If you need to send information in a discrete way from an instance to another:

  1. From the source activity something like:

    private void switchToLoginActivity (int errorCode) { Intent intent = new Intent(this, LoginActivity.class);

    Bundle bundle = new Bundle();
    bundle.putInt (Commons.LOGIN_SHOW_MESSAGE, errorCode);
    
    intent.putExtras(bundle);
    startActivity(intent);
    overridePendingTransition(R.anim.left_to_right_in, R.anim.left_to_right_out);
    finish();
    

    }

  2. At the destination activity you need to get the data received:

    public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState);

    getParametersFromIntent();
    

    }

    private void getParametersFromIntent () {

    Bundle bundle = getIntent().getExtras();
    
    if (bundle != null) {
    
        if (bundle.containsKey(Commons.LOGIN_SHOW_MESSAGE)) {
            showMessage = bundle.getInt (Commons.LOGIN_SHOW_MESSAGE);
        }
    
    }
    

    }

Hope it helps.

Upvotes: 1

Related Questions