I can't believe I have so much trouble with this. I have this variable in my game activity:
public static int numberOfPointsA;
and in another activity
public static int numberOfPointsB;
Now I need these values to pass to another activity, where I should total these values and set result to textView. Since these are public static variables I tried:
public static int totalScore = ClassA.numberOfPointsA + ClassB.numberOfPointsB;
textView.setText("" + totalScore);
But that's not working. So I tried with intent:
In game classA:
Intent intent = new Intent(this, Menu.class);
intent.putExtra("foobar", numberOfPointsA);
startActivity(intent);
and in menu class:
Intent intent = getIntent();
int numberOfPointsA = intent.getIntExtra("foobar", 0);
But that's not working either. If I place in the scope of activity, as soon as activity starts it crashes. If I place it in onCreate method, I can's use my int variable anymore, I don't need it in onCreate method, I need it elsewhere.
So how to set my variable in game class, pass to menu class, save it there and then make it wait until I finish my game class B and do the same with that variable, and then total those two variables and set it successfuly to the textView?
Menu activity:
public class Izbor extends Activity implements OnClickListener{
private int asocijacijeUkupno = 0;
private int thUkupno = 0;
int ukupanBrojPoena = asocijacijeUkupno + thUkupno;
Button toploHladno, asocijacije, cigle, spojnice, nazad, poeniTH, poeniAso, poeniCigle, poeniSpojnice, poeniUkupno;
TextView naslov;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
asocijacijeUkupno = getIntent().getIntExtra("RUNNING_TOTAL", 0);
thUkupno = getIntent().getIntExtra("RUNNING_TOTAL2", 0);
setContentView(R.layout.izbor);
addListenerOnButton();
}
private void addListenerOnButton() {
naslov = (TextView) findViewById(R.id.tvIzborNaslov);
toploHladno = (Button) findViewById(R.id.bIzbor1);
asocijacije = (Button) findViewById(R.id.bIzbor2);
cigle = (Button) findViewById(R.id.bIzbor3);
spojnice = (Button) findViewById(R.id.bIzbor4);
nazad = (Button) findViewById(R.id.bIzborNazad);
poeniTH = (Button) findViewById(R.id.bPoeniTH);
poeniAso = (Button) findViewById(R.id.bPoeniAso);
poeniCigle = (Button) findViewById(R.id.bPoeniCigle);
poeniSpojnice = (Button) findViewById(R.id.bPoeniSpojnice);
poeniUkupno = (Button) findViewById(R.id.bPoeniUkupno);
toploHladno.setOnClickListener(this);
asocijacije.setOnClickListener(this);
cigle.setOnClickListener(this);
spojnice.setOnClickListener(this);
nazad.setOnClickListener(this);
}
#Override
protected void onStart() {
super.onStart();
if(asocijacijeUkupno != 0){
poeniAso.setText("" + asocijacijeUkupno);
}else{
poeniAso.setText("");
}
if(thUkupno != 0){
poeniTH.setText("" + thUkupno);
}else{
poeniTH.setText("");
}
if(ukupanBrojPoena != 0){
poeniUkupno.setText("" + ukupanBrojPoena);
}else{
poeniUkupno.setText("");
}
}
public void onClick(View v) {
switch(v.getId()){
case R.id.bIzbor1:
if(music == true){
buttonClicks.start();
}
startActivity(new Intent("rs.androidaplikacije.toplo_hladno.TOPLOHLADNO"));
break;
case R.id.bIzbor2:
if(music == true){
buttonClicks.start();
}
startActivity(new Intent("rs.androidaplikacije.toplo_hladno.ASOCIJACIJE"));
break;
case R.id.bIzbor3:
if(music == true){
buttonClicks.start();
}
break;
case R.id.bIzbor4:
if(music == true){
buttonClicks.start();
}
break;
case R.id.bIzborNazad:
if(music == true){
buttonBack.start();
}
finish();
break;
}
}
}
The following is a very basic example, using two activities to pass an int around.
First Activity, which you start from:
public class FirstActivity extends Activity {
private int mTotal = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//.... onCreate code, layout stuff etc....
}
// this is tied to a View onClick call
public void moveToSecondAct(View view) {
Intent intent = new Intent();
intent.putExtra("RUNNING_TOTAL",mTotal);
intent.setClass(this, SecondActivity.class);
//... any other options like ...
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// start the second Activity
startActivity(intent);
}
}
And the second Activity example is something like:
public class SecondActivity extends Activity {
private int mTotal = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTotal = getIntent().getIntExtra("RUNNING_TOTAL", 0);
//.... onCreate code, layout stuff etc....
Log.i("Running total is:"+ mTotal);
// update the total on the TextView
TextView tv = (TextView) findViewById(R.id.poeniUkupno);
tv.setText("Total: "+ mTotal);
}
}
Edit: Some changes to try help make things clearer
I didn't completely get what you have been trying to say but what I got was you want to create a variable in FirstActivity send its value to SecondActivity and then pass their sum to ResultActivity if its so then here you go
//First Activity
public class FirstActivity extends Activity{
int firstValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
firstValue = 10;
}
public sendValueToSecondActivity(View view){
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("firstValue", firstValue);
startActivity(intent);
}
}
//Second Activity
public class SecondActivity extends Activity{
int sumOfFirstAndSecond;
int secondValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
secondValue = 20;
}
public sendValueToSecondActivity(View view){
sumOfFirstAndSecond = getIntent().getIntExtra("firstValue") + secondValue;
Intent intent = new Intent(this, ResultActivity.class);
intent.putExtra("sumOfFirstAndSecond", sumOfFirstAndSecond);
startActivity(intent);
}
}
//Result Activity
public class ResultActivity extends Activity{
TextView textView;
int result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
secondValue = 20;
textView = (TextView) findViewById(R.id.textView);
}
public setResultToTextView(View view){
result = getIntent().getIntExtra("sumOfFirstAndSecond");
textView.setText(""+result);
}
}
Related
I am new to Android development. I have an app in which the user creates multiple names (as if they were players of a game). These "players" appear as a matrix is used in the same activity. (Being possible here to exclude any player).
I want to display all of these players (MainActivity) in another activity (Main2Activity), showing only the first player added and, clicking a button, switch to the second player.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
RecyclerView recyclerView;
TextView textAdd;
EditText etAdd;
ArrayList<Model> models = new ArrayList<Model>();
MyAdapter myAdapter;
int position;
Button prox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prox = findViewById(R.id.prox);
prox.setOnClickListener(new View.OnClickListener() {
//next screen
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
String nome = etAdd.getText().toString();
intent.putExtra("value", nome);
startActivity(intent);
}
});
recyclerView = findViewById(R.id.recyclerView);
textAdd = findViewById(R.id.text_adicionar);
etAdd = findViewById(R.id.et_Adicionar);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
myAdapter = new MyAdapter(getApplicationContext(),
models, new MyAdapter.Onclick() {
#Override
public void onEvent(Model model, int pos) {
position = pos;
etAdd.setText(model.getId());
}
});
recyclerView.setAdapter(myAdapter);
textAdd.setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.text_adicionar: {
insertItem(String.valueOf(etAdd.getText()));
}
break;
}
}
private void insertItem(String name) {
Gson gson = new Gson();
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", name);
Model model = gson.fromJson(String.valueOf(jsonObject), Model.class);
models.add(model);
myAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public class Main2Activity extends AppCompatActivity implements View.OnClickListener {
Button play;
TextView text_player_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
play = findViewById(R.id.play);
text_player_name = findViewById(R.id.text);
play.setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.play: {
String name = getIntent().getExtras().getString("value");
text_player_name.setText(String.valueOf(name));
}
break;
}
}
}
I'm not sure if I fully understand your question, but are you just looking for a way to pass data from one Activity to another?
If so, use .putExtra() with your Intent for starting the next Activity.
In the onCreate method for your second Activity, use .getExtras() to retrieve the data.
In 1st Activity
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("DataName", data);
startActivity(intent);
In the 2nd Activity
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
String[] dataArray = getIntent().getExtras().get("DataName"));
}
EDIT:
public class Main2Activity extends AppCompatActivity implements View.OnClickListener {
Button play;
TextView text_player_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
play = findViewById(R.id.play);
text_player_name = findViewById(R.id.text);
play.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String name = getIntent().getExtras().getString("value");
text_player_name.setText(String.valueOf(name));
}
I have an activity and I don't want it to reload every time I get into it. I want it to show the information which had the last time i got into it.
But I also want to have one Button in another activity that will refresh the other activity, so that when i get into it the information has changed. I say that the content changes because the activity show different recyclerviews everytime you get into it.
That is my MainActivity.java:
public class Comida extends AppCompatActivity implements Adaptador2.OnRecipeListener {
private RecyclerView recyclerView1;
List<Entidad2> listItems;
Adaptador2 adaptor;
private Entidad2 entidad1,entidad2,entidad3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_comida);
recyclerView1 = findViewById(R.id.lv_1);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView1.setLayoutManager(layoutManager);
listItems = new ArrayList<>();
entidad1 = new Entidad2(R.drawable.calabacines_3, "Solomillo a la plancha", " 10 min.", 4, 20);
entidad2 = new Entidad2(R.drawable.patatas_deluxe_especiadas_70523_300_150, "Entrecot", " 15 min.", 2, 50);
entidad3 = new Entidad2(R.drawable.tomate, "Hamburguesa", " 2 min.", 5, 100);
listItems.add(entidad1);
listItems.add(entidad2);
listItems.add(entidad3);
adaptor = new Adaptador2(listItems, this);
recyclerView1.setAdapter(adaptor);
adaptor.notifyDataSetChanged();
pickEntidad();
}
#Override
public void OnRecipe(int priority) {
if (priority == 20) {
Intent in = new Intent(this, Solomillo.class);
startActivity(in);
}
if (priority == 50) {
Intent in = new Intent(this, Entrecot.class);
startActivity(in);
}
if (priority == 100) {
Intent in = new Intent(this, Hamburguesa.class);
startActivity(in);
}
}
private void pickEntidad(){
final int random = new Random().nextInt(101);
int priority1 = entidad1.getPriority();
int priority2 = entidad2.getPriority();
int priority3 = entidad3.getPriority();
listItems.clear();
if(random < priority1){
listItems.add(entidad1);
}else if(random < priority2){
listItems.add(entidad2);
}else if (random <= priority3){
listItems.add(entidad3);
}
adaptor.notifyDataSetChanged();
}
}
And that is my activityWithButton.java:
public class Menu extends AppCompatActivity {
Button boton_start;
Button boton_refresh;
Button boton_prueba;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
boton_start=(Button) findViewById(R.id.boton_platos);
boton_refresh = (Button) findViewById(R.id.boton_cambiarmenu);
boton_prueba=(Button) findViewById(R.id.boton_menu);
boton_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(Menu.this,Dishes.class);
startActivity(in);
}
});
boton_prueba.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(Menu.this,Comida.class);
startActivity(in);
}
});
boton_prueba.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//What to do?
}
});
}
}
Please help I don't know what to do.
Thanks
You have two fairly straight-forward options, SharedPreferences and SavedInstanceState.
SharedPreferences, you can access and save data anywhere context is available within your app assigning a key, value pair to any data to later be retreived. Generally you will want to save the data during certain lifecycle events such as onStop and retreive it somewhere else once the activity returns:
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
#Override
public void onStop() {
super.onStop();
editor.putString("key", "My string");
editor.commit();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String myValue = editor.getString("key");
}
SavedInstanceState, comes with the onCreate override method in your activities. Utilising the available override method onSaveInstanceState, pass in the required data when the activity is temprarily destroyed to be retreived on its recreation.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
String myValue = savedInstanceState.getString("key");
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("key", "My string");
super.onSaveInstanceState(outState);
}
Further reading https://developer.android.com/guide/components/activities/activity-lifecycle
I have an activity and I don't want it to reload every time I get into it. I want it to show the information which had the last time I got into it.
But I also want to have one Button in another activity that will refresh the other activity, so that when I get into it the information has changed.
I say that the content changes because the activity shows different recyclerviews every time you get into it.
And that is my activityWithButton.java:
public class Menu extends AppCompatActivity {
Button boton_start;
Button boton_refresh;
Button boton_prueba;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
boton_start=(Button) findViewById(R.id.boton_platos);
boton_refresh = (Button) findViewById(R.id.boton_cambiarmenu);
boton_prueba=(Button) findViewById(R.id.boton_menu);
boton_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(Menu.this,Dishes.class);
startActivity(in);
}
});
boton_prueba.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(Menu.this,Comida.class);
startActivity(in);
}
});
boton_prueba.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//What to do?
}
});
}
}
That is my MainActivity.java:
public class Comida extends AppCompatActivity implements Adaptador2.OnRecipeListener {
private RecyclerView recyclerView1;
List<Entidad2> listItems;
Adaptador2 adaptor;
private Entidad2 entidad1,entidad2,entidad3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_comida);
recyclerView1 = findViewById(R.id.lv_1);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView1.setLayoutManager(layoutManager);
listItems = new ArrayList<>();
entidad1 = new Entidad2(R.drawable.calabacines_3, "Solomillo a la plancha", " 10 min.", 4, 20);
entidad2 = new Entidad2(R.drawable.patatas_deluxe_especiadas_70523_300_150, "Entrecot", " 15 min.", 2, 50);
entidad3 = new Entidad2(R.drawable.tomate, "Hamburguesa", " 2 min.", 5, 100);
listItems.add(entidad1);
listItems.add(entidad2);
listItems.add(entidad3);
adaptor = new Adaptador2(listItems, this);
recyclerView1.setAdapter(adaptor);
adaptor.notifyDataSetChanged();
pickEntidad();
}
#Override
public void OnRecipe(int priority) {
if (priority == 20) {
Intent in = new Intent(this, Solomillo.class);
startActivity(in);
}
if (priority == 50) {
Intent in = new Intent(this, Entrecot.class);
startActivity(in);
}
if (priority == 100) {
Intent in = new Intent(this, Hamburguesa.class);
startActivity(in);
}
}
private void pickEntidad(){
final int random = new Random().nextInt(101);
int priority1 = entidad1.getPriority();
int priority2 = entidad2.getPriority();
int priority3 = entidad3.getPriority();
listItems.clear();
if(random < priority1){
listItems.add(entidad1);
}else if(random < priority2){
listItems.add(entidad2);
}else if (random <= priority3){
listItems.add(entidad3);
}
adaptor.notifyDataSetChanged();
}
}
Please help I don't know what to do.
Thanks
you can`t prevent from reloading activity but you can retrieve last state of your activity every time onCreate() method is called by using savedInstanceState like this:
TextView textView;
// some transient state for the activity instance
String gameState;
#Override
public void onCreate(Bundle savedInstanceState) {
// call the super class onCreate to complete the creation of activity like
// the view hierarchy
super.onCreate(savedInstanceState);
// recovering the instance state
if (savedInstanceState != null) {
gameState = savedInstanceState.getString(GAME_STATE_KEY);
}
// set the user interface layout for this activity
// the layout file is defined in the project res/layout/main_activity.xml file
setContentView(R.layout.main_activity);
// initialize member TextView so we can manipulate it later
textView = (TextView) findViewById(R.id.text_view);
}
// This callback is called only when there is a saved instance that is previously saved by using
// onSaveInstanceState(). We restore some state in onCreate(), while we can optionally restore
// other state here, possibly usable after onStart() has completed.
// The savedInstanceState Bundle is same as the one used in onCreate().
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
textView.setText(savedInstanceState.getString(TEXT_VIEW_KEY));
}
// invoked when the activity may be temporarily destroyed, save the instance state here
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(GAME_STATE_KEY, gameState);
outState.putString(TEXT_VIEW_KEY, textView.getText());
// call superclass to save any view hierarchy
super.onSaveInstanceState(outState);
}
for more info about savedInstanceState and android lifecycles look at the official docs
I have a button. When I click the button, I want to change the value of the variable to 3. In another activity, I want to be able to get the value of the variable and do some computation based on that value.
I have tried using getters and setters methods and just traditionally changing the values and nothing seems to work.
//MainActivity.java
mButtonChoice2 = (Button)findViewById(R.id.choice2);
mButtonChoice2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
//My logic for Button goes in here
if (mButtonChoice2.getText() == "Three"){
setDays(3);
openActivity();
}
}
public int getDays() {
return days;
}
public void setDays(int value){
days = value;
}
public void openActivity() {
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
//SecondActivity.java
public class SecondActivity extends AppCompatActivity {
private TextView textview;
private MainActivity obj = new MainActivity();
Integer days = obj.getDays();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
textview = findViewById(R.id.program);
if (days == 3) {
textview.setText("Days is 3");
}
else {
textview.setText(days);
}
I want the textview in the SecondActivity to update the textview text with "days is 3"
However, it just errors out because it is not being able to correctly receive the value of the integer days.
try the following updated code:
//MainActivity.java
mButtonChoice2 = (Button)findViewById(R.id.choice2);
mButtonChoice2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
//My logic for Button goes in here
if (mButtonChoice2.getText() == "Three"){
setDays(3);
openActivity();
}
}
public int getDays() {
return days;
}
public void setDays(int value){
days = value;
}
public void openActivity() {
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra ("days",days);
startActivity(intent);
}
//SecondActivity.java
public class SecondActivity extends AppCompatActivity {
private TextView textview;
private MainActivity obj = new MainActivity();
// Integer days = obj.getDays();
int days=0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent intent=getIntent();days=intent.getIntExtra ("days",0);
textview = findViewById(R.id.program);
if (days == 3) {
textview.setText("Days is 3");
}
else {
textview.setText(days);
}
Reference :https://developer.android.com/reference/android/content/Intent
https://www.dev2qa.com/passing-data-between-activities-android-tutorial/
Just Declare a static variable in one activity and use it into the second activity.
Starting Intent then calling Method?
In the two classes, the second one has a StartIntent. Right now it simply starts the intent to the first class. I am wanting to know if it is possible from that same onClickListener to essentially StartIntent for the first class as usual, but then immediately call the defaultMap() method within it.
Sometimes I want to simply start the intent normally, and other times I want to start the intent and then call that method. 1) therefore, I can't just make so that OnCreate of the first class it calls defaultMap, because i don't always want to call it. But also 2) I don't want to JUST call the defaultMap() class. I need to call the full class so that it runs through the onCreate functions THEN goes to the defaultMap
FIRST CLASS USED
public class Daily_Schedule extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily__schedule);
......
.......
......
}
public void defaultMap(){
......
.......
......
}
SECOND CLASS USED
public class InRouteDisplay extends AppCompatActivity implements OnMapReadyCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_in_route_display);
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(InRouteDisplay.this, DailySchedule.class);
InRouteDisplay.this.startActivity(myIntent);
}
});
.....
....
.....
}
Try the following: Two ways: 1) Using putExtra() -------- 2) Using SharedPreferences
1)
Demo4.class:-----------
public class Demo4 extends AppCompatActivity {
private Button b;
private final String CALL_DEFAULT_MAP = "call_default_map";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily__schedule);
if(getIntent() != null) {//1
if(getIntent().getStringExtra(CALL_DEFAULT_MAP) != null) {
if (getIntent().getStringExtra(CALL_DEFAULT_MAP).equals("true")) {
defaultMap();
}
}
}
b = (Button) findViewById(R.id.b);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(Demo4.this, Demo5.class);
finish();
startActivity(myIntent);
}
});
}
public void defaultMap() {
Toast.makeText(getApplicationContext(),"defaultMap()---called",Toast.LENGTH_LONG).show();
}
}
Demo5.class------
public class Demo5 extends AppCompatActivity {
private Button home;
private final String CALL_DEFAULT_MAP = "call_default_map";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_in_route_display);
home = (Button) findViewById(R.id.home);
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(Demo5.this, Demo4.class);
myIntent.putExtra(CALL_DEFAULT_MAP,"true");//1
finish();
startActivity(myIntent);
}
});
}
}
2)
Demo4.class---------
public class Demo4 extends AppCompatActivity {
private Button b;
private final String CALL_DEFAULT_MAP = "call_default_map";
private SharedPreferences p;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily__schedule);
p = getApplicationContext().getSharedPreferences("p_key",
0);//2
if(p != null){//2
if(p.getBoolean(CALL_DEFAULT_MAP , false)){
defaultMap();
}
}
b = (Button) findViewById(R.id.b);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(Demo4.this, Demo5.class);
finish();
startActivity(myIntent);
}
});
}
public void defaultMap() {
setBoolean(CALL_DEFAULT_MAP , false);//2
Toast.makeText(getApplicationContext(),"defaultMap()---called",Toast.LENGTH_LONG).show();
}
public void setBoolean(String Name, boolean value)
{
if(p != null){
SharedPreferences.Editor editor = p.edit();
editor.putBoolean(Name, value);
editor.apply();
}
}
}
Demo5.class:----------------
public class Demo5 extends AppCompatActivity {
private Button home;
private final String CALL_DEFAULT_MAP = "call_default_map";
private SharedPreferences p;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_in_route_display);
p = getApplicationContext().getSharedPreferences("p_key",
0);
home = (Button) findViewById(R.id.home);
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setBoolean(CALL_DEFAULT_MAP , true);//2
Intent myIntent = new Intent(Demo5.this, Demo4.class);
finish();
startActivity(myIntent);
}
});
}
public void setBoolean(String Name, boolean value)
{
if(p != null){
SharedPreferences.Editor editor = p.edit();
editor.putBoolean(Name, value);
editor.apply();
}
}
}
No. The sending class doesn't get an instance of the Activity to call it on. What you can do is set a parameter in the intent, USE_DEFAULT_MAP to 1. The activity you launch can look for that variable, and use that to know that it should call defaultMap.
Use if statement inside the Daily_Schedule activity and check the extra whether they are set or null. Use getIntent() method. check the answer of this
From InRouteDisplay activity pass the intent data using putextra before calling InRouteDisplay.this.startActivity(myIntent);
Use this link to how to putextra data to the intent
Use this link's answer to know how to putextra data to the intent