how can i call a method from another class in libgdx - java

I want to call the method walo() from render() in classMyGdxGame:
public class MyGdxGame extends ApplicationAdapter{
public void render() {
walo();
}
}
public class AndroidLauncher extends AndroidApplication {
AndroidLauncher android =new AndroidLauncher();
public void walo() {
Toast.makeText(getApplicationContext(), "You Don't Have Enough Money",
Toast.LENGTH_LONG).show();
}
}

Create interface in core, implement this interface in AndroidLauncher and send it to game.
So you can call method or pass data to render.
Interface:
public interface SomeInterface {
public void walo();
}
AndroidLauncher:
public class AndroidLauncher implements SomeInterface{
#Override
protected void onCreate() {
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
initialize(new MyGdxGame(this), config);
}
public void walo() {
Toast.makeText(getApplicationContext(), "You Don't Have Enough Money",
Toast.LENGTH_LONG).show();
}
}
In game class
public MyGdxgame(SomeInterface myinterface) {
this.myinterface=myinterface;
}
public render() {
myinterface.walo()
}
Here's example (my google play service interface) and a link to open source data of my libgdx game.
public interface PlayServices
{
public void signIn();
public void signOut();
public void rateGame();
public void unlockAchievement(String str);
public void submitScore(int highScore);
public void submitLevel(int highLevel);
public void showAchievement();
public void showScore();
public void showLevel();
public boolean isSignedIn();
public void showBannerAd();
public void hideBannerAd();
public void showInterstitialAd (Runnable then);
public void showRewardedVideo();
public boolean isRewardEarned();
}
You can see ads and video rewards implemented like this.
Github Connect Game

Related

How do I implement interstitial ads to show after X amount of times a player switches to the gameover screens?

So, I am new to AdMob and I am trying to figure out how to display an interstitial ad after the player dies and goes to the game over screen X amount of times. I have my AdMob set up in my AndroidLauncher class, however, my other classes do not have the ad variables. this is what my AndroidLauncher class looks like currently. If it helps, my game is set up with game states, 0 is before game starts, 1 is currently playing, and 2 and 3 are both game over states that send the player to the game over screen.
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {}
});
ad = new InterstitialAd(this);
ad.setAdUnitId("ca-app-pub-2188258702xxxxxxxxxxx");
ad.loadAd(new AdRequest.Builder().build());
ad.setAdListener(new AdListener(){
#Override
public void onAdLoaded() {
// Code to be executed when an ad finishes loading.
if (ad.isLoaded()) {
ad.show();
}
}
#Override
public void onAdFailedToLoad(int errorCode) {
// Code to be executed when an ad request fails.
}
#Override
public void onAdOpened() {
}
#Override
public void onAdLeftApplication() {
// Code to be executed when the user has left the app.
}
#Override
public void onAdClosed() {
}
}); ```
I am not sure if this is the best way but I can explain my way of doing it. This may help.
1) Create an Interface for Adservice
public interface AdService {
void showOrLoadInterstital();
void showBanner();
void hideBanner();
void showRewardedAd();
boolean hasVideoLoaded();
boolean checkAdWatched();
}
2) Implement this interface from your AndroidLauncher class and have a constructor of your base Game Class with this ad interface. From your androidlauncher class, refer to this constructor. Also generate the interface classes. ( I am only posting relevant parts).
public class AndroidLauncher extends AndroidApplication implements AdService {
#Override
protected void onCreate(Bundle savedInstanceState) {
// rest of the code here
setUpInterstitial();
View gameView = initializeForView(new MainGameClass(this), config);
}
private void setUpInterstitial() {
interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(AD_UNIT_ID_INTERSTITIAL);
loadIntersitialAd();
}
private void loadIntersitialAd() {
AdRequest.Builder builder = new AdRequest.Builder();
AdRequest interstitialRequest = builder.build();
interstitialAd.loadAd(interstitialRequest);
}
#Override
public void showOrLoadInterstital() {
runOnUiThread(new Runnable() {
public void run() {
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
loadIntersitialAd();
}
#Override
public void onAdFailedToLoad(int i) {
loadIntersitialAd();
}
});
interstitialAd.show();
adWatched=false;
}
});
}
}
3) Call the ad when you want to show it.
if (MainGameClass.adService != null) {
RunnableAction playWooshAction = Actions.run(new Runnable() {
#Override
public void run() {
MainGameClass.adService.showOrLoadInterstital();
}
});
playWooshAction.run();
}
4) For showing ad after X amount of time, just set a timer.

Android Beacon - Issue with bind/unbind(this)

I'm trying to create my own "BeaconManager" to develop different actions more easily.
So I've created a new class and I've implement "BeaconConsumer" and its functions :
public class MybeaconManager implements BeaconConsumer{
private BeaconManager beaconManager;
private final String TAG = "MybeaconManager";
private boolean mEnterArea = false;
private boolean mAlreadyArea = false;
public MybeaconManager(Context ctx){
beaconManager = BeaconManager.getInstanceForApplication(ctx);
beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
beaconManager.bind(this);
}
public void bindBeacon(BeaconConsumer consumer){
beaconManager.bind(consumer);
}
public void unBindBeacon(BeaconConsumer consumer){
beaconManager.unbind(consumer);
}
public boolean isEnterInArea() {
return mEnterArea;
}
public boolean isAlreadyInArea() {
return mAlreadyArea;
}
public void sendNotification(String Notif) {
}
#Override
public void onBeaconServiceConnect() {
beaconManager.addMonitorNotifier(new MonitorNotifier() {
#Override
public void didEnterRegion(Region region) {
mEnterArea = true;
}
#Override
public void didExitRegion(Region region) {
mEnterArea = false;
}
#Override
public void didDetermineStateForRegion(int i, Region region) {
}
});
}
Next to this, I have my MainActivity :
public class MainActivity extends Activity {
MybeaconManager mybeaconManager;
BeaconManager beaconManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mybeaconManager = new MybeaconManager(this);
if (mybeaconManager.isEnterInArea()){
Log.i("BeaconTest", "I'm detecting a Beacon");
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mybeaconManager.unBindBeacon((BeaconConsumer) this);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
}
So as you can see, I'm trying to use the functions didEnterRegion/didExitRegion more easily in a way that I only have to use on line in my MainActivity code.
The problem is, the bind/unbind(this) don't compile well and I think it's because I don't implement "BeaconConsumer" on the MainActivity because he can't get the consumer right.
It's telling me : "Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference" and return me on the bind thing.
So do you have any ideas on how I can deal with this in a way that I keep my beaconManager ?
Thank you in advance.
PS : Sorry if my English is not perfect
BeaconConsumer interface is designed to be implemented by an Activity or Service class. If you want to implement this interface in a POJO as shown in the question, you need to chain the method definitions shown below.
#Override
public Context getApplicationContext() {
return getActivity().getApplicationContext();
}
#Override
public void unbindService(ServiceConnection serviceConnection) {
getActivity().unbindService(serviceConnection);
}
#Override
public boolean bindService(Intent intent, ServiceConnection serviceConnection, int i) {
return getActivity().bindService(intent, serviceConnection, i);
}
I suspect your code already has empty implementations of these methods, otherwise your code would not compile. Make sure you have provided full implementations as shown above.

Listener doesn't work..It seems the Listener is 0

Hey Guys I have this as MainActivity:
public class LoginActivity extends AppCompatActivity {
public interface LoginListener {
public void onLoginSuccess();
}
public void onLoginSuccess() {
//logged in and do a few other things
}
}
And that's my second Activity from where I want to call the method onLoginSuccess() in my MainActivity, as you can see I am doing this with an Listener...
public class FingerprintHandler extends FingerprintManager.AuthenticationCallback {
private LoginActivity.LoginListener mListener;
public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
if (mListener != null) {
mListener.onLoginSuccess();
}
else{
Toast.makeText((Activity)context, "Listener is 0", Toast.LENGTH_LONG).show();
}
}
}
MY problem is that I everytime I try it I get back: "Listener is 0" from my Toast...SO what's wrong?
Extension of my comment above:
You need to register the mListener somehow. A pattern to do this is:
public class MyHandler {
private LoginListener mListener;
public MyHandler(LoginListener listener) {
mListener = listener;
}
// ... etc...
}
Where LoginListener is:
public interface LoginListener {
public void onLoginSuccess();
}
And your activity has:
public MyActivity implements LoginListener {
// instantiate the handler somewhere, with a reference
// to "this". "this" refers to the LoginListener interface
// which is implemented.
#Override
public void onCreate(Bundle b) {
mHandler = new MyHandler(this);
}
#Override
public void onLoginSuccess() {
Log.i(TAG, "Kewel beanZ");
}
}
Or, you can define LoginListener as an interface inside the activity if you wish, and instantiate it as:
public LoginListener mListener = new LoginListener() {
#Override
public void onLoginSuccess() {
Log.i(TAG, "Sweet sweet baby beanz");
}
};
And instead of using this, use mListener, when you create MyHandler.
Check below code for Fingerprint authentication in Android
https://gist.github.com/Evin1-/6aca8421903acca0e927eaefd85bd617

Android: Play next cued video in onVideoEnd()

I have a Youtube player within my app. I have set a setPlayerStateChangeListener for this player, and on the event of the video ending (onVideoEnd()) I wish to play the next cued video.
This is what I have so far...
YouTubeFragment
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean restored) {
...
player.setPlayerStateChangeListener(myPlayerStateChangeListener);
...
}
MyPlayerStateChangeListener
package x;
import android.util.Log;
import com.google.android.youtube.player.YouTubePlayer;
public final class MyPlayerStateChangeListener implements YouTubePlayer.PlayerStateChangeListener {
#Override
public void onAdStarted() {
}
#Override
public void onError(
com.google.android.youtube.player.YouTubePlayer.ErrorReason arg0) {
}
#Override
public void onLoaded(String arg0) {
}
#Override
public void onLoading() {
}
#Override
public void onVideoEnded() {
Log.d("onVideoEnded()", "Video has ended");
}
#Override
public void onVideoStarted() {
}
}
When the video ends, the log message within onVideoEnded() successfully displays. What I am struggling to get my head around is how I can run hasNext(), play() etc on my youtube player from within this PlayerStateChangeListener.
Actually you can use the following :
private static YouTubePlayer player;
In onInitializationSuccess() set this variable.
this.player = player;
Now in the callback onVideoEnd() use the static version of the player to perform the actions that you need like cueing a new video.

How to call a method defined in an Activity class from a (non-activity) Java class

In my DataTrak activity I defined the following method:
public void updateTotal(IAmount totalAmount, int transactionType) {
switch (transactionType) {
case AccountTotals.VALUE_CANCELS:
txtView_cancels_value.setText("" + (Long.parseLong(txtView_cancels_value.getText().toString()) + totalAmount.getValue()));
break;
case AccountTotals.VALUE_PAYS:
txtView_pays_value.setText("" + (Long.parseLong(txtView_pays_value.getText().toString()) + totalAmount.getValue()));
break;
case AccountTotals.VALUE_SALES:
txtView_sales_value.setText("" + (Long.parseLong(txtView_sales_value.getText().toString()) + totalAmount.getValue()));
break;
default:
break;
}
btn_total.setBackgroundResource(R.drawable.button_green );
}
The method computes and updates some TextViews and changes the color of a button. Then I need to call this method from a Java abstract class. The method call appears in a method that runs on a non-UI thread. Here's how I call the method:
new Thread()
{
public void run()
{
new DataTrak().runOnUiThread(new Runnable()
{
public void run()
{
new DataTrak().updateTotal(totalAmount,transactionType);
}
});
}
}.start();
The problem is that I get a run time exception. Here's the LogCat output:
05-13 16:52:13.325: E/AndroidRuntime(22101): FATAL EXCEPTION: Thread-1577
05-13 16:52:13.325: E/AndroidRuntime(22101): Process: com.ilts.lct, PID: 22101
05-13 16:52:13.325: E/AndroidRuntime(22101): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
05-13 16:52:13.325: E/AndroidRuntime(22101): at android.os.Handler.<init> (Handler.java:200)
05-13 16:52:13.325: E/AndroidRuntime(22101): at android.os.Handler.<init>(Handler.java:114)
05-13 16:52:13.325: E/AndroidRuntime(22101): at android.app.Activity.<init>(Activity.java:786)
05-13 16:52:13.325: E/AndroidRuntime(22101): at com.ilts.lct.ap.mainframe.DataTrak.<init>(DataTrak.java:37)
05-13 16:52:13.325: E/AndroidRuntime(22101): at com.ilts.lct.ap.customerfunctions.CustomerTransaction$2.run(CustomerTransaction.java:736)
In fact, initially I had just the line with the method call but I got the same run time exception. I searched for "Can't create handler inside thread that has not called Looper.prepare()" and I found several posts on this issue. One of them made me put the method call inside a new Thread, as shown above. But I still get the same run time exception. What should I change? Could you help me understand what's the problem actually and how to fix it? Thanks in advance.
After I read the answer by #Metero here's the code in the Java abstract class:
public abstract class CustomerTransaction extends Transaction {
...................................................
public interface CallBack {
public void updateTotal(IAmount a,int n);
}
private static CallBack callback;
public static void registerCallback(CallBack callback1){
callback = callback1;
}
/**
* Method to update the transaction state
*
* #param state The new transaction state
**/
public void setState(final int state) {
this.state = state;
/*
* Update the status
*/
if (state == TRANSACTION_COMPLETE) {
new Thread()
{
public void run() {
Looper.prepare();
new DataTrak().runOnUiThread(new Runnable()
{
public void run() {
Log.i("HERE", "HERE");
Looper.prepare();
callback.updateTotal(totalAmount,transactionType);
Looper.loop();
}
});
}
}.start();
}
}
....................
}
The very nature of this question suggests a MVC violation. Instead of your model calling methods in an Activity, it should call a method on some callback that the Activity has registered on the model. This callback should be queued in the UI thread.
You should never instantiate an Activity by yourself, if you do that, it won't be a normal activity, it will be just a problematic plan Java object.
So what you can maybe to to solve your problem is use the Observer pattern where you can define an interface with the 'callback' method and you let the Activity implement it and make it subscribe to the 'provider' of the notification. So basically, when this update Thread is running, you will run thru the list of subscribed listeners and dispatch the call, it will be just like a normal method call.
Just keep in mind to: 'subscribe' and 'unsubscribe' respecting the Activity lifecycles..like subscribe on onCreate() and unsubscribe on onDestroy().
Activity:
public class YourActivity extends Activity implements ControlListener {
public void onCreate(...) {
....
control.registerListener(this);
control.performOperation();
}
public void onDestroy(...) {
....
control.unregisterListener(this);
}
public void updateTotal(String newValue) {
runOnUiThread(new Runnable() {
public void run() {
textView.setText(newValue);
}
});
}
}
Control class:
public class Control {
private Set<ControlListener> listeners = new HashSet<ControlListener>();
public synchronized void registerListener(ControlListener listener) {
listeners.add(listener);
}
public synchronized void unRegisterListener(ControlListener listener) {
listeners.remove(listener);
}
public synchronized void notifyListeners(String newValue) {
for(ControlListener listener : listeners) {
listener.updateTotal(newValue);
}
}
public void performOperation() {
new Thread() {
public void run() {
String newValue= service.performBackgroundOperationToGetNewValue();
notifyListeners(newValue);
}
}.start();
}
}
Control listener:
public interface ControlListener {
public void updateTotal(String newValue);
}
Alternatively, you can use a very HANDY library to apply the Observer pattern on your project, it's the Otto: http://square.github.io/otto/ With the Otto, you wouldn't need to have the register/unregister/notifylisteners methods in your control, it would be placed somewhere else automatically.
This is not the best choice.
new Thread()
{
public void run()
{
new DataTrak().runOnUiThread(new Runnable()
{
public void run()
{
Looper.prepare();//This is not the best choice.
new DataTrak().updateTotal(totalAmount,transactionType);
}
});
}
}.start();
I recommend use AsyncTask, like this.
class SampleTask extends AsyncTask<Boolean, Boolean, Boolean> {
private int totalAmount;
private yourActivity activity;
//passing parameters
public void SampleTask(yourActivity activity){
this.activity = activity;
}
#Override
protected Boolean doInBackground(Boolean... params) {
while (totalAmount < 10){
totalAmount++;
}
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
// this is not the best choice
// because you are creating two instances.
new DataTrak().updateTotal(totalAmount,transactionType);
//If you pass a parameter, this for me is the best option.
activity.updateTotal(totalAmount,transactionType);
}
}
I agree #Alécio, please use a callback to do this. Add a callback interface in the non-activity class:
class yourclass{
public interface callBack{
public void updateTotal(...);
}
private callBack callback;
public void registerCallback(callBack callback){
this.callback = callback;
}
//somewhere call the updateTotal(...)
callback.updateTotal(...);
}
In the Activity
//the activity implement the callback and then register it, and call the callback when neccesary
class yourActivity extends Activity implement callBack{
#Override
onCreate(...){
...
yourclass.registerCallback(this);
}
#Override
public void updateTotal(...){
.......
}
}
The sample code for multiple class comunicating.
public class Controller {
callBack callBack;
public void registerCallBack(callBack back){
this.callBack = back;
}
public void show(){
callBack.update(1, "my name");
}
public interface callBack{
public void update(int type, String message);
}
public callBack getCallBack(){
return callBack;
}
}
public class AnotherClass {
Controller controller = new Controller();
public void registerCallBack(callBack back){
controller.registerCallBack(back);
}
public void show(){
controller.getCallBack().update(1, "show me!");
}
}
public class MyActivity extends Activity implements callBack {
AnotherClass myclass = new AnotherClass();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("TAG", "This is message!");
setContentView(R.layout.main);
myclass.registerCallBack(this);
}
#Override
protected void onResume() {
super.onResume();
myclass.show();
}
#Override
public void update(int type, String message) {
((TextView) findViewById(R.id.display)).setText(message);
}
}

Categories