在Application类对象上调用getSystemService()时出现NullPointerException

时间:2015-03-11 09:47:01

标签: android

NotesApplication扩展了Application类。 因此,调用getApplicationContext()。getSystemService()会抛出NullPointerException。

@Override
    public View getView(int position, View convertView, ViewGroup   parent) {
        ViewHolder holder;

        if(convertView == null){
            NotesApplication context = NotesApplication.getInstance();


            Object Object;
            try{
                if(context != null)
                Object = context.getApplicationContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            }
            catch(Exception e){

            }
}

NotesApplication:

public class NotesApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        Values passwordSaved = isPasswordSaved();
        launchActivity(passwordSaved);
    }

    private static class  AppInstanceHolder{

        public static NotesApplication notesApp =  new NotesApplication();

    }
    public static NotesApplication getInstance(){
        if(AppInstanceHolder.notesApp == null)
            AppInstanceHolder.notesApp =  new NotesApplication();


        return AppInstanceHolder.notesApp;
    }
}

1 个答案:

答案 0 :(得分:1)

在您的代码中NotesApplication对象不是当前的Application对象

所以改变你的NotesApplication类,如下所示

 public class NotesApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        notesApp = NotesApplication.this;
        Values passwordSaved = isPasswordSaved();
        launchActivity(passwordSaved);

    }


    public static NotesApplication notesApp;

    public static NotesApplication getInstance() {
        return notesApp;
    }
}