android execute method from another activity - java

I am calling from activityA a method that is on activityB.
Method is called from A to B properly but when I execute inside it webviewB.loadUrl(myUrl), app crashes for a nullpointerexception. Same webviewB method, if executed from activityB, works properly. Probably is done because context, when calling from A to B must be set, but how? Which is the best way to do it? Thank you.
ActivityA (tabHost) and ActivityB (tabcontent) are initialized properly and webview from ActivityB shows URL1.
Then when evet from ActivityA is recived, I need to load URL2 on webview from ActivityB.
EDIT:
when event is received on ActivityA,
ActivityB test = new ActivityB();
test.recalcula();
ActivityB,
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.vistaaib);
webviewB = (WebView) findViewById(R.id.webviewB);
webviewB.loadUrl(URL1);
...
public void recalcula (){
webviewB.loadUrl(URL2);
}

Either intents as suggested by Ortisi. Or Why don't you try creating a class, create that method in this class, And call that method from both the activity.

The best way to communicate between activities is using the Intent mechanism.
So just launch an intent from activityA in order to communicate to activityB that its loadUrl method should run.
Or for other solutions you can read this question:
Best way to accomplish inter-activity communication in an Android TabHost application

Related

I am trying get back to previous activity but i get my menu activity

this is my main activity---(1)
enter image description here
here activity I want to go back to---(2)
enter image description here
here from where i want back---(3)
enter image description here
why when I use in previous btn I get my main activity and also when I make a btn to get previous I get my main activity
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateUI();
}
});
}
private void updateUI() {
Intent regTrip = new Intent(getApplicationContext(), regTrip.class);
startActivity(regTrip);
finish();
}
You can try to create a new Intent, but instead of using Application Context, try using the name of the current activity you are in. For example, if the name of the current Activity was 'NewActivity', you would say:
startActivity(new Intent(NewActivity.this, regTrip.class));
This would take you from the 'NewActivity' page to the 'regTrip' page.
Also you can just try adding onBackPressed() inside of your onClickListener. This is the built in method by android which is run when the user presses the back button on their phone. This means that when the user presses your back button, they are essentially doing the same thing as pressing the back button on their phone.
Toast and Intent, both requires reference to context. And getApplication, getApplicationContext, LoginActivity.this and getBaseContext, they all offer reference to the context.
Now the thing confuses is the declaration of different contexts and their specific-usage. To make things simple, you should count two types of context available in the Android framework.
Application Context
Activity Context
Application context is attached to the application's life-cycle and will always be same throughout the life of application. So if you are using Toast, you can use application context or even activity context (both) because a toast can be raised from anywhere with in your application and is not attached to a window.
Activity context is attached to the Activity's life-cycle and can be destroyed if the activity's onDestroy() is raised. If you want to launch a new activity, you must need to use activity's context in its Intent so that the new launching activity is connected to the current activity (in terms of activity stack). However, you may use application's context too to launch a new activity but then you need to set flag Intent.FLAG_ACTIVITY_NEW_TASK in intent to treat it as a new task.
Now referring to your cases:
LoginActivity.this though its referring to your own class which extends Activity class but the base class (Activity) also extends Context class, so it can be used to offer activity context.
getApplication() though its referring to Application object but the Application class extends Context class, so it can be used to offer application context.
getApplicationContext() offers application context.
getBaseContext() offers activity context.
Go for activity context when using Intent and for toast you can use any context.

Communication Between Two Android Activities via Reference to Caller or Callee

I have two activities Activity A and Activity B inside of the same application and they need to be able to call methods on each other. A needs to communicate to B at the start (possibly see "code" below).
B will call a lot of methods on A (this means that I cannot use the startActivityForResult method for communication because this would close B (Activity B is a Bluetooth Client and Server because it is a Peer to Peer app)). I do use startActivityForResult to start B for more of a kill signal than anything as the result.
Activity A uses a SupportMapFragment and Activity B cannot be a fragment because I want to be able to switch from B to A and then never use B again.
Originally, I started with one activity and tried switching between views using a ViewFlipper and just a call to setContentView(R.layout.my_layout_A) or setContentView(R.layout.my_layout_B). The fragment of course caused a lot of problems for both.
Using Fragments were confusing. The SupportMapFragment is the code for a Google Map which is a Fragment.
When I click a menu option inside of the MapsActivity (Activity A), I would like to be able to start myBluetoothActivity (Activity B) with a reference to the MapsActivity (Activity A) OR start myBluetoothActivity and then be able to set a reference to the caller inside of myBluetoothActivity (but this option would require having a reference to the BluetoothActivity inside of the MapsActivity or having some way to obtain the started activity from the intent).
//the following code is in Kotlin, but this can easily be converted over to java:
//option A: (pass it inside of the constructor)
var mbta:myBluetoothActivity = myBluetoothActivity(this)
//line for intent that I am unsure of
//intent so that I can start the activity with the pointer to the caller already passed into the new activity
startActivity(mbta)
//option B: (set this reference after obtaining a reference from intent):
var mintent:Intent = Intent(this.applicationContext, myBluetoothActivity::class.java)
startActivity(mintent)
//obtain the reference to the BluetoothActivity from the intent (NOT SURE HOW TO DO THIS???)
mbta.setCallerReference(this)
How can I accomplish this communication between the two activities via reference between the two activities? Should I use an interface for communication? If I should use it, (which I did try) how should I?
In other words, I am trying to access the caller activity (Activity A) from (Activity B) directly via a reference to Activity A inside of B OR trying to get the reference to B from the intent that started it inside of Activity A. I am trying to get a reference to that, so I can use it for communication/method calling/member variable and UI modification purposes.
NOTES: 1. The BluetoothActivity and the MapsActivity are NOT SERIALIZABLE. I tried serializing it and then adding it to the extras Bundle in the Intent and it just crashed saying that that was impossible to serialize due to BroadCastReciever. As this also deals with WIFI. Which I am highly considering separating out to be put with the BluetoothActivity in a future release.
I am also ASSUMING that Activity B will never just be started up by anything other than my MapsActivity class.
I am also new to Kotlin, but I know Java.
When I tried using an interface, I caused a StackOverflow error and I have no idea why.
I have read the documentation for Intents on the website.
I have done some research on here which gave me those ideas above. I am not sure how to implement them.
You are using the wrong approach. The solution requires a bit more work than you would think. The correct approach is to:
First, realize that these activities Activity A and Activity B (and any other activities) are activities that are specific to your application and you want to establish direct communication between them.
Second, realize that you are trying to get the current (or a previous) activity's context. The context will help serve the reference.
Third, you can create your own Activity and Application classes by extending the desired classes. The Application class is a low-level class used for the activities.
From here, you will be able to make use of the getApplicationContext() which will return your custom Application class.
Design: It is inside of your CustomApplication class that you must track the references to the activities that you want. From there all that you have to do is cast the getApplicationContext() to your CustomApplication class and then call your methods that access the Activity(ies). You must of course cast your Activities if you want to access certain instances of a specific activity that you created to its "type." For example:
MapsActivity mact = (MapsActivity)(((MyApplication)(this.getApplicationContext())).getCurrentActivity())
You must of course note that this activity must be already created (the onCreate method was already called) for this to return the current activity. The same of course goes for the other life-cycle methods for the activity as you will make a baseActivity which will deal with these as well as you will also have an Application life-cycle that will help deal with this too.
To answer the question: "How to get the current foreground activity context in android?" I turned to StackOverflow and found user: gezdy 's answer to be exactly what I needed at: How to get current foreground activity context in android?.
(BEGIN QUOTATION FROM: GEZDY)
You should manage activities references. Add the name of the
application in the manifest file :
<application
android:name=".MyApp"
....
</application>
Your application class :
public class MyApp extends Application {
public void onCreate() {
super.onCreate();
}
private Activity mCurrentActivity = null;
public Activity getCurrentActivity(){
return mCurrentActivity;
}
public void setCurrentActivity(Activity mCurrentActivity){
this.mCurrentActivity = mCurrentActivity;
}
}
Create a new Activity :
public class MyBaseActivity extends Activity {
protected MyApp mMyApp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMyApp = (MyApp)this.getApplicationContext();
}
protected void onResume() {
super.onResume();
mMyApp.setCurrentActivity(this);
}
protected void onPause() {
clearReferences();
super.onPause();
}
protected void onDestroy() {
clearReferences();
super.onDestroy();
}
private void clearReferences(){
Activity currActivity = mMyApp.getCurrentActivity();
if (this.equals(currActivity))
mMyApp.setCurrentActivity(null);
}
}
So, now instead of extending Activity class for your activities, just
extend MyBaseActivity. Now, you can get your current activity from
application or Activity context like that :
Activity currentActivity = ((MyApp)context.getApplicationContext()).getCurrentActivity();
(END OF QUOTATION FROM: GEZDY)
Note: All code is written in java for this answer.

How the setcontentview is called?

I was tweaking the sample hello world app that android studio provides and found out that I cannot call the setContentView(R.layout.activity_main); outside any method.For example:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
setContentView(R.layout.activity_main); //compilation error
}
I know that I should not be calling setContentView outside onCreate(),but just for a reference I tried it out.I can figure out that this has something to do with Java and not android,but I can't seem to figure out the where the problem exactly lies.Any help will be appreciated.
As per activity life cycle onCreate() is the method called when the activity is first created
OnCreate() is the point where most initialization should go: calling setContentView(int) to inflate the activity's UI, using findViewById to programmatically interact with widgets in the UI, calling managedQuery(android.net.Uri , String[], String, String[], String) to

Android: How to set a listener for Acivity.onNewIntent()?

I'm writting my own plug-in for an existing game engine (so to say it's 3rd-party lib in relation to the main application).
So, I have no access to the MainActivity sources.
Nevertheless I have to react somehow on main activity lifecycle events (onCreate, onDestroy, onPause, onResume, onNewIntent and some unimportant others).
Thanks to Application.ActivityLifecycleCallbacks, I have no problems with most of them.
The problem occurs with onNewIntent(). I can't find out a listener for this event and imagine a way to handle it.
Does anybody know how to catch onNewIntent event (surely, except overriding it)?
onNewIntent() works for singleTop or singleTask activities which already run somewhere else in the stack. if the MainActivity is not declared with singleTop or singleTask attributes, even if you use below code, it won't work:
#Override //won't be called if no singleTop/singleTask attributes are used
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// ...
}
To assure all setup logic hooked, it is best use onResume() by utilizing getIntent().
#Override
protected void onResume() { //will be called in any cases
super.onResume();
// getIntent() should always return the most recent
}

Cannot set the view from activity android

I am facing a strange problem suddenly in android. I am creating layout .xml file in res>layout but from a class that extends activity, I can not access it. I have done this several a time but I can not figure out this strange problem. I restarted the eclipse, even the computer but no. When I go for setting the contentView it says something as below :
The method onCreate(Bundle) of type MainActivity must override or implement a supertype method
That is let I have created an xml file at res>layout named "whynot.xml" and from a activity when I try to set it like
setContentView(R.layout.whynot);
It shows red mark below and the above message.
you have to extends Activity and call super.onCreate(savedInstanceState) in the onCreate. For each callback of the Activity's lifecycle is mandatory to call its super
As the error says,
must override or implement a supertype method
you need the super call like
#Override
protected void onCreate(Bundle bundle)
{
super.onCreate(bundle); // here
setContentView(...);
...
}

Categories