我有一个Main类和另外两个名为WebServicesClass和DynamicHeightAdpater的类。
我在WebServicesClass中创建了一个DynamicHeightAdpater实例,我需要MainActivity的上下文,但我不确定如何指出它。我调用的方式抛出NullPointerException。
代码:
MainActivity:
static Context context;
context = this.context;
WebServicesClass:
new DynamicHeightAdapter(MainActivity.context, 1, rowItems);
但它抛出一个空指针异常,我确信这是由于上下文原因我试图打印它并抛出NullPointer。
答案 0 :(得分:2)
我建议你看看Android application class。您可以在那里存储上下文并在需要时检索它:
public class TestApplication extends Application {
private static Context mAppContext;
@Override
public void onCreate() {
super.onCreate();
mAppContext = getApplicationContext();
}
/**
* Returns the application's context. Useful for classes that need a Context
* but don't inherently have one.
*
* @return application context
*/
public static Context getAppContext() {
return mAppContext;
}
答案 1 :(得分:0)
我建议将Context传递给它的构造函数中的WebServicesClass
对象,并有一个成员变量来保存它...类似
public class WebServicesClass
{
private Context mContext;
...
public WebServicesClass(Context c) // constructor
{
mContext = c;
}
void someOtherFunction()
{
new DynamicHeightAdapter(mContext, 1, rowItems);
}
}