我有以下课程。调用readJson方法时,我在Android 6.0中收到空指针异常。如何修复NPE?在大多数设备和版本上都可以正常运行,但在Android 6.0上似乎无法使用。我已经搜索了答案,但是在代码中找不到问题。尝试访问Screens的变量时得到NPE。
public class UserRepository {
private static UserRepository instance = null;
final String TAG = UserRepository.class.getName();
public Resorts resortsData;
public AppSettings appSettingsData;
@Inject
public Resources resources;
public static synchronized UserRepository getInstance(){
if (instance == null){
instance = new UserRepository();
}
return instance;
}
public void readJson(){
FirebaseDatabase database = FirebaseDatabase.getInstance();
String lang = Locale.getDefault().getLanguage();
DatabaseReference myRef = database.getReference(lang);
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
resortsData = dataSnapshot.getValue(Resorts.class);
boolean hasChild = dataSnapshot.hasChild("appSettings");
if (hasChild){
DataSnapshot appSettings = dataSnapshot.child("appSettings");
appSettingsData = appSettings.getValue(AppSettings.class);
Log.e("NAG",appSettingsData.screens.toString());
}
//Resorts resortsData = resort.getValue(Resorts.class);
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
}
}
public class AppSettings {
public ArrayList<ApiEndpoints> apiEndpoints;
public Screens screens;
public GlobalStrings globalStrings;
}
public class Screens {
public RegisterStay registerStay;
public CalendarScreen calendar;
public RegisterError registerError;
public BookingNumber bookingNumber;
public InDestDashboard inDestDashboard;
public PreDestDashboard preDestDashboard;
public LocalExcursions localExcursions;
public PreDestMenu preDestMenu;
public InDestMenu inDestMenu;
public EmailSubscribe emailSubscribe;
public UnregisteredLanding unregisteredLanding;
}
错误消息
Caused by java.lang.NullPointerException: Attempt to read from field 'com.royalton.mobileapp.common.repositories.models.appSettings.screens.Screens com.royalton.mobileapp.common.repositories.models.appSettings.AppSettings.screens' on a null object reference
at com.royalton.mobileapp.base.AppModule.providesEmailSubscribeScreen(AppModule.java:192)
at com.royalton.mobileapp.base.AppModule_ProvidesEmailSubscribeScreenFactory.get(AppModule_ProvidesEmailSubscribeScreenFactory.java:19)
at com.royalton.mobileapp.base.AppModule_ProvidesEmailSubscribeScreenFactory.get(AppModule_ProvidesEmailSubscribeScreenFactory.java:8)