【问题标题】:Viewmodel null after initializingViewmodel 初始化后为空
【发布时间】:2022-01-10 07:29:13
【问题描述】:

初始化 ViewModel 后,我不断收到空对象引用错误,我不知道为什么

import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;

import com.example.foodapp.models.Recipe;
import com.example.foodapp.respositories.RecipeRepository;

public class RecipeViewModel extends ViewModel {

    private String mRecipeId;

    private RecipeRepository mRecipeRepository;

    public RecipeViewModel() {
        mRecipeRepository=RecipeRepository.getInstance();
    }

    public LiveData<Recipe>getRecipe(){
        return mRecipeRepository.getRecipe();
    }

    public void searchRecipeById(String recipeId)
    {  mRecipeId = recipeId;
mRecipeRepository.searchRecipeById(recipeId);
    }

    public String getViewModelRecipeId() {
        return mRecipeId;
    }
}







import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.foodapp.models.Recipe;
import com.example.foodapp.viewmodels.RecipeViewModel;

public class RecipeActivity extends BaseActivity {
    private static final String TAG = "RecipeActivity";
    private AppCompatImageView  mRecipeImage;
    private TextView mRecipeTitle ,mRecipeRank;
    private LinearLayout mRecipeIngredientsContainer;

    private ScrollView mScrollView;
    private  RecipeViewModel mRecipeViewModel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recipe);
        mRecipeImage=findViewById(R.id.recipe_image);
        mRecipeTitle=findViewById(R.id.recipe_title);
        mRecipeRank=findViewById(R.id.recipe_social_score);
        mRecipeIngredientsContainer=findViewById(R.id.ingredients_container);
        mScrollView=findViewById(R.id.parent);

        mRecipeViewModel=new ViewModelProvider(this).get(RecipeViewModel.class);

        showProgressBar(true);
        subscribeObserver();
        getIncomingIntent();
    }

    private void getIncomingIntent(){
        if(getIntent().hasExtra("recipe")){
            Recipe recipe=getIntent().getParcelableExtra("recipe");
            Log.d(TAG, "getIncomingIntent: "+recipe.getTitle());
            mRecipeViewModel.searchRecipeById(recipe.getRecipeId());
        }
    }

private void subscribeObserver(){

        mRecipeViewModel.getRecipe().observe(this, new Observer<Recipe>() {
            @Override
            public void onChanged(Recipe recipe) {
                if(recipe!=null){
                    if(recipe.getRecipeId().equals(mRecipeViewModel.getViewModelRecipeId())){
                        setRecipeProperties(recipe);
                    }
                }

            }
        });
}

        private void setRecipeProperties(Recipe recipe){

        if(recipe!=null){

            RequestOptions requestOptions= new RequestOptions()
                    .placeholder(R.drawable.ic_launcher_background);

            Glide.with(this).setDefaultRequestOptions(requestOptions)
                    .load(recipe.getImageUrl()).into(mRecipeImage);
            mRecipeTitle.setText(recipe.getTitle());
            mRecipeRank.setText(String.valueOf(recipe.getSocialUrl()));
            mRecipeIngredientsContainer.removeAllViews();
            for(String ingredients: recipe.getIngredients()){
                TextView textView= new TextView(this);
                textView.setText(ingredients);
                textView.setTextSize(15);
                textView.setLayoutParams(new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT
                ));
                mRecipeIngredientsContainer.addView(textView);
            }
        }
        showParent();
        showProgressBar(false);
}

private void showParent(){
        mScrollView.setVisibility(View.VISIBLE);
}
}

这是我得到的例外:

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
        at com.example.foodapp.RecipeActivity$1.onChanged(RecipeActivity.java:63)
        at com.example.foodapp.RecipeActivity$1.onChanged(RecipeActivity.java:57)
        at androidx.lifecycle.LiveData.considerNotify(LiveData.java:133)
        at androidx.lifecycle.LiveData.dispatchingValue(LiveData.java:151)
        at androidx.lifecycle.LiveData.setValue(LiveData.java:309)
        at androidx.lifecycle.MutableLiveData.setValue(MutableLiveData.java:50)..etc

模型类:

import android.os.Parcel;
import android.os.Parcelable;

import java.util.Arrays;

public class Recipe implements {
    private String title;
    private String publisher;
    private String imageUrl;
    private String id;
    private String [] ingredients;
    private float socialUrl;

    public Recipe() {
    }

    public Recipe(String title, String publisher, String image_url, String id,
                  String[] ingredients, float socialUrl) {
        this.title = title;
        this.publisher = publisher;
        this.imageUrl = image_url;
        this.id = id;
        this.ingredients = ingredients;
        this.socialUrl = socialUrl;
    }

    
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getPublisher() {
        return publisher;
    }

    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    public String getRecipeId() {
        return id;
    }

    public void setRecipeId(String id) {
        this.id = id;
    }

    public String[] getIngredients() {
        return ingredients;
    }

    public void setIngredients(String[] ingredients) {
        this.ingredients = ingredients;
    }

    public float getSocialUrl() {
        return socialUrl;
    }

    public void setSocialUrl(float socialUrl) {
        this.socialUrl = socialUrl;
    }

    @Override
    public String toString() {
        return "Recipe{" +
                "title='" + title + '\'' +
                ", publisher='" + publisher + '\'' +
                ", image_url='" + imageUrl + '\'' +
                ", recipe_id='" + id + '\'' +
                ", ingredients=" + Arrays.toString(ingredients) +
                ", social_rank=" + socialUrl +
                '}';
    }}

我已经尝试清理项目并使无效和缓存,甚至使用已弃用的 ViewModelProviders 类,

但一切都一样,没有任何改变

【问题讨论】:

  • 你能发布你的异常的堆栈跟踪吗
  • 我用完整的跟踪更新了帖子
  • 你能贴出Recipe的型号代码吗?
  • 已添加
  • 在您的主要活动代码中,首先调用 getIncomingIntent() 然后调用 subscribeObserver()

标签: java android viewmodel


【解决方案1】:
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_recipe);
    mRecipeImage=findViewById(R.id.recipe_image);
    mRecipeTitle=findViewById(R.id.recipe_title);
    mRecipeRank=findViewById(R.id.recipe_social_score);
    mRecipeIngredientsContainer=findViewById(R.id.ingredients_container);
    mScrollView=findViewById(R.id.parent);

    mRecipeViewModel=new ViewModelProvider(this).get(RecipeViewModel.class);

    showProgressBar(true);
    getIncomingIntent(); //this method needs to be called first
    subscribeObserver(); // then this method.
   
}

【讨论】:

  • 仍然出现同样的错误
  • 将日志放入 onChanged() 方法并检查您是否获得 mRecipeViewModel.getViewModelRecipeId() 的任何值。
  • 不,我没有得到任何价值
  • 那是你的错误。
  • 当我已经使用 viewmodelprovider 初始化它时,我不明白如何获得空值
猜你喜欢
  • 2014-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-26
  • 2014-09-30
  • 2021-12-19
  • 1970-01-01
相关资源
最近更新 更多