The code is followed:
Context c = getContext().createPackageContext("com.master.schedule",
Context.CONTEXT_INCLUDE_CODE|Context.CONTEXT_IGNORE_SECURITY);
int id = c.getResources().getIdentifier("layout_main", "layout","com.master.schedule");
LayoutInflater inflater = LayoutInflater.from(c);
piflowView = inflater.inflate(id, null);
com.master.schedule is my package project.The upside code presents how the other project(his package name is different to mine) inflate my project, in my project there is only a ViewGroup(I don't have an activity); and when I invoke "context.getApplicationContext", it returns null... my project code is below:
public class CascadeLayout extends RelativeLayout {
private Context context;
public CascadeLayout(Context context) {
super(context);
this.context=context.getApplicationContext();
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
//here: context == null;
}
}
I find the createPackageContext() give the "Context c" to me is a ContextImpl type; I think that's caused return null;
So how can I get an ApplicationContext which not null?
BTW:please don't persuade me don't invoke getApplicationContext();As I must use an .jar, the jar need to invoke getApplicationContext() in it;
thanks very very much.
The documentation for createPackageContext() states:
Return a new Context object for the given application name. This
Context is the same as what the named application gets when it is
launched, containing the same resources and class loader.
Reading a bit between the lines, this context is apparently supposed to be "the same" as an application context. However, you are seeing that its getApplicationContext() returns null, so we can attempt to fix that by using a ContextWrapper (see below). Hopefully, this approach will be good enough for your needs.
In the following code, WrappedPackageContext is used to wrap the "package context" returned by createPackageContext(), overriding the getApplicationContext() implementation so that it returns itself.
class WrappedPackageContext extends ContextWrapper {
WrappedPackageContext(Context packageContext) {
super(packageContext);
}
#Override
public Context getApplicationContext() {
return this;
}
}
Context createApplicationContext(Context packageContext) {
return new WrappedPackageContext(packageContext);
}
Related
this problem is not always there, I can't find the cause of the problem, ask for help, thank you.
My code is
private static Toast systemToast;
public static Toast getSystemToast(Object resId) {
if (null == systemToast) {
// Apps is the Application.java
systemToast = Toast.makeText(Apps.getAppContext(), R.string.me_empty,
Toast.LENGTH_SHORT);
}
String res = String.valueOf(resId);
if (resId.getClass() == Integer.class) {
systemToast.setText(Integer.valueOf(res));
} else if (resId.getClass() == String.class) {
systemToast.setText(res);
}
systemToast.setDuration(Toast.LENGTH_SHORT);
return systemToast;
}
/** Apps.java **/
public class Apps extends Application {
private static Apps sContext;
#Override
protected void attachBaseContext(Context base) {
sContext = this;
}
public static Apps getAppContext() {
return sContext;
}
In some Android equipment, Error occurred, The error Log is:
android.content.res.Resources$NotFoundException: File res/layout
/transient_notification.xml from xml type layout resource ID #0x10900ef at
android.content.res.Resources.loadXmlResourceParser(Resources.java:2720) at
android.content.res.Resources.loadXmlResourceParser(Resources.java:2675) at
android.content.res.Resources.getLayout(Resources.java:1096) at
android.view.LayoutInflater.inflate(LayoutInflater.java:422) at
android.view.LayoutInflater.inflate(LayoutInflater.java:368) at
android.widget.Toast.makeText(Toast.java:282)
This error might be occurred, when pass context object not proper initialize or might be its referencing to null.
1.if you are using Fragment than, you can find Context in onAttach Method. And pass your getSystemToast Method.
**#Override
public void onAttach(Context context) {
super.onAttach(context);
}**
2. If you are using Activity, than get Context using getBaseContext() Method or ActivityName.this both will return you context
You no need to defined function for get Context. Android provide Following Method for get Context.
1.getApplicationContext() Application context is associated with the Applicaition and will always be the same throughout the life cycle.
2.getBaseContext()
3.onAttach() in Fragment.
I have an app on Android 4.0. It uses the PreferenceManager class to -- among other things -- let the user specify how many decimal places of a number to show.
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Generally I have no problem getting the app context in order to access the Preference Manager. My problem is that I have a class (let's call it Record) that isn't subclassing anything that has the app context; it's just a storage class, but it does have a field "NumDecPlaces". Right now, when I instantiate the class from within my app I just pass in the user's #dec places preference. It would be nice if Record could access the Preference manager directly. I suppose I could always instantiate Record with a pointer to the context from which it was created, but that's a lot to remember ;-)
So right now Record subclasses nothing. Any recommendations on what I can do to it to allow it to see the app context?
Thanks!
You could pass the Context object in the constructor. So whenever you try to use that class it will ask you pass a Context object and then use that to get SharedPreferences
For eg.
public Record(Context context)
{
mContext = context;
mPreferences = PreferenceManager.getDefaultSharedPreferences(mContext)
}
You can also extend a class with Application, which will be global to the whole application and you can set the context in that class as a member variable and that context will be global to the whole application
Eg. class A extends Application{......}
You can do #Apoorv's suggestion or you can create another class that specifically stores the application context.
public class ContextResolver {
private static Context context;
public static void setContext(Context context) {
if (context == null) {
throw new IllegalArgumentException("Context must not be null");
} else if (context instanceof android.app.Activity) {
context = androidContext.getApplicationContext();
} else if (context instanceof android.content.Context) {
context = androidContext;
}
}
public Context getContext() {
return context;
}
}
Now you need to call setContext() in the first activity that will be launched once.
public class MyFirstActivity extends Activity {
public void onCreate() {
ContextResolver.setContext(this);
}
}
Now you can retrieve the Context from any part of your code. So in your Record class you can just do this:
mPreferences = PreferenceManager.getDefaultSharedPreferences(ContextResolver.getContext());
I often find myself needing to access methods that require referencing some activity. For example, to use getWindowManager, I need to access some Activity. But often my code for using these methods is in some other class that has no reference to an activity. Up until now, I've either stored a reference to the main activity or passed the context of some activity to the class. Is there some better way to do this?
If you already have a valid context, just use this:
Activity activity = (Activity) context;
Passing context is better way for refrence Activity.
You can pass Context to another class.
IN Activity ::
AnotherClass Obj = new AnotherClass(this);
IN Another Class
class AnotherClass{
public AnotherClass(Context Context){
}
}
You can implement the necessary methods in your activity and implement a Handler. Then, simply pass a handler instance to your classes, where you can obtain a message for handler and send it to target.
You can make you application instance a singleton, and use it when you need a Context
An example is in this question:
Android Application as Singleton
This way, when you need a Context, you can get it with
Context context = MyApplication.getInstance()
This might not be the cleanest solution, but it has worked well for me so far
I found a way to get the Activity to a non-activity class that I have not seen discussed in forums. This was after numerous failed attempts at using getApplicationContext() and of passing the context in as a parameter to constructors, none of which gave Activity. I saw that my adapters were casting the incoming context to Activity so I made the same cast to my non-activity class constructors:
public class HandleDropdown extends Application{
...
public Activity activity;
...
public HandleDropdown() {
super();
}
public HandleDropdown(Activity context) {
this.activity = context;
this.context = context;
}
public void DropList(View v,Activity context) {
this.activity = context;
this.context = context;
...
}
After doing this cast conversion of Context to Activity I could use this.activity wherever I needed an Activity context.
I'm new to android so my suggestion may look guffy but what if you'll just create a reference to your activity as private property and assign that in OnCreate method? You can even create your CustomActivity with OnCreate like that and derive all your activities from your CustomActivity, not the generic Activity provided by android.
class blah extends Activity{
private Activity activityReference;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityReference = this;
}
}
after that you could use that the way you want, i.e. in
Intent i = new Intent(activityReference, SomeOtherActivity.class)
etc
There are many ways for Activities communication.
you can use:
the startActivityForResult method
a system of broadcast message and receiver (you can broadcast an event from the actual activity, and register a receiver in the target activity. Remember that the target activity must be previously initialized and non finished)
as you say, store a reference of the target activity wherever you need.
We built a framework for this. We have a BaseActivity class that inherits from Activity and it overrides all the lifecycle methods and has some static (class) variables that keep track of the activity stack. If anything wants to know what the current activity is, it just calls a static method in BaseActivity that returns the activity on top of our privately-managed stack.
It is kinda hacky, but it works. I'm not sure I would recommend it though.
Handle the Intent in the class you want to do these methods, and send your information to it in a Bundle like so:
Intent i = new Intent("android.intent.action.MAIN");
i.setComponent(new ComponentName("com.my.pkg","com.my.pkg.myActivity"));
Bundle data = new Bundle();
i.putExtras(data);
startActivityForResult(i);
Then use an OnActivityResultListener to grab the new data.
I solved this by making a singleton class has an instance of the class below as a member.
public class InterActivityReferrer <T> {
HashMap<Integer, T> map;
ArrayList<Integer> reserve;
public InterActivityReferrer() {
map = new HashMap<>();
reserve = new ArrayList<>();
}
public synchronized int attach(T obj) {
int id;
if (reserve.isEmpty()) {
id = reserve.size();
}
else {
id = reserve.remove(reserve.size() - 1);
}
map.put(id, obj);
return id;
}
public synchronized T get(int id) {
return map.get(id);
}
public synchronized T detach(int id) {
T obj = map.remove(id);
if (obj != null) reserve.add(id);
return obj;
}
}
This class can get a T object and return a unique integer assigned to the object by attach(). Assigned integers will not collide with each other unless HashMap fails. Each assigned integer will be freed when its corresponding object is detached by detach(). Freed integers will be reused when a new object is attached.
And from a singleton class:
public class SomeSingleton {
...
private InterActivityReferrer<Activity> referrer = new InterActivityReferrer<>();
...
public InterActivityReferrer<Activity> getReferrer() {return referrer;}
}
And from an activity that needs to be referred:
...
int activityID = SomeSingleton.getInstance().getReferrer().attach(this);
...
Now with this, a unique integer corresponding to this activity instance is returned. And an integer can be delivered into another starting activity by using Intent and putExtra().
...
Intent i = new Intent(this, AnotherActivity.class);
i.putExtra("thisActivityID", activityID);
startActivityForResult(i, SOME_INTEGER);
...
And from the another activity:
...
id refereeID = getIntent().getIntExtra("thisActivityID", -1);
Activity referredActivity = SomeSingleton.getInstance().getReferrer().get(refereeID);
...
And finally the activity can be referred. And InterActivityReferrer can be used for any other class.
I hope this helps.
public static Activity getLaunchActivity()
{
final Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
final Method methodApp = activityThreadClass.getMethod("currentApplication");
App = (Application) methodApp.invoke(null, (Object[]) null);
Intent launcherIntent = App.getPackageManager().getLaunchIntentForPackage(App.getPackageName());
launchActivityInfo = launcherIntent.resolveActivityInfo(App.getPackageManager(), 0);
Class<?> clazz;
try
{
clazz = Class.forName(launchActivityInfo.name);
if(clazz != null)
return Activity.class.cast(clazz.newInstance());
}
catch (Exception e)
{}
return null;
}
Just a guess since I haven't done this but it might work.
1) Get your applicationContext by making your Android Application class a Singleton.
2) Get your ActivityManager class from the context.
3) Get a list of RunningTaskInfos using getRunningTasks() on the ActivityManager.
4) Get the first RunningTaskInfo element from the list which should be the most recent task launched.
5) Call topActivity on that RunningTaskInfo which should return you the top activity on the activity stack for that task.
Now, this seems like a LOT more work than any of the other methods mentioned here, but you can probably encapsulate this in a static class and just call it whenever. It seems like it might be the only way to get the top activity on the stack without adding references to the activities.
I have defined a new class to use in my project and I get null pointer exception in the context
Here is what i coded :
public class OurClass extends Activity {
private dha mContext;
private dhaService sContext;
public OurClass(dha dha) {
sContext=null;
mContext = dha;
}
public OurClass(dhaService dhx) {
sContext = dhx;
mContext=null;
}
public void put_default_value( String varname, String value) {
Log.i("dha", "d1");
SQLiteDatabase db;
Log.i("dha", "d1.5");
if (mContext==null) {
Log.i("dha", "dx1");
db = sContext.openOrCreateDatabase("gipi.db", SQLiteDatabase.CREATE_IF_NECESSARY,null);
Log.i("dha", "dx2");
} else {
Log.i("dha", "dz1");
db = android.database.sqlite.SQLiteDatabase.openOrCreateDatabase("gipi.db", null);
Log.i("dha", "dz2");
}
You're not actually checking that the Contexts are valid before using them.
For example, if OurClass(dhaService dhx) is called with a null Context, then putDefaultValue will fail with a NullPointerException because sContext is assigned the value of dhx without checking either dhx or sContext for valid values.
On a side note, neither sContext, nor mContext are being initialised, which means that with the lack of proper checking you have right now, you could easily inadvertently call put_default_value, while never actually having called either of the constructors. This is not best practice.
EDIT:
One way to help guard against this is to make the default constructor private, so that an instance of the class must be created by calling one of the constructors you have provided:
private:
OurClass ( void ) {
}
Even if you do that, you still need to properly validate your inputs to at least detect null pointers - you can't just assume it will all work as you intend, since it clearly isn't right now.
So, my first major application is almost coded and I'm doing optimizations on my code. The app works fine, but I'm not sure about my way of passing the context to other classes. I don't want to do it the wrong way. I stumbled upon articles and questions here in Stackoverflow about contexts and which is the right way to pass it to non-activity classes. I read the documentation as well, but being a Finn makes complicated tech speak even harder to understand.
So, a simple question. Is my way of passing my main activity's context to other (helper) classes correct? If not, where can I read more about better practice on these situations.
For example:
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle sis){
super(sis);
new Helper(MyActivity.this).makeMyAppAwesome();
}
}
Helper.java
public class Helper {
Context context;
Helper(Context ctx){
this.context = ctx;
}
public void makeMyAppAwesome(){
makeBaconAndEggsWithMeltedCheese(context);
}
}
Is this OK? It would be nice if someone could provide an easy to read article with examples on this subject.
You can do that using ContextWrapper, as described here.
For example:
public class MyContextWrapper extends ContextWrapper {
public MyContextWrapper(Context base) {
super(base);
}
public void makeMyAppAwesome(){
makeBaconAndEggsWithMeltedCheese(this);
}
}
And call the non activity class like this from an Activity
new MyContextWrapper(this);
It is usually in your best interest to just pass the current context at the moment it is needed. Storing it in a member variable will likely lead to leaked memory, and start causing issues as you build out more Activities and Services in your app.
public void iNeedContext(Context context) {...
Also, in any class that has context, I'd recommend making a member variable for readability and searchability, rather than directly passing or (ClassName.)this. For example in MainActivity.java:
Context mContext = MainActivity.this;
Activity mActivity = MainActivity.this;
I have passed context like this which solved my problem:
public class Utils extends ContextWrapper {
private final Context context;
public Utils(Context context) {
super(context);
this.context = context;
}
public void mymethod(){}
}
super(context); with ContextWrapper helped to make getBaseContext() and getApplicationContext() valid and this.context = context; captured context in variable which I can use wherever needed in methods.
Maybe alternatively you can just opt for using a constructor with this.context = context; and replace all occurrences of getApplicationContext() and getBaseContext().
Well, an even better way is to pass context directly to the method if using only few from a class for avoiding memory leaks.
You could also create a static instance reference to your MainActivity initialized in the onCreate() method
public class MainActivity extends AppCompatActivity {
public static MainActivity mMainActivity;
#Override
private onCreate(Bundle savedInstanceState){
//...
mMainActivity = this;
}
}
and call the context like this:
MainActivity.mMainActivity;
or write a method getInstanceOf() if it's clearer and/or you prefer using an accessor
MainActivity.getInstanceOf();
This strategy might provide you with some flexibility if you decide later that you would like to call an instance method contained in your main activity like so:
MainActivity.mMainActivity.myInstanceMethod();
Just a suggestion. Criticism is welcome and encouraged.