空对象引用上的空指针异常 [英] Null pointer exception on null object reference

查看:80
本文介绍了空对象引用上的空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在DessertAdapter类中从行holder.mName.setText(dessert.getName());开始不断收到空指针异常错误. 我尝试了所有已知的方法,但仍然遇到相同的错误. 这是Adapter

I keep getting a null pointer exception error at the DessertAdapter class starting at the line holder.mName.setText(dessert.getName()); I've tried all methods I know and I'm still getting the same error. Here is the Adapter class

public class DessertAdapter extends RecyclerView.Adapter<DessertAdapter.DessertVh> {
private List<Dessert> desserts = new ArrayList<>();
private static final int VIEW_TYPE_EMPTY_LIST_PLACEHOLDER = 0;
private static final int VIEW_TYPE_OBJECT_VIEW = 1;
private Context context;

@Override
public int getItemViewType(int position) {
    if (desserts.isEmpty()) {
        return VIEW_TYPE_EMPTY_LIST_PLACEHOLDER;
    } else {
        return VIEW_TYPE_OBJECT_VIEW;
    }
}
public DessertAdapter(Context context,List<Dessert> desserts) {
    this.context = context;
    this.desserts = desserts;      
}

// TODO: another placeholder stuff here
@Override
public DessertVh onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View view = inflater.inflate(R.layout.item_dessert, parent, false);
    return new DessertAdapter.DessertVh(view);
}

@Override
public void onBindViewHolder(DessertVh holder, int position) {
    Dessert dessert = desserts.get(position);
    System.out.println(position);

    holder.mName.setText(dessert.getName());
    holder.mDescription.setText(dessert.getDescription());
    holder.mFirstLetter.setText(String.valueOf(dessert.getFirstLetter()));
    holder.mPrice.setText(String.valueOf(dessert.getAmount()));
}

@Override
public int getItemCount() {
        return desserts == null ? 0 : desserts.size();
}

public static class DessertVh extends RecyclerView.ViewHolder {

    private TextView mName;
    private TextView mPrice;
    private TextView mDescription;
    private TextView mFirstLetter;

    public DessertVh(View itemView) {
        super(itemView);

        mName = (TextView) itemView.findViewById(R.id.txt_name);
        mPrice = (TextView) itemView.findViewById(R.id.txt_price);
        mDescription = (TextView) itemView.findViewById(R.id.txt_desc);
        mFirstLetter = (TextView) itemView.findViewById(R.id.txt_firstletter);
    }
}

这里是将数据保存到Dessert对象的类

Here is the class to save the data to the Dessert object

public class AddGigActivity  extends AppCompatActivity {
private static String TAG = "AddGigActivity";
private ImageButton saveBtn;
private EditText gigName, gigDescrip, gigAmount;
private String userID;
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private DatabaseReference myRef;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_gig);

    gigName = (EditText)findViewById(R.id.gig_name);
    gigDescrip = (EditText)findViewById(R.id.gig_description);
    gigAmount = (EditText) findViewById(R.id.gig_amnt);
    saveBtn = (ImageButton) findViewById(R.id.mybtn_add);
    mAuth = FirebaseAuth.getInstance();
    mFirebaseDatabase = FirebaseDatabase.getInstance();
    myRef =  FirebaseDatabase.getInstance().getReference();
    FirebaseUser user = mAuth.getCurrentUser();
    userID = user.getUid();
    saveBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            AddGig();
        }
    });

}


// real-time adding to the firebase database
private void AddGig(){
    String name = gigName.getText().toString();
    String descrip = gigDescrip.getText().toString();
    String amount = gigAmount.getText().toString();

    if((!TextUtils.isEmpty(name))&&(!TextUtils.isEmpty(descrip) && (!TextUtils.isEmpty(amount))) ){

        FirebaseUser user = mAuth.getCurrentUser();
        userID = user.getUid();
        String id =  myRef.push().getKey();
        Dessert dessert = new Dessert( name, descrip, amount);
       // myRef.child(id).setValue(dessert);
        myRef.child("users").child(userID).child("Gig posts").child(id).setValue(dessert);
        Toast.makeText(this, "Posted! ",Toast.LENGTH_LONG).show();
        finish();

    // you can still sprlit these to check for each text field
    }else{
        Toast.makeText(this, "One or more field(s) missing!",Toast.LENGTH_LONG).show();
    }
}

以下是主要活动代码段,该代码段在recycler视图上显示了来自Firebase的数据:

And here is the main activity code snippet that displays the data from firebase on the recycler view:

  public static class FeedsFragment extends Fragment {
    int color;

    public FeedsFragment() {
    }

    @SuppressLint("ValidFragment")
    public FeedsFragment(int color) {
        this.color = color;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dummy_fragment, container, false);
        final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.dummyfrag_scrollableview);
        final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.dummyfrag_bg);
        frameLayout.setBackgroundColor(color);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getBaseContext());
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setHasFixedSize(true);

        final List<Dessert> dessertList;
        dessertList = new ArrayList<>();
        //dessertList = new Dessert(context,"");


        final String curtUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();

        DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
       // DatabaseReference mDatabaseGig = rootRef.child("users").child(curtUserId).child("Gig posts");
        final String id = rootRef.push().getKey();

        final DessertAdapter adapter = new DessertAdapter(getContext(), dessertList);
        recyclerView.setAdapter(adapter);

        rootRef.addValueEventListener(new com.google.firebase.database.ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                dessertList.clear();
                for(DataSnapshot gigSnapshot: dataSnapshot.getChildren()){
                    Dessert dessert = gigSnapshot
                            .child("users")
                            .child(curtUserId)
                            .child("Gig posts")
                            .child(id).getValue(Dessert.class);
                    dessertList.add(dessert);
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        // possible to put progress dialogue
        return view;
    }
}

请介意看一下代码,并帮助我弄清楚代码吗?谢谢.

please would you mind taking a look at the code and help me straighten it out? Thank you.

推荐答案

好,所以我解决了! 这是代码

Ok, so I fixed it! here's the code

 public static class UserFeedFragment extends Fragment {
    int color;

    public UserFeedFragment() {
    }

    @SuppressLint("ValidFragment")
    public UserFeedFragment(int color) {
        this.color = color;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dummy_fragment, container, false);
        final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.dummyfrag_scrollableview);
        final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.dummyfrag_bg);
        frameLayout.setBackgroundColor(color);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getBaseContext());
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setHasFixedSize(true);

        String curtUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();

        DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference()
                .child("users")
                .child(curtUserId)
                .child("Gig posts");

        final List<Dessert> dessertList = new ArrayList<Dessert>();

        final DessertAdapter adapter = new DessertAdapter(getContext(), dessertList);
        recyclerView.setAdapter(adapter);

        rootRef.addValueEventListener(new com.google.firebase.database.ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                dessertList.clear();
                for(DataSnapshot gigSnapshot: dataSnapshot.getChildren()){

                    Dessert dessert = gigSnapshot
                            .getValue(Dessert.class);
                    dessertList.add(dessert);
                    adapter.notifyDataSetChanged();
                }
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        // possible to put progress dialogue
        return view;
    }
}

我所要做的就是在这里

 DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference()
                .child("users")
                .child(curtUserId)
                .child("Gig posts");

然后在此处添加事件监听器

then add an event listener here

rootRef.addValueEventListener(new com.google.firebase.database.ValueEventListener() {

成功了! 我确实有一个小问题.我有两个feed片段:UserFeed和FeedsFragments.用户供稿获取当前用户已发布的供稿,而FeedsFragment用于获取所有用户发布的供稿.我尝试这样做

and it worked! I do have a minor problem though. I have two feeds fragment: UserFeed and FeedsFragments. The Userfeed gets the feeds that the current user has posted while the FeedsFragment is meant to get feeds posted by all users. I tried doing this

 DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference()
                .child("users")
               // .child(curtUserId) I commented out the id of the user but nothing happened
                .child("Gig posts");

我的问题是:有没有一种方法可以定向"引用以检索所有用户的帖子? 再次感谢您的帮助!

My question is : is there a way I can "direct" the reference to retrieve posts by all users? Once again, thanks so much in advance for your help!

这篇关于空对象引用上的空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆