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);
Related
i need to get method from appcompatactivity to this class and call this method in another appcaompatactity like this
public class WareHouseActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_warehouse);
}
public void showToast(){
Toast.makeText(WareHouseActivity.this,"warehouse",Toast.LENGTH_SHORT).show();
}
}
call method showToast from appcampatactivity in this class :
public class Common {
public static void showToast(Activity activity){
((WareHouseActivity)activity).showToast();
}
}
and i try with context instead of using Activity like:
public class Common {
public static void showToast(Context context){
((WareHouseActivity)context).showToast();
}
}
call method showToast from class in another appcompatactivity :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_warehouse);
Common.showToast(MainActity.this);
}
}
If you want to share a method with multiple Activities, it cannot live on an Activity instance. You can't be guaranteed that the instance exists when another Activity is being shown, and you should never create Activity instances yourself.
If you move the full method to a separate class like this:
public class Common {
// You must pass in any arguments needed in the function
public static void showToast(Context context){
Toast.makeText(context,"warehouse",Toast.LENGTH_SHORT).show();
}
}
Then you can call it from any activity
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_warehouse);
Common.showToast(this);
}
Update
If the reason you want to do this is to have shared data that you can access from both activities, that data should not live in one of the activities. Have a look at the activity lifecycle, activities will be destroyed when the device is rotated, or can be destroyed when in the background by the OS. Any temporary data you store on an activity would be lost when that happens.
One simple option for storing some temporary data is a singleton class. This is not persistent - the data will still be lost if your app is stopped and restarted). If you need persistent data you should use SharedPreferences or a database for that. However, it will let some temporary data live longer than an individual activity's lifecycle and be accessible from multiple activities or fragments.
class Common {
private static Common instance = null;
private Common() {}
public static synchronized Common getInstance() {
if (instance == null) {
instance = new Common();
}
return instance;
}
final List<String> names = new ArrayList<>();
String message = "";
void showMessage(Context ctx) {
Toast.makeText(ctx,message,Toast.LENGTH_SHORT).show();
}
}
Then you can set and use data stored in this class from multiple activities, like this
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Common c = Common.getInstance();
c.message = "Hello from Main";
c.names.add("Test");
}
}
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Common c = Common.getInstance();
c.showMessage(this)
c.names.add("Test Two");
}
}
is it possible to get all activities in the application? i have a global integer variable that should be in the ActionBar of every activity. i thought something like this:
for (Layout/Activity l in (all activites)) {
l.setTitle(variable);
}
i already tried it with R.layout but this didnt work for me.
How can i do this or is there a better way to display my variable in all activity labels? later i want to call this code from my set method for the global variable.
There is only one activity running at a time, so you can’t get this kind of references.
Said that, I think the way to go it’s create an int static variable in some class, and called it from your activities.
//SomeClass
public static int xValue = 0;
//ActivityOne || ActivityTwo || ActivityThree ...
String text = String.valueOf(SomeClass.xValue);
SomeClass.xValue = 1;
Because it’s a public static variable, you don’t need to instantiate any object to get/set its value, and it will be accesible from any class. Furthermore, this value will be reachable as long as its class is in the memory, and destroy just when class gets unloaded.
yes it's possible with singleton.
This is how to use singleton:
This is Singleton class:
public class Singleton {
private static Singleton mInstance = null;
private String mTitle;
public void setmTitle(String mtitle){
this.mTitle=mtitle
}
public String getmTitle(){
return mTitle;
}
public static FilterArrayList getInstance(){
if(mInstance == null)
{
mInstance = new FilterArrayList();
}
return mInstance;
}
}
This is the first activity:
public class FirstActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Singleton.mInstance.setmTitle("This is Singleton");
}
}
and in second activity:
public class SecondActivity extends Activity {
String Title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Title=Singleton.mInstance.getmTitle();
}
}
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
I have an Activity and non Activity class. How to call a method in Activity class from non Activity class
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
DataClass dc = new DataClass();
dc.show();
}
public void call(ArrayList<String> arr) {
// Some code...
}
}
public class DataClass {
public void show(ArrayList<String> array) {
// Here I want to send this ArrayList values into the call
// method in activity class.
MainActivity act = new MainActivity();
act.call(array);
}
}
Just create a callback interface inside the DateClass.
public DateClass {
public interface IDateCallback {
void call(ArrayList<String> arr);
}
private IDateCallback callerActivity;
public DateClass(Activity activity) {
callerActivity = (IDateCallback)activity;
}
...
}
public void show(ArrayList<String> array) {
callerActivity.Call(array);
...
}
//And implements it inside your activity.
public class MainActivity extends Activity
implements IDateCallback {
public void call(ArrayList<String> arr) {
}
}
Well there are several things you could do. I think the easiest for you would be to send the Context into DataClass like so:
DataClass dc =new DataClass();
dc.show(this);
And in your DataClass save the context into a global var Context context. Then use it like so:
((MainActivity)context).call(array);
((MainActivity)getContext).array();
Just make a singleton like:
TeacherDashboardSingleton:
public class TeacherDashboardSingleton {
public Teacher_Dashboard aa;
private static final TeacherDashboardSingleton ourInstance = new TeacherDashboardSingleton();
public static TeacherDashboardSingleton getInstance() {
return ourInstance;
}
}
myActivity class:
onCreate(....){
....
TeacherDashboardSingleton.getInstance().aa = this;
....
}
this will create an object of same instance as in activity
now you can use it from anywhere
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.