Ich habe eine App, in der ich eine Singleton-Klasse gemacht habe, die AdvertId
holen. Aber ich bin nicht in der Lage Application
Kontext zu übergeben. Wie überprüfe ich meinen Code und führe mich auch?Konnte Anwendungskontext in der Singleton-Klasse nicht übergeben werden?
Singleton Klassencode: -
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();
}
Berufung Klassencode: -
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
Wo in Ihrem Code stellen Sie den Kontext ein? 'public AdIdFetcher (Kontext Kontext) { this.context = Kontext; } 'erstellen Sie Objekt von AdIdFetcher mit dem obigen Konstruktor vor dem Aufruf von getOurInstance – Sanjeet
Das ist, was ich – Niraj
an dieser Zeile setzen möchte: - ID_Info = AdvertisingIdClient.getAdvertisingIdInfo (Kontext); – Niraj