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
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 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.
I'm trying to change a textview value on one activity by using a numberpicker on the previous activity. Any help would be appreciated.
Here's the relevant part of my Java from activity1
public class activity_game extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
final NumberPicker fizzNumberPkr = (NumberPicker)findViewById(fizzNumberPicker);
fizzNumberPkr.setValue(3);
fizzNumberPkr.setMinValue(1);
fizzNumberPkr.setMaxValue(20);
fizzNumberPkr.setWrapSelectorWheel(true);
final NumberPicker buzzNumberPkr = (NumberPicker)findViewById(buzzNumberPicker);
buzzNumberPkr.setValue(5);
buzzNumberPkr.setMinValue(1);
buzzNumberPkr.setMaxValue(20);
buzzNumberPkr.setWrapSelectorWheel(true);
}
public void toActivityPlay (View view) {
Intent toActivityPlay = new Intent(this, activity_play.class);
toActivityPlay.putExtra("fizzNumber", fizzNumber);
toActivityPlay.putExtra("buzzNumber", buzzNumber);
startActivity(toActivityPlay);
}
And my relevant java from activity2
public class activity_play extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
TextView fizzNumberText = (TextView)findViewById(R.id.fizzNumber);
fizzNumberText.setText(getIntent().getExtras().getString("fizzNumber"));
if(getIntent().hasExtra("fizzNumber")) {
fizzNumber = getIntent().getIntArrayExtra();
} else {
throw new IllegalArgumentException("Error: Fizz number not found");
}
If there's any relevant code that I may not have posted please let me know and i'll edit my post.
Some ideas come to me now to communicate two activities..
You can create a method setValuePicker()/getValueFromPicker() in the first Activity, and call getValue() in the other activity.
public void setValuePicker(Parameter value){
number = value;
}
public Parameter getValuePicker(){
return value;
}
If you variable have been set global only need implement getValue() method.
If you someday want use fragments need implement callback.
EDIT:
Using your code is something like this:
- FirstActivity
public class MainActivity extends AppCompatActivity {
private int number;
public static final String FIZZ_TAG = "fizz_numer";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final NumberPicker picker = (NumberPicker) findViewById(R.id.numberPicker);
picker.setMinValue(0);
picker.setMaxValue(10);
picker.setValue(5);
picker.setWrapSelectorWheel(true);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
number = picker.getValue();
Intent intent = new Intent(getApplicationContext(), Main2Activity.class)
.putExtra(FIZZ_TAG,number);
startActivity(intent);
}
});
}
}
Second Activity need be something like this.
.
.
.
.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
int s = getIntent().getIntExtra(MainActivity.FIZZ_TAG,0);
TextView textView = (TextView) findViewById(R.id.text_test);
textView.setText(String.format("%s = %d","number ",s));
}
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);
}
}
I'm trying to switch the views, but when I'm in the second view, the back event click doesnt work.. I don't know what's wrong.
Pls, see my code and help me!
Part1
Part2
public class t extends Activity implements OnClickListener {
Button volta;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.janela2);
volta = (Button) findViewById(R.id.button2);
volta.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v == volta) {
startActivity(new Intent(t.this, MainActivity.class));
}
}
}
You have to override onBackPressed. Change your MainActivity as below
public class MainActivity extends Activity {
private boolean goBack = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sobre = (Button) findViewById(R.id.button1);
sobre.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
goBack = true;
setContentView(R.layout.janela2);
}
});
}
#Override
public void onBackPressed() {
//If you have switched to R.layout.janela2 then go back
if (goBack){
setContentView(R.layout.activity_main);
goBack = false;
return;
}
//else do default action
super.onBackPressed();
}
}
Just do the following code, I hope it might help you
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sobre = (Button) findViewById(R.id.button1);
sobre.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, t.class);
startActivity(intent);
}
});
}
}
In t.java
public class t extends Activity{
Button volta;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.janela2);
}
#Override
public void onStop() {
super.onStop();
finish();
}
}
If you want two layouts then use viewflipper. If you want two activities (java classes) AND two layouts separately then use:
Intent i = new Intent (this, myClass.class);
startActivity(i);
To start the Activity and NOT setcontentview
So here:
public void onClick(View v) {
startActivity(new Intent (MainActivity.this, t.class));
OR IN THE CASE OF T.CLASS:
startActivity(new Intent (t.this, MainActivity.class));
}
You have to override onBackPressed() method if you want to back button functionality in your application. i.e.
public void onBackPressed() {
Intent start = new Intent(CurrentClass.this,Next_Activity.class);
startActivity(start);
finishActivity(0);
}