无法在单例类中传递应用程序上下文?

时间:2017-11-27 04:44:51

标签: android singleton

我有一个应用程序,我在其中创建了一个获取AdvertId的单例类。但我无法通过Application上下文。我该怎么做,请检查我的代码并指导我?

  

Singleton类代码: -

private static AdIdFetcher ourInstance = null;
public static Context context;
private static String TAG = AdIdFetcher.class.getSimpleName();

interface AdIdFetcherResult {
    void onId(String advertId);
}

public AdIdFetcher(Context context) {
    this.context = context;
}

public static AdIdFetcher getOurInstance() {
    if (ourInstance == null) {
        ourInstance = new AdIdFetcher(context);
    }
    return ourInstance;
}

public void fetchId(final AdIdFetcherResult rcb) {
    AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... params) {
            AdvertisingIdClient.Info id_Info = null;
            try {
                id_Info = AdvertisingIdClient.getAdvertisingIdInfo(context);
            } catch (IOException | GooglePlayServicesNotAvailableException | GooglePlayServicesRepairableException e) {
                e.printStackTrace();
            }
            String advertId = null;
            try {
                assert id_Info != null;
                advertId = id_Info.getId();
                Log.e(TAG, "Advertisement Id::::" + advertId);

            } catch (NullPointerException e) {
                e.printStackTrace();
            }
            rcb.onId(advertId);
            return advertId;
        }
    };
    task.execute();
}
  

调用类代码: -

 AdIdFetcher.getOurInstance().fetchId(new AdIdFetcher.AdIdFetcherResult() {
        @Override
        public void onId(String advertId) {
            Log.e(TAG,"Advert ID:::"+advertId);
        }
    });
  

logcat的

Caused by: java.lang.NullPointerException: null reference

3 个答案:

答案 0 :(得分:0)

您需要在调用getOurInstance()

时传递Context
public static AdIdFetcher getOurInstance(Context context) {
    if (ourInstance==null){
        ourInstance=new AdIdFetcher(context);
    }
    return ourInstance;
}

并将其称为

AdIdFetcher.getOurInstance(context).fetchId(new AdIdFetcher.AdIdFetcherResult() {
        @Override
        public void onId(String advertId) {
            Log.e(TAG,"Advert ID:::"+advertId);
        }
});

答案 1 :(得分:0)

将上下文保持为静态字段会导致内存泄漏并且很糟糕,您不应该这样做,而是在fetchId方法本身中传递上下文。

public void fetchId(Context context, final AdIdFetcherResult rcb)

答案 2 :(得分:0)

我认为你的调用代码是在Activity或任何Fragment中吗?

  1. 如果是碎片:

    传递上下文&#34; getOurInstance()&#34;像这样:

    AdIdFetcher.getOurInstance(getActivity()).fetchId(.....
    ......
    
  2. 如果是活动:

    传递上下文&#34; getOurInstance()&#34;像这样:

    AdIdFetcher.getOurInstance(classname.this).fetchId(.....
    ......
    
  3. 并在单件类中传递如下:

    public static AdIdFetcher getOurInstance(Context context) {
      if (ourInstance==null){
        ourInstance=new AdIdFetcher(context);
      }
      return ourInstance;
    }
    

    并且您的代码存在问题,您在构造函数中获取上下文但从未在调用活动中调用该构造函数。