Android call method from another activity - java

How would I call a method from a different activity?
In my main activity, I have a button that shows a dialog to set the difficulty level of the game.
Then you click start game which starts a new activity containing a view with all the game information.
I need to send the difficulty level chosen to the other activity but cannot seem to figure out how to.

You could put it in the extras with the intent:
Intent StartGame = new Intent(this, StartGame.class);
StartGame.putExtra("difficulty", difficultyLevel);
startActivity(StartGame);
Then in your StartGame.class you can retrive it like this(assuming its a string):
Bundle extras = getIntent().getExtras();
if (extras != null) {
String difficulty= extras.getString("difficulty");
}

Well I don't know how sound my solution is but I created a myApplication class which sub classes the Application class .
This holds the reference to the activity I wanted to call
import android.app.Application;
public class myApplication extends Application {
public PostAndViewActivity pv;
}
When the PostAndViewActivity calls the oncreate is sets the pv to point to itself.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((myApplication) getApplication()).pv = this;
Then when I want to call the method I want I just use code like this:
((myApplication) getApplication()).pv.refreshYourself();
Perhaps a bit hacky but it works.....
I welcome some critisism for this ;-)

Related

onSavedInstanceState doesn't save my Instance

Hope you're all doing fine in these tough times.
I have 2 activities, A and B.
A has a button that enables an intent to go from A to B. B itself has a Dialog window whom's cancel button enables an Intent to go from B to A.
I'd like to save some data from A (2 EditTexts' content) so when I come back to A I don't have to retype those EditTexts.
So after looking up the documentation and a bit of StackOverflow, I decided to go with the onSavedInstance method but I'm wondering whether the intent transition destroys the Activity and hence the savedInstance as well...
Here's my simplified code - Activity A :
public class A extends AppCompatActivity {
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_match);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
if (savedInstanceState != null) {
EditText firstPlayer = findViewById(R.id.firstPlayerName);
EditText secondPlayer = findViewById(R.id.secondPlayerName);
String firstPlayerName = savedInstanceState.getString("firstPlayerName");
String secondPlayerName = savedInstanceState.getString("secondPlayerName");
firstPlayer.setText(firstPlayerName);
secondPlayer.setText(secondPlayerName);
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
EditText firstPlayer = findViewById(R.id.firstPlayerName);
EditText secondPlayer = findViewById(R.id.secondPlayerName);
String firstPlayerName = String.valueOf(firstPlayer.getText());
String secondPlayerName = String.valueOf(secondPlayer.getText());
savedInstanceState.putString("firstPlayerName", firstPlayerName);
savedInstanceState.putString("secondPlayerName", secondPlayerName);
}
}
When I debugged it, I did notice it passed thru onSavedInstance and it did save the values, but once in onCreate, the savedInstanceState is null.
Any advice?
Thanks in advance & take care people.
Fares.
You note that the "cancel button enables an Intent to go from B to A.". This sounds like you're creating a new instance of Activity A (so your activity stack goes A, B, A), and the instance state is specific to the individual instance.
Instead, you should return to A by simply calling finish() on B. This will return to the original instance of A, which will have your data.

How to start a new activity and start a method in that activity

So I'm working with Java in android studio and I want to start a new class from a different class (I'm in ListenerServiceFromWear and want to start MainActivity) and once Mainactivity is started I want to start a method (startEmergencyMode();) in Mainactivity.
How do I do this from ListenerServiceFromWear?
Start MainActivity with an intent and in the extra of the intent put some flag that will tell MainActivity to call startMergencyMode()
Intent intent = new Intent(this, Mainactivity.class);
intent.putExtra("isEmergency", true);
startActivity(intent);
And then in Mainactivity actually call startEmergencyMode()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
Intent intent = getIntent();
boolean isEmergency = intent.getBooleanExtra("isEmergency", false);
if(isEmergency){
startEmergencyMode();
}
}
I don't quite understand what you mean by "start"
In java, you either:
Declare a static field or method
Create an instance of an object and use its public fields and methods.
If you wish to just have one 'instance' of MainActivity, use a static method:
public static void startEmergencyMode() {
// Code here
}
Which you can call anywhere using MainActivity.startEmergencyMode().
Keep in mind that this static method can only access static fields and other static methods.
If you wish to create an instance of MainActivity, simply create one and call the method:
public void startEmergencyMode() {
// Code here
}
// Somewhere else
MainActivity activity = new MainActivity();
activity.startEmergencyMode();
If you don't understand the difference between a static and non static method or field, refer the answer on this thread: What does 'public static void' mean in Java?

How do I use both CordovaActivity and AppCompatActivity in Android java code?

I'm making a Cordova plugin so I need to extend the MainActivity class with CordovaActivity. I also need to use AppCompatActivity. In a native app I extended MainActivity with AppCompatActivity and everything worked fine but in my Cordova plugin I'm not able to extend twice.
I'm trying to launch some code to keep running in the background. When I try this within onCreate:
appCompat = new AppCompatActivity();
Intent intent = new Intent(this, MyClass.class);
appCompat.startService(intent);
I define global variable:
private AppCompatActivity appCompat;
I get an error at runtime about the context (appCompat) being null. This is the actual error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
Does anyone know how I can use AppCompatActivity without using it as an extension?
(edit: I've attached the whole class for the sake of clarity)
public class MainActivity extends CordovaActivity {
private AppCompatActivity appCompat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context context = this.getBaseContext();
Intent intent = new Intent(context, MyClass.class);
appCompat = new AppCompatActivity();
appCompat.startService(intent); // CAUSES CRASH AT RUNTIME
}
}
I updated CordovaActivty class to extend AppCompatActivity, as i had to deal with Toolbar.
I'm not sure if its the right approach, but it works fine for me.
Well it turns out I don't need to use AppCompatActivity to run services in the background. I can simply use:
Intent intent = new Intent(this, MyClass.class);
startService(intent)
and it works just fine.

proper android activity flow?

I am trying to wrap my head around what proper activity flow convention is.
I currently have:
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
//do stuff
//clicklisteners setup etc
Intent intent = new Intent(this, ExampleActivity.class);
//putExtras
startActivity(intent);
}
}
public class ExampleActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
//getExtras
//objectA state lives here
//do stuff
}
}
If the user presses back when on the ExampleActivity view, and then clicks another listener that takes them to ExampleActivity, I want to be able to access "objectA" state again. How do I implement this? I am not understanding onResume or onRestart...
are these the methods to call? or is there a better convention to navigate the app activities?
Android has a mechanism for having an activity pass results back to the prior activity that started it. The documentation for that is here.
Basically, you use startActivityForResult to start the second activity, the second activity uses setResult to set results, and the first activity receives those results in the onActivityResult callback when the second activity finishes.
If the user presses back when on the ExampleActivity view, the ExampleActivity is dead and user is back in the MainActivity, which calls "onResume".
When your are back from activity1 to activity2, activity2's onResume method is called.
With that being said, after the user closed ExampleActivity objectA is destroyed.

Using buttons on android - newbie

I am a newbie to android development, trying to get buttons working. every time i use this code below, the error message "unfortunately the app has stopped". but when i remove the code the app runs but obviously the buttons do nothing. here is the code ive tried
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button) findViewById(R.id.ExerciseButton);
button1.setOnClickListener (new View.OnClickListener(){
public void onClick(View v) {
setContentView(R.layout.exercises);
}
});
}
}
anybody able to help me out there? thanks
Don't try to load another View in the current activity. Navigate to a new ExercisesActivity.
Use:
public void onClick(View v) {
Intent intent = new Intent(ExercisesActivity.this, WcActivity.class);
startActivity(intent);
}
You can't call setContentView anymore after the view has loaded (which it obviously has to receive button clicks). Use a different approach, like showing and hiding views or using a ViewFlipper (see Calling setContentView() multiple times), using fragments (see Fragments) or starting a new activity.
Well, from your code, I see a couple of things:
I am usually familiar to using the onClickListener of the Button class if I want to use it for a button. Makes sense, doesn't it?
buttonOne.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
//Do stuff here
}
Second thing:
Start a new Activity (if that is what you want) by using an Intent:
Intent myIntent = new Intent(this, exercises.class);
startActivity(myIntent);
You CAN absolutaly call setContentView on any event, even after the view has loaded
I tried your code in a demo project and it is working fine. So, i think the error will be some where in your layout.(Let me know more if you need more help on this)

Categories