how to call a function from other activity android - java

In my Android app I have two activities :
1) MapsActivity
2) OtherActivity
MapsActivity has navigation drawer through which I opened OtherActivity . Now , I want to call a method (like updatemap() ) from MapsActivity .
After searching a lot on google I found this question on stackoverflow
How to call method in main activity from other activity? but that doesn't solves my problem .
UPDATE :
Here is the code for OtherActivity :
public class OtherActivity extends AppCompatActivity {
#Override
protected void attachBaseContext(Context newBase) {.....}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.... }
#Override
protected void onStart() {
super.onStart();
removeConnection(userID)
.... }
private void removeConnection(String currentUserId) {
...
// Here I want to call a function from MapsActivity i.e. disaplayLocation()
}
public static class ConnectedViewHolder extends
RecyclerView.ViewHolder{ ... }
}
Code for MapsActivity is :
public class MapsActivity extends AppCompatActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
#Override
protected void attachBaseContext(Context newBase) { ... }
#Override
protected void onCreate(Bundle savedInstanceState) { ... }
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull
String[] permissions, #NonNull int[] grantResults) { ... }
private void setUpLocation() { ... }
public void displayLocation() { ... } // This is the function i want to call
private void createLocationRequest() { ... }
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) { ... }
protected synchronized void buildGoogleApiClient() { ... }
private boolean checkPlayServices() { ... }
private void requestRuntimePermission() { ... }
private void startLocationUpdates() { ... }
#Override
public void onMapReady(GoogleMap googleMap) { ... }
#Override
public void onConnected(#Nullable Bundle bundle) { ... }
#Override
public void onConnectionSuspended(int i) { ... }
#Override
public void onConnectionFailed(#NonNull ConnectionResult
connectionResult) { ... }
#Override
public void onLocationChanged(Location location) { ... }
#Override
public boolean onCreateOptionsMenu(Menu menu) { ... }
#Override
public boolean onOptionsItemSelected(MenuItem item) { ... }
private void makeConnectionToGetLocation() { ... }
private void updateConnectedLatLng() { ... }
}
I am pasting only structure of code because it is 1000 line of code and pasting here is of no use and become more complicate to read .
I tried to add static keyword before displayLocation method but it gives error in variables within function and making every variable to global is not possible .

If MapsActivity is expecting a result from OtherActivity, you're better off with Getting Result From an Activity. Simply call OtherActivity via startActivityForResult() (instead of startActivity()):
static final int MAP_REQUEST = 1; // your request code
...
private void callOtherActivity() {
Intent intent = new Intent(this, OtherActivity.class)
startActivityForResult(intent, MAP_REQUEST);
}
Then in your MapsActivity, do this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MAP_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
updateMap();
}
}
}

Make a static function in one Activity like
public static double getVariance(double[] data)
{
double mean = getMean(data);
double temp = 0;
for(double a :data)
temp += (mean-a)*(mean-a);
return temp/data.length;
}
Then in another activity call it as:
double res = Activity1.getVariance(<your data>);
Hope it helps.

Be aware, you may get NullObjectRefernce if the other activity is closed.
to do it you can use public static method. so, you can call it from anywhere in the application.
in your activity add it.
public static void YOUR_NAME(){}
to call it in second activity add it.
try{
YOUR_ACTIVITY.YOUR_NAME();
}catch(Exception e){}
another solution, you can use EventBus library
https://github.com/greenrobot/EventBus

Related

Call a Function in a OnPreferenceClickListener

I am trying to call a function in a OnPreferenceClickListener which is defined in a another class. Since I have not managed to initialisation an interface in OnPreferenceClickListener. I have given an example code below:
public void onCreatePreferences(Bundle bundle, String s) {
ListPreference preference = findPreference(getString(R.string.settings_ble_choose_device_key));
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(#NonNull Preference preference) {
callFunctionInMainActivity();
return false;
}
});
}
How i can call a function witch is implement in a another class?
Thank you very much
Rene
You can implement an intent for this. Where you send a broadcast from your OnPreferenceClickListener class and implement a broadcast received in the other class to listen for this intent and invoke the method that you want. Here is an example:
public void onCreatePreferences(Bundle bundle, String s) {
ListPreference preference = findPreference(getString(R.string.settings_ble_choose_device_key));
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(#NonNull Preference preference) {
sendBroadcast(new Intent(Constants.ACTION_STOP_MAIN_SERVICE));
return true;
}
});
}
In your other class:
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action= intent.getAction();
if(action.equalsIgnoreCase(ConstantesIdentifiant.ACTION_STOP_MAIN_SERVICE)){
finishAffinity();
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(broadcastReceiver, new IntentFilter(ConstantesIdentifiant.ACTION_STOP_MAIN_SERVICE));
}
#Override
protected void onDestroy() {
unbindService(mConnection);
unregisterReceiver(broadcastReceiver);
super.onDestroy();
}

Java - Interface - How do I assign a specific interface in multiple activities all together

I have a service which has an interface, I'm implementing the interface callback in multiple activities, but because of I'm calling the app instance on every activity's onCreate, the interfaces are responding on the current activity only. How do I make sure they work all together in every activity.
MyApp.java
public class MyApp extends Application {
private static MyApp myApp;
#Override
public void onCreate() {
super.onCreate();
myApp = new MyApp();
}
#Contract(pure = true)
public static synchronized MyApp getInstance() {
MyApp myApp;
synchronized (MyApp.class) {
myApp = MyApp.myApp;
}
return myApp;
}
public void setCallBackListener(MyService.ReceiversCallbacks receiversCallbacks) {
MyService.receiversCallbacks = receiversCallbacks;
}
}
MyService.java
public class MyService extends Service {
public static MyService.ReceiversCallbacks receiversCallbacks;
public MyService() {
super();
}
public interface ReceiversCallbacks {
void onReceiveCallbacks(String data);
}
#Override
public void onCreate() {
super.onCreate();
Notification notification = new NotificationCompat.Builder(this, NOTIFICATION_ID)
.setContentTitle("Background service")
.setSmallIcon(R.drawable.ic_launcher)
.build();
startForeground(1, notification);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (MY_LOGIC) receiversCallbacks.onReceiveCallbacks("DATA_FROM_MY_LOGIC");
//stopSelf();
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
ActivityA.java
public class ActivityA extends AppCompatActivity implements MyService.ReceiversCallbacks {
#Override
protected void onCreate(Bundle savedInstanceState) {
MyApp.getInstance().setCallBackListener(this);
}
#Override
public void onReceiveCallbacks(String data) {
// calling important functions
}
}
ActivityB.java
public class ActivityB extends AppCompatActivity implements MyService.ReceiversCallbacks {
#Override
protected void onCreate(Bundle savedInstanceState) {
MyApp.getInstance().setCallBackListener(this);
}
#Override
public void onReceiveCallbacks(String data) {
// calling important functions
}
}
Each activity's onCreate when I do this MyApp.getInstance().setCallBackListener(this); The focus of the call back shifts to the new activity. But I want the focus in both or more activities at the same time, how do I do that? Is there any better way for the solution I want?
Please note these:
I don't want to call those functions onResume
I don't want to use Broadcasts
I just created different interfaces for each activity and registered them to their corresponding activity, and they worked!
MyApp.getInstance().setCallBackListener(this);

How to implement admob rewarded video ads in a list view?

I want to know how to implement AdMob rewarded video ads in a list view?
I'm using the source code from here
and I want to use it in this class StickerPackDetailsActivity.java
and the layout is gonna like this
![layout][1]
I want to lock add to WhatsApp and unlock it by watching video reward.
but this stickerdetails showed from listview from
![here][2]
so, how to implement video reward ads only in 1 specified item of the listview not all of them?
public class MainActivity extends AppCompatActivity implements RewardedVideoAdListener {
private RewardedVideoAd mRewardedVideoAd;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this,"ca-app-pub111111111");
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
listitem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadRewardedVideoAd();
}
});
}
private void loadRewardedVideoAd() {
mRewardedVideoAd.loadAd("ca-app-pub-",
new AdRequest.Builder().build());
}
#Override
public void onRewardedVideoAdLoaded() {
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoStarted() {
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoAd();
}
#Override
public void onRewarded(RewardItem rewardItem) {
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
}
#Override
public void onRewardedVideoCompleted() {
}
#Override
protected void onPause() {
mRewardedVideoAd.pause(this);
super.onPause();
}
#Override
protected void onResume() {
mRewardedVideoAd.resume(this);
super.onResume();
}
}

Android Studio: #Override "Annotations are not allowed here"

I want to implement the ...
#Override
public void onBackPressed() {
}
However, I get an error message saying, "Annotations are not allowed here". I need this method to be implemented here. Is there an alternative?
public class supbreh extends Appbreh
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intent_breh);
if (myBundle != null) {
String name = myBundle.getString("workout");
ShowDetails(name);
}
}
private void ShowAbDetails(String mName) {
if(mName.equals("abs1")){
#Override
public void onBackPressed() { //"Not Allowed here"
}
}
void onBackPressed ()
Called when the activity has detected the user's press of the back
key. The default implementation simply finishes the current activity,
but you can override this to do whatever you want.
In here you can't declare this method inside another method .
Only override it in that one Activity
#Override
public void onBackPressed()
{
super.onBackPressed();
}
FYI
#Override
public void onBackPressed() {
Intent intent = new Intent(IndividualAbsWorkout.this, IndividualAbsWorkout.class);
startActivity(intent);
}
You can override onBackPressed as normal and call the method in ShowAbDetails() method like below.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intent_breh);
if (myBundle != null) {
String name = myBundle.getString("workout");
ShowDetails(name);
}
}
private void ShowAbDetails(String mName) {
if(mName.equals("abs1")){
onBackPressed();
}
}
#Override
public void onBackPressed() {
// your logic here
}

How to react on the End of a SpeechRecognizer in a other class? Recognizer in extra class

community,
I'm programming in android and i have 2 classes, the mainactivity and a other class with a SpeechRecognizer(a listener).
I want to give the activity a sign that the listener is done with listining, how can i do that?
Should i extend the SpeechRecognizer-class with the mainActivity-class and then call a method from the mainActivity-class in the SpeechRecognizer-class?
Here is a simplified version of my code to understand my problem:
thirst class:
puplic class mainActivity{
onCreate(){
speech.startListening();
}
}
second class:
pulbic class speech implements Recognizer{
startListening(){
//start the listener
}
#Override
onResult(){
//hear i get my string after a random various amount of time
//(when the recognizer is done with hearing my stuff)
//at this point i want to let the other class know, that im done here
}
}
I hope you understand my problem, i think its an easy one, but i dont know a solution..
Greetings
Just call setRecognitionListener on your MainActivity.
public class MainActivity extends Activity {
SpeechRecognizer speech;
public void onCreate(){
super.onCreate();
speech.startListening();
recognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
}
}

Categories

Resources