NullPointerException в простом проекте ViewModel - PullRequest
0 голосов
/ 18 сентября 2018

Я приказываю сохранить данные произвольного объекта, я создал шаблон ViewHolder.Тем не менее, я продолжаю получать NullPointerException с помощью моего ViewHolder.


Класс простого объекта

public class Action {

public Action() {
}

public String activity;

}

ViewModel:

public class Action_ViewModel extends ViewModel{

public Action action;

public Action_ViewModel () {
    Action action = new Action();
}

public Action getAction() {
    return action;
}

public void setActivity(String activity) {
    action.activity = activity;
}

}

Activity(NullPointer on vm.setActivity):

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        savedInstanceState.getBoolean(STATE_CHOOSER);

    setContentView(R.layout.create_actions);

    Action_ViewModel vm = ViewModelProviders.of(this).get(Action_ViewModel.class);

    //Autocomplete za select Actiona
    AutoCompleteTextView chooser = findViewById(R.id.choose_action_complete);
    String[] allActions = getResources().getStringArray(R.array.autocomplete_createAction);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, allActions);
    chooser.setAdapter(adapter);
    chooser.setOnItemClickListener((AdapterView<?> parent, View view, int p

osition, long id) -> {
            vm.setActivity(allActions[position]);
            ACTION_CHOOSER = true;
        });

Трассировка стека:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.android.activities, PID: 15667
                  java.lang.NullPointerException: Attempt to write to field 'java.lang.String com.example.android.activities.Action.activity' on a null object reference
                      at com.example.android.activities.Action_ViewModel.setActivity(Action_ViewModel.java:22)
                      at com.example.android.activities.CreateAction.lambda$onCreate$0$CreateAction(CreateAction.java:35)
                      at com.example.android.activities.CreateAction$$Lambda$0.onItemClick(Unknown Source:46)
                      at android.widget.AutoCompleteTextView.performCompletion(AutoCompleteTextView.java:1017)
                      at android.widget.AutoCompleteTextView.-wrap1(Unknown Source:0)
                      at android.widget.AutoCompleteTextView$DropDownItemClickListener.onItemClick(AutoCompleteTextView.java:1313)
                      at android.widget.AdapterView.performItemClick(AdapterView.java:318)
                      at android.widget.AbsListView.performItemClick(AbsListView.java:1165)
                      at android.widget.AbsListView$PerformClick.run(AbsListView.java:3134)
                      at android.widget.AbsListView$3.run(AbsListView.java:4049)
                      at android.os.Handler.handleCallback(Handler.java:789)
                      at android.os.Handler.dispatchMessage(Handler.java:98)
                      at android.os.Looper.loop(Looper.java:164)
                      at android.app.ActivityThread.main(ActivityThread.java:6541)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

Пожалуйста, проверьте код и помогите мне с этим, поскольку я перепробовал все, что мог вспомнить сам,Спасибо.

1 Ответ

0 голосов
/ 18 сентября 2018

Чтобы создать экземпляр ViewModel, вам нужен ViewModelFactory

@Inject
ViewModelProvider.Factory viewModelFactory;

Action_ViewModel vm = ViewModelProviders.of(this, viewModelFactory).get(modelClass)

ViewModelFactory

    @Singleton
    public class ViewModelFactory implements ViewModelProvider.Factory {

    private final Map<Class<? extends ViewModel>, Provider<ViewModel>> creators;

    @Inject
    public ViewModelFactory(Map<Class<? extends ViewModel>, Provider<ViewModel>> creators) {
        this.creators = creators;
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T extends ViewModel> T create(Class<T> modelClass) {
        Provider<? extends ViewModel> creator = creators.get(modelClass);
        if (creator == null) {
            for (Map.Entry<Class<? extends ViewModel>, Provider<ViewModel>> entry : creators.entrySet()) {
                if (modelClass.isAssignableFrom(entry.getKey())) {
                    creator = entry.getValue();
                    break;
                }
            }
        }
        if (creator == null) {
            throw new IllegalArgumentException("unknown model class " + modelClass);
        }
        try {
            return (T) creator.get();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

ViewModelKey

@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@MapKey
public @interface ViewModelKey {
    Class<? extends ViewModel> value();
}

Модуль ViewModel

@Module
public abstract class ViewModelModule {

    @Binds
    @IntoMap
    @ViewModelKey(Action_ViewModel.class)
    public abstract ViewModel bindsHomeActivityModel(Action_ViewModel actionViewModel);

    @Binds
    public abstract ViewModelProvider.Factory viewModelFactoryProvider(ViewModelFactory factory);

}

Примечание: в приведенном выше коде используется Dagger

...