应用程序扩展类返回null

时间:2018-04-23 07:51:42

标签: android

在我的Android应用程序中,MyApp类扩展了Application类,如下所示:

public class MyApp extends Application {
   private static MyApp instance;

   public static MyApp getInstance() {
      return instance;
   }

   @Override
   public void onCreate() {
     super.onCreate();
     instance = this;    
   }
}

在AndroidManifest.xml中声明

<application android:name="com.mypackage.mypackage.MyApp">...</application>

从活动类访问时如下:

MyApp.getInstance()

返回null并导致Nullpointer异常,有时主要在Android 7.0版中。 我认为这可能是因为应用程序被杀死了。那么我应该如何重新启动应用程序类,以便getInstance()返回非空值。

3 个答案:

答案 0 :(得分:1)

  

当应用程序尝试使用时抛出NullPointerException   具有空值的对象引用。

您应该传递当前活动名称。

 MyApp.getInstance(YourActivityName.this) // You should pass Context

要获得良好的方法,请使用 synchronized

  

Java中的同步块在某个对象上同步。所有   在同一对象上同步的同步块只能有一个   线程一次在它们内部执行。

public static synchronized MyApp getInstance() {
        return instance ;
    }

答案 1 :(得分:0)

试试这个

public class MyApp extends Application {
public static MyApp instance;
static Context mContext;


public static MyApp getInstance() {
if (instance== null)
        instance= (MyApp) mContext;
  return instance;
}

@Override
public void onCreate() {
 super.onCreate();
 mContext = this;  
}
}

答案 2 :(得分:0)

我希望这对你有用

public static synchronized MyApp getInstance() {
    return mInstance;
}

在这样的活动访问中,假设为Toast(for Context)

Toast.makeText(MyApp.getInstance(), "hello",Toast.LENGTH_SHORT).show();
相关问题