1
        loginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            User currUser ;
            currUser = MainActivity.mainMenuPrompt(theBank, UserID, password, bankView, errorLogin);

            Intent intent = new Intent(MainActivity.this, MainActivity2.class);

            intent.putExtra("USER", currUser);
            startActivity(intent);
        }
    });

I can't pass my "currUser" variable with intent. Is there any other way to do it?

Zjeref
  • 19
  • 1
  • 5

3 Answers3

2

If we want to pass an object between activities we use Parcelable or Serialazable. Generally, we use Parcelabel as it is faster than Serialazable. In order to use it in your case the User class must implement Parcelable interface and provide the implementation of methods and then we create Parcelable constructor and send data as we used to send with intent.putExtra() method and in the other activity we receive data using getIntent().getParcelableExtra() method.
User.class

public class User implements Parcelable {
private String theBank;
private int userId;
private String password;
private String bankView;
private String errorLogin;

public User(String theBank, int userId, String password, String bankView, String errorLogin) {
    this.theBank = theBank;
    this.userId = userId;
    this.password = password;
    this.bankView = bankView;
    this.errorLogin = errorLogin;
}

public String getTheBank() {
    return theBank;
}

public void setTheBank(String theBank) {
    this.theBank = theBank;
}

public int getUserId() {
    return userId;
}

public void setUserId(int userId) {
    this.userId = userId;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public String getBankView() {
    return bankView;
}

public void setBankView(String bankView) {
    this.bankView = bankView;
}

public String getErrorLogin() {
    return errorLogin;
}

public void setErrorLogin(String errorLogin) {
    this.errorLogin = errorLogin;
}

protected User(Parcel in) {
    theBank = in.readString();
    userId = in.readInt();
    password = in.readString();
    errorLogin = in.readString();
}

public static final Creator<User> CREATOR = new Creator<User>() {
    @Override
    public User createFromParcel(Parcel in) {
        return new User(in);
    }

    @Override
    public User[] newArray(int size) {
        return new User[size];
    }
};

@Override
public int describeContents() {
    return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
    parcel.writeString(theBank);
    parcel.writeInt(userId);
    parcel.writeString(password);
    parcel.writeString(errorLogin);
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

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

    // User class initialization
    User userObj = new User("SBI", 001, "stackOverFlow", "OpenBank", "Sorry!!");

    // Passing data with key-name as user
    Intent intent = new Intent(this, MainActivity2.class);
    intent.putExtra("user", userObj);
    startActivity(intent);

    }
}

MainActivity2.java

public class MainActivity2 extends AppCompatActivity {

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

    // Receiving the user objet using getIntent().getParcelableExtra() method
    User user = getIntent().getParcelableExtra("user");
    String bank = user.getTheBank();
    int id = user.getUserId();
    String password = user.getPassword();
    String bankView = user.getBankView();
    String error = user.getErrorLogin();

    Toast.makeText(this, bank + id + password + bankView + error, Toast.LENGTH_SHORT).show();
    }
}
paul035
  • 327
  • 2
  • 8
0

It is better to use live data to save the object. It is easy to configurate in the project.

The android's page is https://developer.android.com/topic/libraries/architecture/livedata?hl=es-419

The first you need to use the next library

// Live data
implementation "androidx.annotation:annotation:$versions.annotation"
api "androidx.lifecycle:lifecycle-extensions:$versions.archComponents"

   annotation      : '1.0.0',
   archComponents  : '2.0.0',

If you don't want to use livedata, you could use The gson library to convert object to string. After you need to convert the string to class

Alejandro Gonzalez
  • 1,221
  • 4
  • 15
  • 30
  • I'd upvote this answer if the OP was using a single activity and could share a viewmodel between fragments. You can't pass LiveData to the other activity without making it a global static variable and then; it wouldn't survive process death – Some random IT boy Jan 23 '22 at 17:55
  • Because you don't need to use the global static, due that the live data has the responsability to save the object, in this case you need the setValue to persist the object – Alejandro Gonzalez Jan 23 '22 at 18:23
  • Live data does not persist objects and it doesnt survive process death – Some random IT boy Jan 23 '22 at 18:30
0

Easy use EventBus.

Add EventBus to your project

implementation("org.greenrobot:eventbus:3.3.1")

Create a class to store the data you want to send

public class User {
    private String theBank;
    private int userId;
    private String password;
    private String bankView;
    private String errorLogin;

    public User(String theBank, int userId, String password, String bankView, String errorLogin) {
        this.theBank = theBank;
        this.userId = userId;
        this.password = password;
        this.bankView = bankView;
        this.errorLogin = errorLogin;
    }

    public String getTheBank() {
        return theBank;
    }

    public void setTheBank(String theBank) {
        this.theBank = theBank;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getBankView() {
        return bankView;
    }

    public void setBankView(String bankView) {
        this.bankView = bankView;
    }

    public String getErrorLogin() {
        return errorLogin;
    }

    public void setErrorLogin(String errorLogin) {
        this.errorLogin = errorLogin;
    }
}

In the activity/fragment that received the data

Register and unregister your subscriber

@Override
public void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}

@Override
public void onStop() {
    super.onStop();
    EventBus.getDefault().unregister(this);
}

Message will be received in here

private User _user;

@Subscribe(threadMode = ThreadMode.MAIN)  
public void onMessageEvent(User user) {
    Log.d("theBank", user.getTheBank());
    Log.d("userId", user.getUserId());
    Log.d("password", user.getPassword());
    Log.d("bankView", user.getBankView());
    Log.d("errorLogin", user.getErrorLogin());

    // save user in member variable (_user), 
    //   so you can access _user from other place in this activity or fragment
    _user  = user;
}

In the activity/fragment that sends the data

User user = new User();
user.setTheBank = "my bank";
user.setUserId = 1;
user.setPassword = "my password";
user.setBankView = "my bank view";
user.setErrorLogin = "my error login";

EventBus.getDefault().post(user);
Ihdina
  • 950
  • 6
  • 21
  • Bringing an entire event bus just to pass a data object between activities is a complete overkill. You might as well just set a dirty global static variable and read it from there. Note that the approach given by the answer and the dirty static variable will work; none of them will survive process death. Crash crash crash – Some random IT boy Jan 23 '22 at 17:53
  • I also use eventbus greenrobot on android edc app for communication between fragments, activities and native(c ansi), all works fine. – Ihdina Apr 13 '22 at 13:21