简单的ViewModel项目中的NullPointerException

问题描述 投票:0回答:1

我为了保存任意对象的数据,我创建了一个ViewHolder模式。但是,我一直在通过ViewHolder获取NullPointerException。


简单的对象类

public class Action {

public Action() {
}

public String activity;

}

视图模型:

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;
}

}

活动(qazxsw poi上的空指针):

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;
        });

请检查代码并帮助我,因为我已经尝试了我自己记住的一切。谢谢。

java android mvvm data-binding android-livedata
1个回答
0
投票

要实例化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) ,你需要一个ViewModel

ViewModelFactory

ViewModelFactory

@Inject
ViewModelProvider.Factory viewModelFactory;

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

ViewModelKey

    @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);
        }
    }
}

ViewModel模块

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

注意:上面的代码使用@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); }

© www.soinside.com 2019 - 2024. All rights reserved.