Android-Libgdx, Calling Another Activity after the Game starts on Button click - java

I faced a major problem when I need to call another activity when the button is clicked after the Game is started. The Game is called via initiate(game, ) method from AndroidApplication interface.
In normal Activity, I can easily call the another Activity but it seems to be difficult to call another Activity from Libgdx class that implements AndroidApplication.
Could anyone suggest a proper method to call the Activity from Libgdx class that implements AndroidApplication interface?
I tried to do this for a week but it seems that my method is totally wrong..
Thanks in advance.

Define a callback interface in you LibGdx class, and use it to notify your AndroidLauncher to start the new activity.
For example in your LibGdx game class:
// Your Game class in the core package
public class MyGame extends Game {
// Define an interface for your various callbacks to the android launcher
public interface MyGameCallback {
public void onStartActivityA();
public void onStartActivityB();
public void onStartSomeActivity(int someParameter, String someOtherParameter);
}
// Local variable to hold the callback implementation
private MyGameCallback myGameCallback;
// ** Additional **
// Setter for the callback
public void setMyGameCallback(MyGameCallback callback) {
myGameCallback = callback;
}
#Override
public void create () {
...
}
...
private void someMethod() {
...
// check the calling class has actually implemented MyGameCallback
if (myGameCallback != null) {
// initiate which ever callback method you need.
if (someCondition) {
myGameCallback.onStartActivityA();
} else if (someOtherCondition) {
myGameCallback.onStartActivityB();
} else {
myGameCallback.onStartSomeActivity(someInteger, someString);
}
} else {
Log.e("MyGame", "To use this class you must implement MyGameCallback!")
}
}
}
Then ensure your AndroidLauncher implements the required interface:
// Your AndroidLauncher
public class AndroidLauncher extends AndroidApplication implements MyGame.MyGameCallback {
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
// create an instance of MyGame, and set the callback
MyGame myGame = new MyGame;
// Since AndroidLauncher implements MyGame.MyGameCallback, we can just pass 'this' to the callback setter.
myGame.setMyGameCallback(this);
initialize(myGame, config);
}
#Override
public void onStartActivityA() {
Intent intent = new Intent(this, ActivityA.class);
startActivity(intent);
}
#Override
public void onStartActivityB(){
Intent intent = new Intent(this, ActivityB.class);
startActivity(intent);
}
#Override
public void onStartSomeActivity(int someParameter, String someOtherParameter){
Intent intent = new Intent(this, ActivityA.class);
// do whatever you want with the supplied parameters.
if (someParameter == 42) {
intent.putExtra(MY_EXTRA, someOtherParameter);
}
startActivity(intent);
}
}

Related

What am i doing wrong when I try to call an activity outside an other activity in Android Java?

I Want to put all my methods in seperate classes to clean my code up when creating my Android App but i can seem to get it right.
In my MainActivity class i call the method from the importet class noteFunctionality onLongpress and OnDoubleTap.
#Override
public void onLongPress(#NonNull MotionEvent e) {
noteFunc.enterNote("2");
super.onLongPress(e);
}
#Override
public boolean onDoubleTap(#NonNull MotionEvent e) {
noteFunc.enterNote(2);
return super.onDoubleTap(e);
}
Then in my NoteFunctionality class i try start the a new activity class with the given int for the specifik activity, "I have more then one activity".
public void enterNote(int i) {
Class mainActivity = Class.forName("MainActivity" + i);
Intent secondActivityIntent = new Intent(this, mainActivity.class);
startActivity(secondActivityIntent);
}
What am I doing wrong?.
public void enterNote(Activity activity,Context context) {
//Class mainActivity = Class.forName("MainActivity" + i);
Intent secondActivityIntent = new Intent(context, activity.getClass());
startActivity(secondActivityIntent);
}
and when you call it
noteFunc.enterNote(MainActivity,yourActivity.this);
If you would like to trigger another Activity, it must be done through Context.
Therefore, you need to pass Context to your NoteFunctionality function to achieve your task.
MainActivity:
public class MainActivity extends Activity { // or extending any other form of Activity
NoteFunctionality noteFunc; // I assume you have properly assign it somewhere
#Override
public void onLongPress(#NonNull MotionEvent e) {
// You will have to pass also Context to enterNote function
noteFunc.enterNote(MainActivity.this, "2"); // You should pass an Integer instead of String here
super.onLongPress(e);
}
#Override
public boolean onDoubleTap(#NonNull MotionEvent e) {
noteFunc.enterNote(MainActivity.this, 2);
return super.onDoubleTap(e);
}
}
NoteFunctionality:
public class NoteFunctionality {
// You need to have Context here
public void enterNote(Context context, int i) {
Intent secondActivityIntent = new Intent(context, SecondActivity.class); // Replace your target Activity name with SecondActivity
context.startActivity(secondActivityIntent);
}
}

How can i use result in main activity

I am new user of android studio. I am using priority in manifest file and all required permissions but I do not know how can I use result in main activity, help me out.
public abstract class SmsBroadcastReceiver extends BroadcastReceiver {
protected abstract void onSmsReceived(SmsMessage smsMessage);```
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pduObjectList = (Object[]) bundle.get("pdus");
if (pduObjectList != null) {
for (Object pduObject : pduObjectList) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pduObject);
onSmsReceived(smsMessage);
}
}
}
}
}
The abstract keyword is a non-access modifier, used for classes and methods:
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from).
In your activity:
public class MyActivity extends Activity {
private smsReceiver SmsBroadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_one_position);
smsReceiver = new SmsBroadcastReceiver() {
// this code is call asyncrously from the receiver
#Override
protected void onSmsReceived() {
// Add your activty logic here
}
};
}
#Override
protected void onPause() {
super.onPause();
this.unregisterReceiver(this.smsReceiver);
}
}
One easy way is by using static variables.
On the MainActivity add the following:
public class MainActivity extends AppCompatActivity{
public static SmsMessage result;
//...
}
Then, add the following line MainActivity.result = smsMessage to the code you provided just after you get the message.
Then you can use the variable result in any part of the MainActivity (also by calling MainActivity.result you have the value of the variable in any part of your code).
Just be careful, static variables are defined as null before any assignment.
Automatic SMS Verification with the SMS Retriever API used so this is easily getting in SMS,So there was no problem and No permission is needed
https://developers.google.com/identity/sms-retriever/overview

How to call a Main activity method in another non activity class

Below is My Main activity with ColorChange method.I want to call this Colorchange method in ImageColor Class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void ColorChange() { // <----- Want to call this method in below class
ImageView blue = (ImageView) findViewById(R.id.imageView);
blue.setColorFilter(0xff000000);
}
}
And this is my class where i want to call the ColorChange method of Mainactivity.
public class ImageColor {
public void Imager() {
// Want to call my ColorChange method here
MainActivity obj = new MainActivity();
obj.ColorChange(); //<-------- Using mainactiviy object crashes my app.
}
}
I have already tried using Mainactivity as object it crashes my app.I also cannot declare my ColorChange method static because it uses findViewbyid.Please let me know if there is any way to call Color change method in this Image Color Class.
Try this way. It will help you.
public class ImageColor {
public void Imager(Activity activity) {
// Want to call my ColorChange method here
if(activity instance of MainActivity)
((MainActivity)activity).ColorChange(); //<-------- Using mainactiviy object crashes my app.
}
}
use interface to communicate with activity from non activity class. create colorChange() in interface and get the instance of interface in non activity class and call that method
class MainActivity {
interface mInterface = new interface() {
public void colorChange(){
}
}
}
pass mInterface to non activity class and call colorChange of interface when you want ..
You have to pass activity as a parameter in ImageColor class
Then call your ColorChange() method by refference of Activity.
Like This-
public class ImageColor {
Activity activity;
public ImageColor(Activity activity)
{
this.activity = activity;
}
public void Imager()
{
if(activity instance of MainActivity)
((MainActivity)activity).ColorChange();
}
}
Activity classes are created by Android. So the above method is not correct.
You have 2 ways to access the method in activity.
1 . using a static method
public static void ColorChange() {
ImageView blue = (ImageView) findViewById(R.id.imageView);
blue.setColorFilter(0xff000000);
}
}
Using a callback mechanism
public interface ImageLoadedcallback{
void onColorChanged(int color);
}
And update
public class ImageColor {
public void Imager(ImageLoadedcallback callback) {
callback.onColorChanged(color)
}
}
And In activity
public void ColorChange() {
new ImageLoader().Imager(new ImageLoadedcallback{
#Override
public void onImageLoaded(Color color){
ImageView blue = (ImageView) findViewById(R.id.imageView);
blue.setColorFilter(0xff000000);
});
}
To make it clear, make an Activity as a static variable can lead to Activity leak, so we must avoid doing that.
I suppose if the Activity where you create ImageColor object is MainActivity, you can pass MainActivity directly to achieve what you want.
public class ImageColor {
public void Imager(MainActivity activity) {
activity.ColorChange();
}
}
If you called it from other class(not from MainActivity), you can always passing MainActivity to that other class object to be used for ImageColor object.
PS: Check about java naming convention too, it will help you to write a better code

How to interact with UI from a different class

I would like to update my UI from a different class. I am familiar with runOnUiThread() method, but don't know how to implement it in this scenario?
public class UploadAct extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
}
//my code and functions would go here
}
Then, my UploadData class
public class UploadData extends UploadAct {
public void doSomethig(){
printThis("I want to print this message to the UI");
}
public void printThis(String messsage) {
final String mess = message;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),mess,Toast.LENGTH_LONG).show();
// I want this to display on the main thread
txt_upload.setText(mess);// and this also
}
});
}
}
Use BroadcastReceiver
// define a Broadcast Intent Action in String resources
<string name="broadcast_id">MY_BROADCAST_ID</string>
// register receiver in constructor/onCreate()
MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver();
IntentFilter myIntentFilter = new IntentFilter();
myIntentFilter.addAction(context.getString(R.string.broadcast_id));
context.registerReceiver(myBroadcastReceiver, myIntentFilter);
// place your BroadcastReceiver in MainActivity, your UploadData class
public class MyBroadcastReceiver extends BroadcastReceiver {
public MyBroadcastReceiver(){
super();
}
#Override public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Broadcast received");
if(intent.getAction() != null && intent.getAction().equals(context.getString(R.string.broadcast_id)) ){
// do something
}
}
}
// send Broadcasts from where you want to act, your UploadAct class.
Intent intent = new Intent();
intent.setAction(context.getString(R.string.broadcast_id));
context.sendBroadcast(intent);
Log.d(TAG, "Broadcast sent.");
// you can unregister this receiver in onDestroy() method
context.unregisterReceiver(myBroadcastReceiver);
You can also use an interface to update your UI as a listener.
First, Create an interface
public interface UpdateTextListener {
void updateText(String data);
}
Then, Call its method in your UploadData class
public class UploadData extends UploadAct {
UpdateTextListener listener;
public void doSomethig(){
listener.updateText("data to be loaded");
}
}
Then, Update your UploadAct by listening to this method
public class UploadAct extends MainActivity implements UpdateTextListener {
#Override
public void updateText(String data) {
textview.setText(data);
}
}
First of all - there is no such thing like UI of some class. There are activities that can have handles to UI widgets (ex TextView). If you want to make some changes to UI from your UploadData class you have to pass somehow reference to this class. Possibly by constructor:
public class UploadData extends UploadAct{
private TextView txt_upload;
public UploadData(TextView tv)
{
txt_upload = tv;
}
public void doSomethig(){
printThis("I want to print this message to the UI")
}
public void printThis(String messsage) {
final String mess = message;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),mess,Toast.LENGTH_LONG).show();// I want this to display on the main thread
txt_upload.setText(mess);// and this also
}
});
}
}
I assume that you create DataUpload in your MainActivity.
Everyone use so much library to be trendy as they forget built in functions in Android :)
For sure isn't any hard thing to use AsyncTask, beside it provides the doInBackground function it has the https://developer.android.com/reference/android/os/AsyncTask.html#publishProgress(Progress...) function too, what you have asked for.
Just create a class (UploadTask) which extends AsyncTask and override 1-2 function.

Define generic method can open all activities

Can i define an activity in parent class of all activities that that can open new activity like this method that working:
public class ActivityBase extends Activity{
public <T extends Activity,U extends Activity> void openActivity()
{
Intent myIntent = new Intent(T.this, U.class);
T.this.startActivity(myIntent);
}
}
public class ActivityChield extends ActivityBase{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_warning_unregistered_shipping);
// Set widgets reference
btnOpenActivity = (Button)findViewById(R.id.btn_wus_select_violation);
// Set widgets event listener
setListeners();
}
private void setListeners()
{
btnOpenActivity.setOnClickListener( new View.OnClickListener()
{
#Override
public void onClick(View view)
{
openActivity<ActivityChield , OtherActivity>();
}
});
}
}
This code is not working . Please help me how can i define a method that can open all activities with one method.
I don't think this way is a perfect solution. Better is to write the calling code when you need.
By the way here is a solution for your question
public void openActivity(Class<?> calledActivity) {
Intent myIntent = new Intent(this, calledActivity);
this.startActivity(myIntent);
}
And you can call it as
openActivity(OtherActivity.class);

Categories

Resources