How to pass value from 1 class method to another class activity
public class A extends Activity {
int value;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.
.
.
methodA();
}
public void methodA() {
if (condition) {
value = 1
} else if (condition) {
value = 2
} else {
value = 3
}
}
}
}
public class B extends Activity {
protected void onCreate(Bundle savedInstanceState) {
int val;
super.onCreate(savedInstanceState);
.
.
//how do we can get val = value
}
}
Question is how can val from class B get the value from class A? Will intent work here?
There are several options to pass values. However passing integer is not best pattern in my private opinion. I used to create class ex. call it ContainerWithData that implements Serializable (may be Parcalable). I would prefer thge first one as it can be used later on by other libraries like Gson for api sending or mappers to convert.
Class Aa extends Activity {
public initAndRunBeAcitvity(int parameterInt){
ContainerWithData data = new ContainerWithData();
data.setIntegerValue(parameterInt);
runBe(data);
}
public void runBe(ContainerWithData data){
Intent intent = new Intent(Aa.this,Be.class);
intent.putExtra("MyBeData",data);
startActivity(intent);
}
}
Class Be extends Activity {
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
prepareInitParameters();
}
private void prepareInitParameters(){
getInitParameters();
checkInitParameters();
}
private void getInitParameters(){
ContainerWithData value = getIntent().getSerializableExtra("MyBeData");
this.value = value;
}
private void checkInitParameters(){
if (value==null){
//Perform any initialization data,
//message or postDelayed closing of activity
}
}
}
Class ContainerWithData implements Serializable {
@Getter
@Setter
private Integer integerValue;
//can be null if not setted,
//so should be checked by if conditions later on controller of view logic
}
So proposition is to use
getIntent().getSerializableExtra("MyBData");
and
getIntent().getSerializableExtra("MyBData"); together with using model to pass data.
With such pattern many times I had avoid spending more time to add new values as application grows.