Android Firebase RecyclerView Adapter Remove Views - java

I am facing a Firebase RecyclerView problem where I cannot remove unwanted CardViews from my RecyclerViews. In my code I check the city's name and the guide's chosen city to match them. It populates guide's details only if the guide's city matches the picked city, but it also shows empty cardview with default layout.
guideDataRef = FirebaseDatabase.getInstance().getReference().child("Guides");
public void recycler() {
super.onStart();
try {
//Guide RecyclerView
Query guideQuery = guideDataRef.orderByKey();
guideQuery.keepSynced(true);
FirebaseRecyclerOptions guideOptions =
new FirebaseRecyclerOptions.Builder<UserModelClass>().setQuery(guideQuery, UserModelClass.class).build();
guideAdapter = new FirebaseRecyclerAdapter<UserModelClass, guideViewHolder>(guideOptions) {
#Override
protected void onBindViewHolder(#NonNull guideViewHolder holder, final int position, #NonNull final UserModelClass model) {
String pickedcity = model.getPickedCity();
String postname = (String) cityName.getText();
if(pickedcity.equals(postname)) {
final String guide_key= getRef(position).getKey();
holder.setGuideName(model.getName());
holder.setGuideSurname(model.getSurName());
holder.setGuideImage(getApplicationContext(), model.getPhotoURL());
// holder.mView.setVisibility(View.VISIBLE);
//Guide Click listener
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent guideHireIntent = new Intent(getApplication(), GuideHireActivity.class);
guideHireIntent.putExtra("guide_id", guide_key);
finish();
startActivity(guideHireIntent);
}
});
}
}
#NonNull
#Override
public guideViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout_guides, parent, false);
return new guideViewHolder(view);
}
#Override
public void onError(DatabaseError e){
Toast.makeText(getApplicationContext(), "Error by stopping ", Toast.LENGTH_SHORT).show();
}
#Override
public int getItemCount() {
return super.getItemCount();
}
#Override
public void onDataChanged() {
super.onDataChanged();
notifyDataSetChanged();
}
};
guideAdapter.notifyDataSetChanged();
guideRecyclerView.setAdapter(guideAdapter);
guideAdapter.startListening();
} catch (DatabaseException e) {
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
}
}
enter image description here
enter image description here
I can change the adapter visibility to gone if it does not match with the requirements but the problem is that after making it's visibility gone it is still there holding the place (but invisible - there's still an empty space). How can I avoid populating an item from the recycler view completely, instead of making it invisible if the requirements do not match?

You're not showing what guideDataRef is in your code, so I'm assuming that it's just aDatabaseReference object for everything beneath a \Guides node.
If you're doing that, you're going to get a call for onBindViewHolder for every child at that particular location. This means that you're going to be asked to make a view for every child. You cannot choose whether or not a view will appear for that item.
It looks like you're assuming that your if statement in onBindViewHolder method will skip over those items. But what's actually happening is that you're simply allowing an empty view to occupy that spot in the list.
Instead, you should come up with a query that generates only the items of interest to your list. This means you'll have to tell Firebase to filter for children that meet your criteria.
You can also read the entire contents of the location, manually filter out the items you don't want, and build a list of items you do want. You can then build an custom adapter with that list, and it can then become the input to a ListView or even better to a RecyclerView.

Related

Firebase android studio get id on ListView items

first time using Firebase and pretty new to android studio, i'm trying to make a schedule app where a user can create many schedules and it would be associated to their account.
At the moment a user can create an account, create a schedule (i just have 2 fields for this, will add the rest once i get the issue sorted) and also have multiple schedules.
I would like to be able to update/delete a schedule of a user but i'm struggling to get the ID of the specific schedule node in which I need to delete.
This is what i have in Firebase with a single user and 2 schedules
I added a toast when i long click a list item which displays the corresponding scheduleId of that schedule. keep in mind this is to help so i can just long click and show if the item displays the proper scheduleId.
Part of ScheduleActivity.java
What the problem is
I have a listView with all the schedules that has a listener
In the listener I have this line which gets the ID, but the issue is since its on the listener, i wont get the ID of the schedule until i click the list item and view the details, then Im only able to view the scheduleId, otherwise i get a NULL value.
scheduleId = scheduleList.get(position).getScheduleId();
public class ScheduleActivity extends AppCompatActivity implements View.OnClickListener {
private List<Schedule> scheduleList;
private List<String> scheduleIdList;
private DatabaseReference scheduleReference;
private String userId;
public static final String SCHEDULE_TITLE = "title";
public static final String SCHEDULE_DESCRIPTION = "description";
private String scheduleId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
getSupportActionBar().hide();
scheduleList = new ArrayList<>();
scheduleIdList = new ArrayList<>();
userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
scheduleReference = FirebaseDatabase.getInstance().getReference(DBStrings.DB_SCHEDULES);
registerForContextMenu(scheduleListView);
// when a user clicks any of list items
scheduleListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Schedule schedule = scheduleList.get(position);
// this gets the id but the issue is i need to first click the list item then ill get the correct id, otherwise i get a NPE because i haven't accessed the list item yet
// need to figure out how to implement this in the onStart() method so i can get the scheduleId beforehand
scheduleId = scheduleList.get(position).getScheduleId();
// intent that takes me to the activity to view the schdule details
Intent viewSchedule = new Intent(ScheduleActivity.this, ViewSchedule.class);
viewSchedule.putExtra(SCHEDULE_TITLE, schedule.getTitle());
viewSchedule.putExtra(SCHEDULE_DESCRIPTION, schedule.getDescription());
startActivity(viewSchedule);
}
}
});
}
// when a user long clicks a list item, brings up menu with option to edit/delete
// Also display a toast with scheduleID so i can see if the proper id is being retrieved
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
Toast.makeText(ScheduleActivity.this, "id: " + scheduleId, Toast.LENGTH_SHORT).show();
getMenuInflater().inflate(R.menu.schedule_menu, menu);
}
// switch statement for delete/ redirect to edit activity that i left out
// load schedule data into list view
#Override
protected void onStart() {
super.onStart();
scheduleReference.child(userId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
scheduleList.clear();
scheduleIdList.clear();
for(DataSnapshot dataSnapshot : snapshot.getChildren()) {
Schedule schedule = dataSnapshot.getValue(Schedule.class);
// add schedules to list to show in list view
scheduleList.add(schedule);
// Add all the ids of schedules in a list, i used this in my scheduleListView.setOnItemListener to grab the scheduleId.
scheduleIdList.add(schedule.getScheduleId());
}
System.out.println("id list: " + scheduleIdList);
ScheduleListAdapter adapter = new ScheduleListAdapter(ScheduleActivity.this, scheduleList);
scheduleListView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
System.out.println("ERROR: " + error.toException());
}
});
}
private void deleteSchedule(String scheduleId) {
// At the moment i can only delete a item if i first view it by clicking, then i need to go back and it allows me to delete it, this is obviously because my listview listener issue (It does not let me delete without first clicking the item to view/access it) scheduleReference.child(userId).child(scheduleId).removeValue();
Toast.makeText(ScheduleActivity.this, "Schedule " + scheduleId + " was deleted!", Toast.LENGTH_LONG).show();
}
}
List view of schedules
The issue is in the scheduleListView.setOnItemClickListener , i need to find a way to grab the id maybe in onStart method or somewhere eother than the listener, but since I do not have access to the position like i did here, i am struggling to implement this.
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Schedule schedule = scheduleList.get(position);
// Talking about this <position>
scheduleId = scheduleList.get(position).getScheduleId();
}
Images to explain it better
I hope it makes sense, i would need to access each list item then go back to be able to delete a specific one.

Why firebase recyclerview is not working correctly?

I try to open each video when I click on them but what I get instead is only the second video (sometimes first video). For example, when I click on "16 best video ideas for small business" I want it to open that particular video. But what I get instead is "this tiny camera can show the world from a bug's point of view. I think the problem occurs because of for loop inside query in UserHomeVideoAdapter.
UserHomeVideoAdapter.java:
public class UserHomeVideoAdapter extends FirestoreRecyclerAdapter<FollowList, UserHomeVideoAdapter.UserVideoHolder> {
Context context;
final FirebaseFirestore db = FirebaseFirestore.getInstance();
String thumbUrl, videoTitle, videoUrl, videoDesc, videoId, publisherId;
Video video;
public UserHomeVideoAdapter(#NonNull #NotNull FirestoreRecyclerOptions<FollowList> options, Context context) {
super(options);
this.context = context;
}
#Override
protected void onBindViewHolder(#NonNull #NotNull UserVideoHolder holder, int position, #NonNull #NotNull FollowList model) {
Query query = db.collection("Videos").whereEqualTo("publisherId", model.getUserId());
query.get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
if (task.getResult() != null) {
for (QueryDocumentSnapshot documentSnapshot : task.getResult()) {
video = documentSnapshot.toObject(Video.class);
Log.d("Data", documentSnapshot.getId() + " => " + documentSnapshot.getData());
thumbUrl = video.getThumbUrl();
videoTitle = video.getVideoTitle();
videoUrl = video.getVideoUrl();
videoDesc = video.getVideoDesc();
videoId = video.getVideoId();
publisherId = video.getPublisherId();
}
if (task.getResult().size() != 0) {
Glide.with(context).load(model.getUserImageUrl()).into(holder.userProfileImage);
Glide.with(context).load(thumbUrl).into(holder.videoImageView);
holder.videoTitle.setText(videoTitle);
holder.mainContainerVideo.setVisibility(View.VISIBLE);
} else if (task.getResult().size() == 0) {
holder.mainContainerVideo.getLayoutParams().height = 0;
holder.mainContainerVideo.getLayoutParams().width = 0;
}
}
} else {
Toast.makeText(context, String.valueOf(task.getException()), Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(e -> Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show());
holder.videoContainer.setOnClickListener(v -> {
Intent intent = new Intent(context, VideoActivity.class);
intent.putExtra("videoPublisherUserName", model.getUserName());
intent.putExtra("thumbUrl", thumbUrl);
intent.putExtra("videoPublisherEmail", model.getUserEmail());
intent.putExtra("videoUrl", videoUrl);
intent.putExtra("videoId", videoId);
intent.putExtra("videoPublisherFullName", model.getUserFullName());
intent.putExtra("videoPublisherId", publisherId);
context.startActivity(intent);
});
}
#NonNull
#NotNull
#Override
public UserVideoHolder onCreateViewHolder(#NonNull #NotNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.video_cell, parent, false);
return new UserVideoHolder(v);
}
public static class UserVideoHolder extends RecyclerView.ViewHolder {
RelativeLayout videoContainer, mainContainerVideo;
CircleImageView userProfileImage;
TextView videoTitle;
ImageView videoImageView;
public UserVideoHolder(#NonNull #NotNull View itemView) {
super(itemView);
mainContainerVideo = itemView.findViewById(R.id.mainContainerVideo);
videoContainer = itemView.findViewById(R.id.videoContainer);
userProfileImage = itemView.findViewById(R.id.userProfileImage);
videoTitle = itemView.findViewById(R.id.videoTitle);
videoImageView = itemView.findViewById(R.id.videoImageView);
}
}
}
I logged videoId inside that is assigned inside for loop. Sometimes it returns ids in this order "1"; "2" and sometimes it returns like this "2"; "1". When it returns in this order "1"; "2" click opens second video even if I click first video and when it returns like this "2"; "1" click opens first video even if I click second video.
If you need additional code to solve the problem please ask and I will provide it as soon as possible. Any help is appreciated. Thanks
The short answer is that onBindViewHolder() is trying to do too much. From the documentation:
Called by RecyclerView to display the data at the specified position. This method should update the contents of the ViewHolder#itemView to reflect the item at the given position.
In other words, onBindViewHolder() is only responsible for one single item in the RecyclerView. However, you are trying to fetch all of the data for every element in the list. Instead, you should fetch the data external to your adapter and pass it in as a parameter. Then onBindViewHolder() should update the UI elements of a view inside the RecyclerView to display whatever you want for one single item.
Google has a great example CustomerAdapter. First, the constructor takes the list of data that will be displayed:
public CustomAdapter(String[] dataSet) {
mDataSet = dataSet;
}
Then onbindViewHolder() is only responsible for setting what is displayed in the UI of a single item in the RecyclerView:
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
Log.d(TAG, "Element " + position + " set.");
// Get element from your dataset at this position and replace the contents of the view
// with that element
viewHolder.getTextView().setText(mDataSet[position]);
}
It does NOT try to get data or loop over a list or anything else. All of that is someone else's responsibility.

Failed to show specific data from firebase in a RecyclerView

I managed to retrieve the data from the firebase and use a recylcerview and a holder to display them. I only need to retrieve data from certain nodes from the firebase. Nodes that are not taken by id but by an inside name:
The problem is that it only displays my data for certain nodes, but it displays them in the order in which they are found in the database. This leaves empty rows in the recyclerview. (for example if the second node is the one you are looking for, put an empty card then the one with data):
The function by which I take the data from the firebase depending on the name is:
private void LoadFeedbackMuzee(String denumire) {
options = new FirebaseRecyclerOptions.Builder<Parere>().setQuery(refM, Parere.class).build();
adapterFM = new FirebaseRecyclerAdapter<Parere, MyViewHolderRecenziiM>(options) {
#Override
protected void onBindViewHolder(#NonNull MyViewHolderRecenziiM holder, int position, #NonNull Parere model) {
if (model.getDenumire().equals(denumire)) {
String userId = model.getIdUser();
int photo = model.getLevel();
holder.parere.setText(model.getIntrb1());
userRef.child(userId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.hasChild("fullname")) {
String nume = snapshot.child("fullname").getValue().toString();
holder.username.setText(nume);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
if (photo == 1) {
holder.image.setImageResource(R.drawable.terrible);
} else if (photo == 2) {
holder.image.setImageResource(R.drawable.bad);
} else if (photo == 3) {
holder.image.setImageResource(R.drawable.okay);
} else if (photo == 4) {
holder.image.setImageResource(R.drawable.good);
} else if (photo == 5) {
holder.image.setImageResource(R.drawable.great);
}
}
}
#NonNull
#Override
public MyViewHolderRecenziiM onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.parere_layout, parent, false);
return new MyViewHolderRecenziiM(view);
}
};
adapterFM.startListening();
recyclerViewR.setAdapter(adapterFM);
}
This is happening because you are doing these things in the onBindViewHolder. So in this case what happens is, if your condition matches then the data is binded otherwise the item in the recycler is left empty means the item layout is just inflated and if you know the working of the adapter then you must be knowing that the size of the list is used to inflate the number of items (parere_layout) in recycler view. So the adapter inflates the layout but when it comes to binding (in onBindViewHolder) the data like userName and photo then if your defined condition matches then it binds otherwise the fields are left empty. Hope now you understand the working of the adapter.
So the solution is:
(1) that either you make itemView Visible for only your condition and make its visibility gone for unwanted condition. Sample code below
holder.itemView.setVisibility(View.GONE);// to make it's visibility gone
holder.itemView.setVisibility(View.VISIBLE);// to make it visible when condition matches.
(2) Recommended Solution: The second solution that I can see is that, if you filter your data before passing it to the adapter then your problem will be solved. By filtering, I mean that after fetching data from the database you just make another list in which you add only that data what you want to be shown, so in this way, your adapter code will be more cleaner and also your problem will be solved simultaneously.
Feel free to ask if something is unclear. And kindly mark this as the correct answer if it helps you so that in the future this answer can also help any other needy.
I THINK you have to do something to your views if data doesn't exist at a node but is still being looped through. So you would do something like this where you would make the views GONE if the denumire doesn't .equal(model.getDenumire) and VISIBLE if it does. And do the same if the snapshot.hasChild(fullname) doesn't have the name so like:
if (model.getDenumire().equals(denmuire) {
GETDATA()
if (snapshot.hasChild(fullname) {
holder.image.setVisibility(View.VISIBLE);
holder.name..setVisibility(View.VISIBLE);
holder.name.setName(Name)
if (photo == 1) {
holder.image.setImageResource(R.drawable.terrible);
} else if (photo == 2) {
holder.image.setImageResource(R.drawable.bad);
} else if (photo == 3) {
holder.image.setImageResource(R.drawable.okay);
} else if (photo == 4) {
holder.image.setImageResource(R.drawable.good);
} else if (photo == 5) {
holder.image.setImageResource(R.drawable.great);
}
}else{
holder.image.setVisibility(View.GONE);
holder.name.setVisibility(View.GONE);
}
} else{
holder.image.setVisibility(View.GONE);
holder.name.setVisibility(View.GONE);
etc...
}

Android Adapter not being updated

I want to display a list of match objects (match = two users having liked each other) in a recycler view with the help of an adapter.
This is my activity which is meant to display those matches:
public class MatchesActivity extends AppCompatActivity {
// variables:
private RecyclerView mMatchesRecyclerView;
private RecyclerView.Adapter mMatchItemAdapter;
private RecyclerView.LayoutManager mMatchesLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_matches);
mMatchesRecyclerView = findViewById(R.id.matches_recyclerView);
mMatchesRecyclerView.setNestedScrollingEnabled(false);
mMatchesRecyclerView.setHasFixedSize(true);
// set layout manager & pass it to the recycler view:
mMatchesLayoutManager = new LinearLayoutManager(MatchesActivity.this);
mMatchesRecyclerView.setLayoutManager(mMatchesLayoutManager);
// set match adapter & pass it to the recycler view:
mMatchItemAdapter = new MatchItemAdapter(getMatchesList(), MatchesActivity.this);
mMatchesRecyclerView.setAdapter(mMatchItemAdapter);
// add test items to the recycler view:
Match testMatch = new Match("abcdefgh");
matchesList.add(testMatch);
mMatchItemAdapter.notifyDataSetChanged();
Log.d("MatchesActivity", "TEST LIST: " + matchesList.toString());
}
private ArrayList<Match> matchesList = new ArrayList<Match>();
private List<Match> getMatchesList() {
Log.d("MatchesActivity", "getMatchesList function: " + matchesList.toString());
return matchesList;
}
}
And this is my adapter which is supposed to inflate the relevant layout & populate it with relevant object data:
public class MatchItemAdapter extends RecyclerView.Adapter<MatchViewholder> {
private List<Match> mMatchesList;
private Context mViewContext;
public MatchItemAdapter(List<Match> matchesList, Context context) {
this.mMatchesList = matchesList;
this.mViewContext = context;
Log.d("MatchItemAdapter", "Constructor: " + mMatchesList.toString());
}
// inflate the layout:
#Override
public MatchViewholder onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_matches, null, false);
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutView.setLayoutParams(lp);
MatchViewholder matchViewholder = new MatchViewholder(layoutView);
Log.d("MatchItemAdapter", "onCreateViewHolder: " + mMatchesList.toString());
return matchViewholder;
}
// populate each row within the layout:
#Override
public void onBindViewHolder(MatchViewholder holder, int position) {
Log.d("MatchItemAdapter", "onBindViewHolder: " + mMatchesList.toString());
holder.mMatchID.setText(mMatchesList.get(position).getMatchID());
}
#Override
public int getItemCount() {
return 0;
}
}
The Match class currently only takes matchID parameter which is string. An object is created with a default image and this matchID string.
At the moment, I have no real match objects from database ready, so I wanted to check that the recycler view along with adapter are working as expected before i move on to that later.
However, when I go to Matches Activity, it is empty, showing nothing at all. As you can see from the MatchesActivity onCreate method, I created a test Match object with matchID = "abcdefgh" and then added that to the matchesList. So I am expecting the "abcdefgh" text to be passed to the adapter and to be shown in the MatchesActivity.
My log statements indicate that the Match object has been created and added to the list successfully, however, getMatchesList() function returns an empty list which is then used in the Adapter constructor too, (I think this is) causing Activity not show anything.
I am relatively new to Android and Java development, especially recycler view and adapters, but from what I gathered it seems to be as if the
mMatchItemAdapter.notifyDataSetChanged();
is not working properly as everything seems to be fine up until that point. Any help would be appreciated!
You're returning 0. What you should do instead is return the length of the mMatchesList list.
#Override
public int getItemCount() {
return mMatchesList.size();
}

ListView's getCount() always returns 0

I'm using ParseQueryAdapter to display a ListView including the set of elements given by the Parse query:
ParseQueryAdapter.QueryFactory<AlertObject> factory =
new ParseQueryAdapter.QueryFactory<AlertObject>() {
public ParseQuery<AlertObject> create() {
ParseQuery<AlertObject> query = AlertObject.getQuery();
query.orderByDescending(AlertObject.TIMESTAMP_KEY);
query.fromLocalDatastore();
return query;
}
};
alertsListAdapter = new AlertListItemAdapter(activity, factory, thisFragment);
ListView alertsListView = (ListView) rootView.findViewById(R.id.alerts_list_view);
alertsListView.setAdapter(alertsListAdapter);
Now, I'd like to know the number of items in the ListView, but if I call alertsListView.getCount(), it returns 0. What am I doing wrong?
EDIT: someone gave this post a negative vote, but without leaving a comment or a request for clarification. So, I ask for some explanation about the reason of that in order to improve the readability of my question.
UPDATE: below my adapter
public class AlertListItemAdapter extends ParseQueryAdapter<AlertObject> {
private Context context;
private Fragment listAlertsFragment;
public AlertListItemAdapter(Context context,
ParseQueryAdapter.QueryFactory<AlertObject> queryFactory,
Fragment fragment) {
super(context, queryFactory);
this.context = context;
this.listAlertsFragment = fragment;
}
#Override
public View getItemView(final AlertObject alertObject, View view, final ViewGroup parent) {
[...]
}
#Override
public int getCount() {
return super.getCount();
}
}
I suspect (cannot be sure without seeing the Parse code/docs) that the adapter is not immediately populated with items, and when the query is executed, it'll call notifyDataSetChanged() on itself so that the ListView requeries it for item Views.
This would explain why your getCount() returns 0 immediately after setAdapter(ListAdapter) but why you can also see 33 items.
You can verify this logging adapter.getCount() as you do, and in addition, overriding notifyDataSetChanged to then observe the order of statements:
public class AlertListItemAdapter extends ParseQueryAdapter<AlertObject> {
public AlertListItemAdapter(
Context context,
ParseQueryAdapter.QueryFactory<AlertObject> queryFactory,
Fragment fragment) {
super(context, queryFactory);
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
Log.d("FOO", "item count: " + getCount());
}
#Override
public View getItemView(AlertObject alertObject, View view, ViewGroup parent) {
Log.d("FOO", "getItemView()");
...
}
...
}
If you need to know when the data changes, you can register a dataset changed listener on the adapter:
adapter.registerDataSetObserver(new DataSetObserver() {
#Override
public void onChanged() {
super.onChanged();
Log.d("Foo", adapter.getCount());
}
});
Are you sure you populated your ListView with parse AlertObjects?
I think you should add something like this to your query:
query.findInBackground(new FindCallback<AlertObject>() {
#Override
public void done(List<AlertObject> alerts, ParseException e) {
if (e == null) {
// Success
mAlerts = alerts;
String[] alertObjects = new String[mAlerts.size()];
Log.v(TAG, "There are " + mAlerts.size() + “ on the parse");
}
} else {
Log.e(TAG, e.getMessage());
}
}
});
Log can tell you how many objects you have on Parse.
In this Callback you can populate your ListView and then use
.getCount();
on your alertListAdapter.
Make sure you pass, store, and override the getCount() method correctly.
Please provide the code of adapter class if possible
Simply write following line to get number of items in the list view:
int count = alertsListView.alertsListAdapter().getCount();
After:
alertsListView.setAdapter(alertsListAdapter);
So your code will look like:
alertsListAdapter = new AlertListItemAdapter(activity, factory, thisFragment);
ListView alertsListView = (ListView) rootView.findViewById(R.id.alerts_list_view);
alertsListView.setAdapter(alertsListAdapter);
int count = alertsListView.alertsListAdapter().getCount();

Categories