I want to start an activity from a static java method on an android device.
I do not have any context or anything passed as parameter to the static function.
For starting the activity I must call "startActivity" with the current running method as "this" pointer. So is there a way to get the current running activity?
You can access only static variables/objects inside static method.
So You need to Implement this way
public class MainActivity extends Activity {
private static Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
}
public static void goToLoginActivity() {
Intent login = new Intent(mContext, LoginActivity.class);
mContext.startActivity(login);
}
}
NOTE : But this is not the proper way to do so, this may cause window leak issue.
Better approach is pass activity/context object as parameter like this.
public static void goToLoginActivity(Context mContext) {
Intent login = new Intent(mContext, LoginActivity.class);
mContext.startActivity(login);
}
Create a Class in your app extending class Application, define a static context and initialise this with your application context. You can expose a static method from this class for accessing defined static reference. Thats it.
class MyApp extends Application{
private static Context mContext;
public void onCreate(){
mContext = this.getApplicationContext();
}
public static Context getAppContext(){
return mContext;
}
}
Now you can use this static method for accessing context anywhere in your app.
Related
To get context, I use:
Context context = InstrumentationRegistry.getInstrumentation().getContext();
But I didn't found any method like getApplicationContext();
Any leads would be appreciated
Try this way:
Your_Activity.this
Or you can create a public static method to get the Context:
public class App extends Application {
private static Application sApplication;
public static Application getApplication() {
return sApplication;
}
public static Context getContext() {
return getApplication().getApplicationContext();
}
#Override
public void onCreate() {
super.onCreate();
sApplication = this;
}
}
Or get it through a View, using Your_View.getContext()
Hope this help
I want to access a class extending SQLiteOpenHelper to get the context of database from a java class. I need to pass application context to get that but don`t have access to getApplicationContext().
How can I get Application Context in java class that is not activity?
I suggest you create a constructor that has a parameter of the Context type.
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
// Variables
private Context ctx;
public MySQLiteOpenHelper(Context ctx) {
this.ctx = ctx;
}
//More code
}
Now, in your activities, you can do this:
MySQLiteOpenHelper helper = new MySQLiteOpenHelper(this);
And in your fragments, you can do this:
MySQLiteOpenHelper helper = new MySQLiteOpenHelper(getActivity().getApplicationContext()); //getActivity() would work too, Activity (indirectly) extends Context.
You can create custom Application class and write method getContext().
Someting like this:
public class MyApplication extends Application {
private static MyApplication mCurrentInstance;
#Override
public void onCreate() {
super.onCreate();
mCurrentInstance = this;
}
public static MyApplication instance() {
return mCurrentInstance;
}
public static Context context() {
return mCurrentInstance.getApplicationContext();
}
}
And add this class into manifest:
<application
android:name=".MyApplication">
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();
}
}
I'm playing with the GCM.
Everything is perfect using the example on https://code.google.com/p/gcm/source/checkout
Im getting notifications on my app with the gcm messages,
Now I want to add the message in a listView located on my MainActivity.
Im receiving my messages on a different class (GcmIntentService.java). How can I get MainActivity context to sendBroadcast.
Already tried with
private static Context mContext;
public static Context getContext() {
return mContext;
}
public static void setContext(Context context) {
mContext = context;
}
But is not working.
Any Ideas.
Thanks
I am not sure what you are doing. But keeping the below in mind
Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself).
http://www.curious-creature.org/2008/12/18/avoid-memory-leaks-on-android/
You can do as below
Example:
new MyClass(ActivityName.this);
class MyClass
{
Context mContext;
public MyClass(Context context)
{
mContext=context;
}
}
pass the context variable through constructor .
create new activity like below
public class GetContext extends AppCompatActivity {
Context mainActivity;
public GetContext(Context mainActivity){
this.mainActivity = mainActivity;
}
and in your previous mainActivity send this context as below
GetContext sendContext = new GetContext(mainActivityContext);
where mainActivityContext is Context mainActivityContext = this;
or simply pass this instead of mainActivityContext
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_attendance_from_database);
}
MyI don't understand why I get a compile error for this:
public class Main_screen extends ListActivity {
List<Object> completeList;
private My_ArrayAdapter adapter;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
completeList = getCompleteList();
adapter = new My_ArrayAdapter(this, completeList);
setListAdapter(adapter);
}
public void doSth() {
...
}
}
and in My_ArryAdapter:
public class My_ArrayAdapter extends ArrayAdapter<Object> {
private final List<Object> list;
private final Activity context;
public My_ArrayAdapter(Activity context, List<Object> list) {
this.context = context;
this.list = list;
}
public void tryIt() {
context.doSth(); // <-------- THIS DOES NOT WORK, this method can not be called
}
}
Please explain, is there something fundamental I have not understood. I am just passing the context into the ArrayAdapter instance I create. And from within this instance I would like to acccess the caller's method.
Why shoudl this not be possible?
Many thanks!
try this:
public void tryIt() {
((Main_screen)context).doSth();
}
context is Activity and it hasn't doSth(), but Main_screen has, so you should cast to this class
Actually you are making Activity context object and passing a child of Activity (i.e Main_Screen), Its called upward cast (Implicit Casting).
So the Activity (as parent) has no method of doSth(). So you need downward Casting (Explicit casting) to make it a Main_Screen.
Two ways to do this.
make an Object of Main_Screen context instead of Activity context
or
cast it as Main_Screen in tryIt() method to avail Main_Screen methods like this way:
if(context.isInstance(Main_Screen.class))
{
((Main_Screen)context).doSth()
}
you can also use try catch to minimize the chances of ClassCastException
You can use the below code. Obviously class context don't contain an object doSth(). doSth() is declared in class Main_screen.
public class My_ArrayAdapter extends ArrayAdapter<Object> {
private final List<Object> list;
private final Activity context;
public My_ArrayAdapter(Activity context, List<Object> list) {
this.context = context;
this.list = list;
}
public void tryIt() {
Main_screen.doSth();
}
}
How I did it
StaticCommonDataClass -> maintains static data here I will keep the instance of Activity one in it.
ActivityOneClass -> Contains the method that I have to access in ActivityTwo actually.
ActivityTwoClass => Will access the ActivityOne Method.
What I hate is to pass two many parameters from one function to other function or one class to other class,
that too when it has to be done for similar values again and again.
Here i will store refrence of ActivityOneClass in static Variable.
public class CommonStaticData {
private static Activity _activity;
private static Context _context;
public static void setactivity(Activity activity) {
_activity = activity;
}
public static Activity getactivity() {
return _activity;
}
public static void setcontext(Context context) {
_context = context;
}
public static Context getcontext() {
return _context;
}
}
public class ActivityOneClass extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
CommonStaticData.setactivity(ActivityOneClass.this); //will keep the instance alive for this activity
}
Public void activityOneMethod()
{
//Set of statements
}
}
public class ActivityTwoClass extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
((ActivityOneClass) CommonStaticData.getactivity()).activityOneMethod();
//we need to typecast the instance stored in CommonStaticData.getactivity() to "ActivityOneClass" thats is the
//activity containing the method so as to access the method otherwise it will not come in the intellisense window and will generate Compiler Error
}
}