Android activity abstract method call - android

I have an abstract class called BaseActivity (extends Activity) which has a function
public abstract void onLocationChanged();
All other activities extends this class. When I call BaseActivity's method onLocationChanged() I would expect, that all other classes that implement this method would call their onLocationChanged() method or at least the activity that is currently on top of the stack, but it seem that only one activity calls the method and it is not the one on top of the stack.
Can someone help?
here are relevant parts of my code:
abstract class BaseActivity extends FragmentActivity {
public static MyLocation location = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (location == null) {
location = new MyLocation(this);
}
}
public abstract void onLocationChanged();
}
public class MyLocation {
BaseActivity parrent;
public MyLocation(BaseActivity act) {
public MyLocation(BaseActivity act) {
this.parrent = act;
}
public void refreshMyLocation() {
/*location get refreshed here*/
this.parrent.onLocationChanged();
}
}
public class MainActivity extends BaseActivity {
#Override
public void onStart() {
BaseActivity.location.refreshMyLocation();
}
public void onLocationChanged() {
/*some stuff*/
}
}

You are calling on location changed on an instance of base activity not all of them at once. Without your code I don't know which one. But simply declaring a method in a base class does not mean it will be called on every class that implements it.

I dont understand why do you want to do that. I think you should need a Serivice that implements onLocationChanged and communicates with activities via Handler or BroadcastReceiver.

Related

call Activity when click button on core game LibGDX

I have a button on Core game. I want when i click button, a Activity will run. I think i can use Interface but it do not work.
buttonPost.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y) {
myGameCallback.startActivity();
}
});
Here is my interface
public interface MyGameCallback{
public void startActivity();
}
private MyGameCallback myGameCallback;
public void setMyGameCallback(MyGameCallback callback){
myGameCallback=callback;
}
And android code:
public class MainActivity extends AndroidApplication implements Main.MyGameCallback {
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
Main main=new Main();
main.setMyGameCallback(this);
initialize(main, config);
}
#Override
public void startActivity() {
Intent intent = new Intent(this, Post.class);
startActivity(intent);
}
}
Please help me, thank you so much.
The Interface way to implement some native android functionality in LIBGDX works as follows.
First of all why your Main class implement screen? As far as I know the Main Class should implement Game. Screen is different then main class.
So here you go for Interface.
public interface MyGameCallback{
public void startActivity();
}
On AndroidLauncher
public class AndroidLauncher extends AndroidApplication implements
MyGameCallback{
// provide implementation of startActivity(); method.
}
Finally your main Game class should go like
public class MainGame extends Game {
public MyGameCallback myGameCallback;
public MainGame(MyGameCallback myGameCallback) {
super();
this.myGameCallback = myGameCallback; // initialize in constructor
}
Finally on the button in game where you want to start your activity do it like.
public class MainMenuScreen implements Screen {
private MainGame mygame;
public MainmenuScreen(MainGame game) { // initiaize maingame class so that you can call Interface method by its reference
this.mygame = game;
}
///////////////////////////////////
Finally on your button do call the method
buttonPost=new TextButton("Post",skin);
buttonPost.pad(20);
buttonPost.addListener(new EventListener() {
#Override
public boolean handle(Event event) {
mygame.myGameCallback.startActivity();
return true;
}
});
If You call it by just Interface name it wont work.

Finishing activity from static method

I would like to do a static method in a class for finishing an activity. I mean something like this :
activity A , activity B , activity C, class ActivitiesKiller.
Class ActivitiesKiller has a static method for finishing the activity A, B or C.
An example:
My runnig class is B and I want to finish activity A, so I will call:
ActivitiesKiller.activityKiller(A);
Is that possible?.
Thanks in advanced
I´m doing something like this, but It doesn´t work.
public class ActivitiesKiller {
//.....
public static void activityKiller(Activity activity){
activity.finish();}
}
While it doesn't sound like a good idea, what you would need to do is to make a static reference to the activities on creation, and null them on destruction.
public class ActivityA extends Activity
{
public static Activity self;
#Override
public void onCreate(Bundle saveInstanceState)
{
super.onCreate(saveInstanceState);
self = this;
}
#Override
public void onDestroy()
{
super.onDestroy();
self = null;
}
}
And then you would need to do the following
public class ActivitiesKiller
{
public static void activityKiller(Activity activity)
{
if(activity != null)
{
activity.finish();
}
}
}
Which you would call as
ActivitiesKiller.activityKiller(ActivityA.self);

How to pass an Activity instance to another activity

Hi I have an activity named BaseActivity, which extends Activity.
from this i have to go to SettingsActivity which extends PreferenceActivity, on menu button press. To start a AsyncTask, which is in an independent class, i need an instance of BaseActivity. How can i get a BaseActivity instance in the SettingsActivity?
is there any way like,
eg:
intent.putExtra("activity_instance",BaseActivity.this);
Use getters and setters and make the class they reside as singleton class.
This is a singleton class.Using this class we can share data(ex: int,boolean,activity instance ...etc) all over the class.
public class CommonModelClass
{
public static CommonModelClass singletonObject;
/** A private Constructor prevents any other class from instantiating. */
private Activity baseActivity;
public CommonModelClass()
{
// Optional Code
}
public static synchronized CommonModelClass getSingletonObject()
{
if (singletonObject == null)
{
singletonObject = new CommonModelClass();
}
return singletonObject;
}
/**
* used to clear CommonModelClass(SingletonClass) Memory
*/
public void clear()
{
singletonObject = null;
}
public Object clone() throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
}
//getters and setters starts from here.it is used to set and get a value
public Activity getbaseActivity()
{
return baseActivity;
}
public void setbaseActivity(Activity baseActivity)
{
this.baseActivity = baseActivity;
}
}
In BaseActivity class do like this.
Class BaseActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
CommonModelClass commonModelClass = CommonModelClass.getSingletonObject();
commonModelClass.setbaseActivity(BaseActivity.this);
//after using the BaseActivity instance dont forget to call commonModelClass.clear(); else it wont be garbage collected
}
}
In SettingsActivity do like this
Class SettingsActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
CommonModelClass commonModelClass = CommonModelClass.getSingletonObject();
Activity instanceBaseActivity= commonModelClass.getbaseActivity();;
}
}
please give tick if this works
You are confusing activities with class objects. The moment activity class is instantiated it obeys all activity life cycle rules, importantly system can kill this activity any time. So you have to design activities in such a way that it shouldn't be dependent on another activity instance at all but only drive the results. you can write a helper class and call it again and again if you want. if not use storages like sdcard or preference or sandbox to store the information and retrieve it from the other activity. If you want to keep some of these information in memory then subclass Application class and keep them at the application level.
Make a static Context in "Base Activity"
public class BaseActivity extends Activity{
public static Context ctxt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ctxt = BaseActivity.this
}
}
and in your "PreferenceActivity" activity use this way
BaseActivity.ctxt

Call a public method in the Activity class from another class?

MAIN ACTIVITY
public class MyActivity() extends Activity
{
onCreate()
{
MyClass myobj=new MyClass();
}
public void Mymethod()
{}
}
//HELPER CLASS IN A SEPARATE FILE
public class MyClass()
{
MyClass(Context context)
{
}
}
I tried to call Mymethod() from an instance of MyClass.
I would really appreciate any help. Thanks.
Why not just pass the activity to the constructor like
public class MyActivity extends Activity {
onCreate(){
MyClass myobj=new MyClass(MyActivity.this);
}
public void myMethod(){
}
}
//HELPER CLASS IN A SEPARATE FILE
public class MyClass{
public MyClass(MyActivity act) {
act.myMethod();
}
}
Make that method as static so you can call without creating the class object
public static void Mymethod()
{}
and call like this way
MainActivity.Mymethod();
This is probably the best way to do it. This is how I'm doing it. It's called a Singleton Design Pattern:
public class MyActivity extends Activity {
private static MainActivity instance;
public static MainActivity getInstance() {
if(instance==null){
setInstance(this);
}
return instance;
}
public static void setInstance(MainActivity instance) {
MainActivity.instance = instance;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setInstance(this);
}
}
If I'm understanding you correctly I believe you can solve your problems using an interface as a callback.
////ACTIVITY/////////////////////////////////
public class MyActivity() extends Activity {
onCreate()
{
MyClass myObj=new MyClass();
//Set the listener on the object. Created as anonymous
myObj.setListener(new MyClass.Listener() {
myMethod();
});
}
}
public void myMethod(){
}
//////Custom Class//////////////////
public class MyClass {
Listener mListener;
public interface Listener {
public void onInterestingEvent();
}
public void setListener(Listener listener) {
mListener = listener;
}
public void someUsefulThingTheClassDoes() {
//Do your code here and when you're ready to call the activity's method do this
mListener.onInterestingEvent();
}
}
I had an inner class that I wanted to pull out into a more general library "Helper" class. I had the same issue you do. I got around it by making the helper class abstract, with a single abstract method. Then in my project package I extended the helper class with a constructor call in the specific class.
public class MyActivity extends Activity {
onCreate() {
MyHelperClass = new MyHelperClass(this, "foobar");
}
public void myMethod() {
// Code...
}
}
// In a different file
public class MyHelperClass extends HelperClass {
private MyActivity mInstance;
public MyHelperClass(MyActivity act, String data) {
super();
this.mInstance = act;
this.mActivity = act; // Useful for calling generic Activity methods in the HelperClass
this.mData = data;
}
protected void callMyActivityMethod() {
mInstance.myMethod();
}
}
// In a different file
public abstract class HelperClass {
protected Activity mActivity;
protected String mData;
public HelperClass() {
// Subclass will set variables
}
protected abstract void callMyActivityMethod();
// More code for all the other stuff the class does
}
In this way, I have a helper class that contains the vast majority of the "work", and all I have to do is make a subclass with the constructor and one method in order to get access to the calling activity's method of interest.
You have to pass instance of MainActivity into another class, then you can call everything public (in MainActivity) from everywhere.
MainActivity.java
public class MainActivity extends AppCompatActivity {
// Instance of AnotherClass for future use
private AnotherClass anotherClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Create new instance of AnotherClass and
// pass instance of MainActivity by "this"
anotherClass = new AnotherClass(this);
}
// Method you want to call from another class
public void myMethod(){
...
}
}
AnotherClass.java
public class AnotherClass {
// Main class instance
private MainActivity mainActivity;
// Constructor
public AnotherClass(MainActivity activity) {
// Save instance of main class for future use
mainActivity = activity;
// Call method in MainActivity
mainActivity.myMethod();
}
}
In MainActivity.class file
You have to pass MainActivity context from MainActivity Class. Then in MyClass you have to Get MainActivity context. Remember Context and MyActivity are two different reference.
public class MyActivity extends Activity
{
onCreate(){
MyClass myobj=new MyClass(MyActivity context);
}
public void Mymethod(){}
}
//HELPER CLASS IN A SEPARATE FILE
public class MyClass()
{
MyActivity context;
MyClass(MyActivity context)
{
this.context = context;
this.context.Mymethod();
//Or you can directly use activity context
context.Mymethod();
}
}
I decided to write the HelperClass MyClass as an inner class of MyActivity class. This allows it full access to parent class but the bad thing is now MyClass is restricted to MyActivity class only.
public class MyActivity() extends Activity
{
onCreate()
{
MyClass myobj=new MyClass();
}
public void myMethod()
{
}
}
//INNER CLASS
public class MyClass
{
public MyClass()
{
}
//I can directly access the MyMethod
myMethod();
}

How to access Activity UI from my class?

I have an activity which creates an object instance of my class:
file MyActivity.java:
public class MyActivity extends Activity {
TextView myView = (TextView)findViewById(R.id.myView);
...
Points myPoints new Points();
...
}
--------------------------------------------------------------
file Points.java:
private class Points {
...
HOW TO USE myView HERE ???
...
}
--------------------------------------------------------------
How do I use the UI objects in my class (which does not extend an
Activity)? Should I pass some context to my Points class? How do I do, exactly?
see you post, i've edited it , to fix the problem
hope it helps :=)
here is the Edit :
file MyActivity.java:
public class MyActivity extends Activity {
TextView myView ;
protected void onCreate(android.os.Bundle savedInstanceState) {
myView = (TextView)findViewById(R.id.myView);
Points myPoints = new Points(this);
myPoints.displayMsg("Hello World !!!");
}
}
--------------------------------------------------------------
file Points.java:
private class Points {
protected MyActivity context;
//add a constructor with the Context of your activity
public Points(MyActivity _context){
context = _context;
}
public void displayMsg( final String msg){
context.runOnUiThread(new Runnable() {
#Override
public void run() {
context.myView.setText(msg);
}
});
}
}
Your Points can't be a private class without being an inner class. So your code doesn't even compile...
Pass the view as parameter to the constructor of your Points class:
public class MyActivity extends Activity {
TextView myView = (TextView)findViewById(R.id.myView);
Points myPoints new Points(myView);
private class Points {
public Points(TextView view) {
// todo
}
}
}
You should do everything and pass back the value to the activity to handle UI instead of doing any UI related stuff in the point stuff.
You can pass the main Activity's context (using Points(getApplicationContext());) to the class as a constructor parameter. You could also pass the specific UI elements you want to manipulate.
A better way to do it, however, may be to have Points not know about the Activity. Have your Activity call Points methods and take the necessary actions based on the method output.
You could just pass the view to your class.
Points myPoints = new Points(myView);
private class Points
{
private TextView mTextView;
Points(TextView textView)
{
this.mTextView = textView;
}
}
i was in same trouble..
i found the simple way..
make a static variable and function ...
call from other class..
TestActivity.java
public class TestActivity extends Activity {
static EditText edit_text1;
public void onCreate(Bundle savedInstanceState)
{
.....
edit_text1 = (EditText) findViewById(R.id.edit_text1);
.....
}
public static void setMSG(String str)
{
edit_text1.setText(str);
}
}
Test2.java
TestActivity.setMSG("this is text");
Could work using an interface
file MyActivity.java:
public class MyActivity extends Activity implements Points.MyListener {
TextView myView;
... onCreate(...){
myView = (TextView)findViewById(R.id.myView);
Points myPoints = new Points();
//pass in MyActivity's instance of the listener
myPoints.addListener(this);
}
#Override
public void updateTextView(String message){
myView.setMessage(message);
}
}
file Points.java:
public class Points {
public Points(){
}
public interface MyListener{
void updateTextView(String message);
}
MyListener myListener;
public void addListener(MyListener listener){
myListener = listener;
}
public void updatePoints(){
//do some operations in calculatePoints()
String points = calculatePoints();
//update views using MyActivity's implementation of updateTextView()
myListener.updateTextView(points);
}
}
Doing it this way, events can be fired / messages sent, for lack of better terms, from the external class to update the Activity UI. This might be overkill if all sb need is to call a method in the Points class that returns something

Categories

Resources