java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference

huangapple go评论69阅读模式
英文:

java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference

问题

private List<ParseObject> mRooms = new ArrayList<>();
private ArrayList<ParseObject> filterlist;
private ParseObject room;
private String mSection;
private Context context;

public RoomCardRecyclerViewAdapter(){
    super(DIFF_CALLBACK);
}
public static final DiffUtil.ItemCallback<ParseObject> DIFF_CALLBACK = new
DiffUtil.ItemCallback<ParseObject>() {
    @Override
    public boolean areItemsTheSame(@NonNull ParseObject oldItem, @NonNull ParseObject newItem) {
        return oldItem.getObjectId() == newItem.getObjectId();
    }

    @Override
    public boolean areContentsTheSame(@NonNull ParseObject oldItem, @NonNull ParseObject newItem) {
        return (oldItem.getUpdatedAt().equals(newItem.getUpdatedAt()) &&
                oldItem.getCreatedAt().equals(newItem.getCreatedAt()));
    }
};


public RoomCardRecyclerViewAdapter(String section) {
    this();
    this.mSection = section;
}
public RoomCardRecyclerViewAdapter(Context context, List<ParseObject> arrayList) {
    this();
    this.context = context;
    mRooms = arrayList;
    filterlist = (ArrayList<ParseObject>) arrayList;
}


public class RoomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
    protected ImageView mRoomImage;
    protected TextView mRoomPrice;
    protected TextView mInclusiveOrNot;
    protected TextView mPropertyType;
    protected TextView mNumOfBeds;
    protected TextView mNumOfBaths;
    protected TextView mRoomLocation;

    private Context context;

    public RoomViewHolder(Context context, View itemView) {
        super(itemView);
        mRoomImage = itemView.findViewById(R.id.room_image);
        mRoomPrice = itemView.findViewById(R.id.price_label);
        mInclusiveOrNot = itemView.findViewById(R.id.incl_excl_label);
        mPropertyType = itemView.findViewById(R.id.propertyType_label);
        mNumOfBeds = itemView.findViewById(R.id.num_beds_label);
        mNumOfBaths = itemView.findViewById(R.id.details_num_baths_label);
        mRoomLocation = itemView.findViewById(R.id.location_label);
        this.context = context;
        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // ... (click event handling)
    }
}

@Override
public RoomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.room_cardview, parent,
            false);
    return new RoomViewHolder(parent.getContext(), view);
}

@Override
public void onBindViewHolder(@NonNull RoomViewHolder holder, int position) {
    room = getItem(position);
    // ... (bind view holder with data)
}

@Override
public Filter getFilter() {
    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence charSequence) {
            // ... (perform filtering logic)
        }

        @Override
        protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
            // ... (update data and notify adapter)
        }
    };
}

// MainActivity
mHomeSectionsPagerAdapter = new
HomeSectionsPagerAdapter(getSupportFragmentManager());
roomCardRecyclerViewAdapter = new RoomCardRecyclerViewAdapter(this,
        mRooms);
mRooms = new ArrayList<>();
mViewPager = findViewById(R.id.container);
mViewPager.setAdapter(mHomeSectionsPagerAdapter);

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    final ParseQuery<ParseUser> query = ParseUser.getQuery();

    SearchManager searchManager = (SearchManager)
            getSystemService(Context.SEARCH_SERVICE);

    MenuItem item = menu.findItem(R.id.search);
    SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);

    searchView.setSearchableInfo(searchManager.getSearchableInfo
            (getComponentName());

    searchView.setSubmitButtonEnabled(true);

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            roomCardRecyclerViewAdapter.getFilter().filter(query);
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            roomCardRecyclerViewAdapter.getFilter().filter(newText);
            return false;
        }
    });

    return true;
}

@Override
public boolean onSearchRequested() {
    return super.onSearchRequested();
}
英文:

I m currently working on a android apps which fetch data from parse server. I wanted to filter my recyclerView by using searchview. But it shows me nothing while search. It gives me error in this line*for (ParseObject parseObject : mRooms){ * Please help me to edit my code regarding this issues.

roomcardrecyclerviewadapter

private List&lt;ParseObject&gt; mRooms = new ArrayList&lt;&gt;();
private ArrayList&lt;ParseObject&gt; filterlist;
private ParseObject room;
private String mSection;
private Context context;
public RoomCardRecyclerViewAdapter(){
super(DIFF_CALLBACK);
}
public static final DiffUtil.ItemCallback&lt;ParseObject&gt;  DIFF_CALLBACK = new 
DiffUtil.ItemCallback&lt;ParseObject&gt;() {
@Override
public boolean areItemsTheSame(@NonNull ParseObject oldItem, @NonNull ParseObject newItem) {
return oldItem.getObjectId() == newItem.getObjectId();
}
@Override
public boolean areContentsTheSame(@NonNull ParseObject oldItem, @NonNull ParseObject newItem) {
return (oldItem.getUpdatedAt().equals(newItem.getUpdatedAt()) &amp;&amp; 
oldItem.getCreatedAt().equals(newItem.getCreatedAt()));
}
};
public RoomCardRecyclerViewAdapter(String section) {
this();
this.mSection = section;
}
public RoomCardRecyclerViewAdapter(Context context, List&lt;ParseObject&gt;arrayList) {
this();
this.context = context;
mRooms = arrayList;
filterlist = (ArrayList&lt;ParseObject&gt;) arrayList;
}
public class RoomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
protected ImageView mRoomImage;
protected TextView mRoomPrice;
protected TextView mInclusiveOrNot;
protected TextView mPropertyType;
protected TextView mNumOfBeds;
protected TextView mNumOfBaths;
protected TextView mRoomLocation;
private Context context;
public RoomViewHolder(Context context, View itemView) {
super(itemView);
mRoomImage = itemView.findViewById(R.id.room_image);
mRoomPrice = itemView.findViewById(R.id.price_label);
mInclusiveOrNot = itemView.findViewById(R.id.incl_excl_label);
mPropertyType = itemView.findViewById(R.id.propertyType_label);
mNumOfBeds = itemView.findViewById(R.id.num_beds_label);
mNumOfBaths = itemView.findViewById(R.id.details_num_baths_label);
mRoomLocation = itemView.findViewById(R.id.location_label);
this.context = context;
//set onclick listener
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Log.i(&quot;Click event: &quot;, &quot;My room has been clicked.&quot;);
int pos = getAdapterPosition();
Intent intent;
ParseObject room = getCurrentList().get(pos);
//create the ParseObject proxy
ParseProxyObject roomProxy = new ParseProxyObject(room);
Toast.makeText(context, room.getString(&quot;roomSuburb&quot;), Toast.LENGTH_LONG).show();
//fork to corresponding activity
if(mSection != null) {
Log.i(&quot;mSection text: &quot;, &quot;mSection text is: &quot; + mSection);
if (mSection.equals(&quot;My Rooms&quot;)) {
//start my rooms detail activity
Log.i(&quot;My room: &quot;, &quot;Room selected &quot; + roomProxy.getObjectId());
intent = new Intent(context, MyRoomDetailActivity.class);
//add the room to the intent
intent.putExtra(&quot;currentSelectedRoomObject&quot;, room);
Log.i(&quot;Selected room&quot;, &quot;Put Extra, &quot; + room);
intent.putExtra(&quot;roomObject&quot;, roomProxy);
context.startActivity(intent);
}
}else {
Log.i(&quot;My room:&quot;, &quot;RoomDetailActivity loaded for MyRoomDetail Activity instead&quot;);
intent = new Intent(context, RoomDetailActivity.class);
//add the proxy to the intent
intent.putExtra(&quot;roomObject&quot;, roomProxy);
context.startActivity(intent);
}
}
}
@Override
public RoomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//inflating the viewholder with the appropriate views
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.room_cardview, parent, 
false);
return new RoomViewHolder(parent.getContext(), view);
}
@Override
public void onBindViewHolder(@NonNull RoomViewHolder holder, int position) {
room = getItem(position);
holder.mRoomLocation.setText(room.getString(&quot;roomSuburb&quot;));
holder.mRoomPrice.setText(Integer.toString(room.getInt(&quot;roomMonthlyRent&quot;)));
holder.mInclusiveOrNot.setText(room.getString(&quot;roomRentInclusiveOfBills&quot;));
holder.mPropertyType.setText(room.getString(&quot;roomPropertyType&quot;));
holder.mNumOfBeds.setText(Integer.toString(room.getInt(&quot;roomBedrooms&quot;)));
holder.mNumOfBaths.setText(Integer.toString(room.getInt(&quot;roomBathrooms&quot;)));
@Override
public Filter getFilter(){
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()){
room = (ParseObject) mRooms;
}else {
List&lt;ParseObject&gt; filteredList = new ArrayList&lt;&gt;();
for (ParseObject parseObject : mRooms){
if (parseObject.getString(&quot;roomSuburb&quot;).toLowerCase().contains(charString.toLowerCase())){
filteredList.add(parseObject);
}
}
room = (ParseObject) filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = room;
return filterResults;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
room = (ParseObject) filterResults.values;
notifyDataSetChanged();
}
};
}

mainActivity

mHomeSectionsPagerAdapter = new 
HomeSectionsPagerAdapter(getSupportFragmentManager());
roomCardRecyclerViewAdapter = new RoomCardRecyclerViewAdapter(this, 
mRooms);
mRooms = new ArrayList&lt;&gt;();
// Set up the ViewPager with the sections adapter.
mViewPager = findViewById(R.id.container);
mViewPager.setAdapter(mHomeSectionsPagerAdapter);
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
final ParseQuery&lt;ParseUser&gt; query = ParseUser.getQuery();
//get the search view and set the searchable configuration
SearchManager searchManager = (SearchManager) 
getSystemService(Context.SEARCH_SERVICE);
MenuItem item = menu.findItem(R.id.search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
//assumes the current activity is the searchable activity
searchView.setSearchableInfo(searchManager.getSearchableInfo
(getComponentName());
searchView.setSubmitButtonEnabled(true);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
roomCardRecyclerViewAdapter.getFilter().filter(query);
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
roomCardRecyclerViewAdapter.getFilter().filter(newText);
return false;
}
});
return true;
}
@Override
public boolean onSearchRequested() {
//pauseSomeStuff();
//roomCardRecyclerViewAdapter.getFilter().filter(query);
return super.onSearchRequested();
}

答案1

得分: 1

我认为问题出在这里:

您尚未共享“MainActivity”中声明变量的第一行代码。因此,我假设您有类似以下的一些代码:

List mRooms;

然后,我假设在给这个mRooms赋值之前,您已将其传递给了RoomCardRecyclerViewAdapter

roomCardRecyclerViewAdapter = new RoomCardRecyclerViewAdapter(this, mRooms);
mRooms = new ArrayList<>();

然后,您已经给mRooms赋了值。这就是为什么会出现NPE的原因。您可以像这样解决这个问题:

mRooms = new ArrayList<>();
roomCardRecyclerViewAdapter = new RoomCardRecyclerViewAdapter(this, mRooms);
英文:

I think problem is here:

You haven't shared first lines of MainActivity where you declare your variables. So, I assume that you have some code like this:

List mRooms;

Then I assume that, before assigning value to this mRooms you have passed it to RoomCardRecyclerViewAdapter:

roomCardRecyclerViewAdapter = new RoomCardRecyclerViewAdapter(this, mRooms);
mRooms = new ArrayList&lt;&gt;();

Then you have assigned value to mRooms. That's why you get NPE. You can solve this problem just like this:

mRooms = new ArrayList&lt;&gt;();
roomCardRecyclerViewAdapter = new RoomCardRecyclerViewAdapter(this, mRooms);

huangapple
  • 本文由 发表于 2020年10月3日 17:02:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/64182485.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定