Updating listview isn't working - java

So basically I'm collecting data from a json url in my listview. It's a chatroom type of app and in the lists I want to sync the chatroom contact lists with latest message and timestamps.
When the json gets updated I'm calling the fuction.
public void addGroupAdapter() {
Firebase jsonurl = new Firebase("firebase url");
jsonurl.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ContactListAdapter adapter = new ContactListAdapter(getContext(),dataSnapshot);
try {
Log.i("Response Array fire",new JSONArray(dataSnapshot.getValue(String.class)).toString());
if (!adapted){
chatLists.setAdapter(adapter);
adapted = true;
}else {
Log.i("update",dataSnapshot.getValue(String.class));
adapter.setContactList(dataSnapshot);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
That Json data is stored in the firebase database .
chatLists.setAdapter(adapter) works well.
But when I try to update. notifyDataSetChanged(); doesn't work.
new ContactListAdapter(getContext(),dataSnapshot).notifyDataSetChanged();
I also tried invalidateviews method and same result. So where am I doing wrong?
After reading answers I tried this. SO now this my adapter class,
class ContactListAdapter extends BaseAdapter {
Context c;
List lists;
Type type = new TypeToken<List<ChatroomLists>>(){}.getType();
JsonParser parser = new JsonParser();
ArrayList<ChatroomLists> ob1 = new ArrayList<ChatroomLists>();
public void setContactList(DataSnapshot dataSnapshot) {
Type listType = new TypeToken<ArrayList<ChatroomLists>>() {
}.getType();
ob1 = new Gson().fromJson((JsonArray)parser.parse(dataSnapshot.getValue(String.class)),listType);
Log.i("setContactList",dataSnapshot.getValue(String.class));
notifyDataSetChanged();
}
ContactListAdapter(Context c, DataSnapshot group_name) {
this.c = c;
this.groupids = group_name;
Type listType = new TypeToken<ArrayList<ChatroomLists>>() {
}.getType();
ob1 = new Gson().fromJson((JsonArray)parser.parse(group_name.getValue(String.class)),listType);
}
#Override
public int getCount() {
return ob1.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
GroupChat.viewHolder holder = null;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) c.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate (R.layout.chat_list_style, parent, false);
holder = new GroupChat.viewHolder(row);
row.setTag (holder);
} else {
holder = (GroupChat.viewHolder) row.getTag ();
}
ChatroomLists chatroomLists = ob1.get(position);
Iterator<ChatroomLists> iter = ob1.iterator();
String id = chatroomLists.getId();
String time = chatroomLists.getTimestamp();
Log.i("updated data",id + time);
viewHolder finalHolder = holder;
Firebase chatlink = new Firebase ("firebase link");
chatlink.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot d: dataSnapshot.getChildren()){
finalHolder.user_message.setText (dataSnapshot.child(d.getKey()).child("message").getValue(String.class));
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Firebase imageurl = new Firebase("firebase link");
imageurl.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Glide.with (getActivity ())
.load (dataSnapshot.getValue(String.class))
.error (R.drawable.man)
.into (finalHolder.user_img);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
holder.user_name.setText (id);
row.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick(View v) {
Intent intent = new Intent (getActivity (), ChatRoom.class);
intent.putExtra ("group_name", id);
startActivity (intent);
}
});
registerForContextMenu (row);
return row;
}
}
But it's still not updating.. :(
UPDATE: Listview was so buggy in this case. And I changed to Recyclerview. Now everything is working smoothly.

This is because you are creating new adapter instance instead of updating data on existing adapter which is set on list/recyclerview.
private ContactListAdapter mAdatper;
public void addGroupAdapter() {
Firebase jsonurl = new Firebase("firebase url");
jsonurl.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
Log.i("Response Array fire",new JSONArray(dataSnapshot.getValue(String.class)).toString());
if (!adapted){
mAdatper = new ContactListAdapter(getContext(),dataSnapshot);
chatLists.setAdapter(mAdapter);
adapted = true;
}else {
Log.i("update",dataSnapshot.getValue(String.class));
mAdatper.setContactList(dataSnapshot);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
In your adapter, add setter method.
public void setContactList(DataSnapshot dataSnapshot) {
// set contactList here
notifyDataSetChanged();
}
Hope it might be helpful for you.

You are calling notifyDataSetChanged() on a new instance of the adapter everytime. You should call it on the same adapter that you set on the list. And you should update the data in that particular instance of the adapter

In your else case you are creating a new ContactListAdapter but you are not attaching that adapter to your chatLists. Anyway, you do not need to create a new CustomAdapter instance, just create a update method within your CustomAdapter and call it passing new dataSnapshot data.
You can Try something as the following inside your CustomAdapter.java:
public void updateData(Data data) {
this.dataList = data;
notifyDataSetChanged();
}
Then back into your addGroupAdapter method just call that method

Related

my list is not showing while i click on the button

Actually i couldn't find any error here. I think i m missing something here. this filtersbutton is not working. Your help will be appreciated. Thank you
This is my fragment.class
sortByLeastExpensive = rootView.findViewById(R.id.sort_by_least_expensive);
sortByMostExpensive = rootView.findViewById(R.id.sort_by_most_expensive);
sortByMostRecent = rootView.findViewById(R.id.sort_by_most_recent);
applyFiltersBtn = rootView.findViewById(R.id.apply_filters_btn);
sortByLeastExpensive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//set the filter; or call the viewmodel to set the filter?
mViewModel.sortBy.setValue(getResources().getString(R.string.sort_rooms_ascending));
}
});
sortByMostExpensive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mViewModel.sortBy.setValue(getResources().getString(R.string.sort_rooms_descending));
}
});
sortByMostRecent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mViewModel.sortBy.setValue("sort_most_recent");
}
});
return rootView;
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewModel = ViewModelProviders.of(getActivity()).get(FilterRoomsViewModel.class);
mViewModel.getSortBy().observe(this, Observer -> {
Log.i("Viewmodel", "Viewmodel ,sortby: " + mViewModel.sortBy.getValue());
});
applyFiltersBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FilterRoomsRepository roomsRepository = new FilterRoomsRepository();
roomsRepository.getFilteredRooms(mViewModel.sortBy.getValue());
}
});
}
This is viewmodel.class
i have updated my viewmodel.class. now its showing me another error on fragment.class
public FilterRoomsViewModel(Application application){
super();
FilterRoomsRepository filterRoomsRepository = new FilterRoomsRepository(application);
}
public MutableLiveData<String> getRooms(){
if (rooms==null){
rooms = new MutableLiveData<String>();
}
return rooms;
}
public LiveData<String> getSortBy() {
if (sortBy == null){
sortBy = new MutableLiveData<String>();
}
return sortBy;
}
this is repository.class
if(sortyBy.equals("ascending")){
Log.i("Sort by", "Rooms sorted in ascending order");
filterQuery.orderByAscending("roomRentalAmount");
}else if (sortyBy.equals("descending")){
Log.i("Sort by", "Rooms sorted in descending order");
filterQuery.orderByDescending("roomRentalAmount");
}else {
filterQuery.orderByDescending("updatedAt");
}
filterQuery.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if(e == null){
//success
Log.i("Rooms", "Filtered rooms, " + objects.get(0).getObjectId());
rooms.setValue(objects);
}else{
//error, handle accordingly
Log.e("Error", "Error filtering, " + e.getMessage());
}
}
});
Log.i("Rooms", "Live data rooms, " + rooms.getValue());
return rooms;
}
What do you mean that its not showing? It's not showing in the ui or in logs? Because when you call getFilteredRooms you don't do anything with the result.
What i would suggest is to move the repository call to the viewModel, so that instead of calling getFilteredRooms in the fragment, you would call sth like viewModel.getFilteredRooms and then, in the viewmodel, you call the repository and you use the result to set the value of the livedata.
Then, in the fragment you just need to observe this variable and based on that you update the ui. By doing so, you separate the logic (viewmodel and repository) from the ui part (fragment).
Here is a good tutorial on how to code with mvvm pattern: https://medium.com/#er.ankitbisht/mvvm-model-view-viewmodel-kotlin-google-jetpack-f02ec7754854

Display Firestore Doc by Id on click, from fragment to activity

So, I've been using the Google's Friendlyeats example as guide. I changed it a bit in order to use Butterknife but had issues when trying to open a single doc (fragment) and show its content in the following activity.
I'm using a recyclerview to show the summarize data and then I want to show the full individual data on an activity. It's really not that much info, just four textviews.
Because of this, I decided to stick to the original example as much as I could to see what was up. Still same error. I can open the following activity but no data is being displayed.
I'm already three months behind lmao. please help!
here's the code:
MessageAdapter.java
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.bind(getSnapshot(position), mListener);
}
static class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(View itemView) {
super(itemView);
headerView = itemView.findViewById(R.id.message_item_header);
senderView = itemView.findViewById(R.id.message_item_sender);
dateView = itemView.findViewById(R.id.message_item_date);
imageView = itemView.findViewById(R.id.message_item_image);
actualMessageView = itemView.findViewById(R.id.actual_message);
}
public void bind(final DocumentSnapshot snapshot,
final OnMessageSelectedListener listener) {
Messages messages = snapshot.toObject(Messages.class);
imageView.setImageResource(R.drawable.logo_app_off);
headerView.setText(messages.getHeader());
senderView.setText(messages.getSender());
actualMessageView.setText(messages.getMessage());
dateView.setText(messages.getDate());
itemView.setOnClickListener(v -> {
if (listener != null) {
listener.onMessageSelectedListener(snapshot);
}
});
}
}
}
HomeFragment.java
#Override
public void onMessageSelectedListener(DocumentSnapshot message) {
Intent intent = new Intent(getActivity(), MessageDetailActivity.class);
intent.putExtra(KEY_MESSAGE_ID, message.getId());
startActivity(intent);
}
private void initFirestore() {
mFirestore = FirebaseFirestore.getInstance();
mQuery = mFirestore.collection("messages")
.orderBy("date", Query.Direction.DESCENDING)
.limit(LIMIT);
}
private void initRecyclerView() {
if (mQuery == null) {
Log.w(TAG, "No query, not initializing RecyclerView");
}
mAdapter = new MessageAdapter(mQuery, this) {
#Override
protected void onDataChanged() {
if (getItemCount() == 0) {
mMessagesRecycler.setVisibility(View.GONE);
mEmptyView.setVisibility(View.VISIBLE);
} else {
mMessagesRecycler.setVisibility(View.VISIBLE);
mEmptyView.setVisibility(View.GONE);
}
}
#Override
protected void onError(FirebaseFirestoreException e) {
Snackbar.make(view.findViewById(android.R.id.content),
"Error: check logs for info.", Snackbar.LENGTH_LONG).show();
}
};
mMessagesRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
mMessagesRecycler.setAdapter(mAdapter);
}
DetailMessageActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message_detail);
String messageId = getIntent().getExtras().getString(KEY_MESSAGE_ID);
if (messageId == null) {
throw new IllegalArgumentException("Must pass extra " + KEY_MESSAGE_ID);
}
mFirestore = FirebaseFirestore.getInstance();
mMessageRef = mFirestore.collection("messages").document(messageId);
}
#Override
public void onEvent(DocumentSnapshot snapshot, FirebaseFirestoreException e) {
if (e != null) {
Log.w(TAG, "message:onEvent", e);
return;
}
onMessageLoaded(snapshot.toObject(Messages.class));
}
private void onMessageLoaded(Messages message) {
mDetailedHeader.setText(message.getHeader());
mDetailedHeader.setText(message.getSender());
mDetailedMessage.setText(message.getMessage());
mDetailedDate.setText(message.getDate());
}
}

FirebaseRecyclerAdapter Search

I have implemented a FirebaseRecyclerAdapter to populate cities from the database in to the RecyclerView. After several fails to implement a search feature I am seeking for help. I would like to let users search for a particular city by typing the city's name (postName). The idea is to populate all of the available cities at the beginning and the desired city after its name is typed in the search field.
My code to populate the view is:
searchField = view.findViewById(R.id.search_field);
searchButton = view.findViewById(R.id.imageButton);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String search_field = searchField.getText().toString().trim();
initialiseScreen(view, search_field);
Toast.makeText(getContext(), search_field, Toast.LENGTH_SHORT).show();
}
});
String search_field = null;
initialiseScreen(view, search_field);
return view;
}
private void initialiseScreen(final View view, String searchText) {
Query postQuery = mDataRef.orderByChild("postName").startAt(searchText).endAt(searchText + "\uf8ff");
mDataRef.keepSynced(true);
recyclerView = view.findViewById(R.id.post_RV);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(mPostViewAdapter);
FirebaseRecyclerOptions postOptions = new FirebaseRecyclerOptions.Builder<Post>()
.setQuery(postQuery, Post.class).build();
mPostViewAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(postOptions) {
#Override
protected void onBindViewHolder(PostViewHolder holder, int position, final Post model) {
final String post_key = getRef(position).getKey();
holder.setPostCityImage(model.getImageURL());
holder.setPostCityName(model.getPostName());
holder.setLikeBtn(post_key);
//When is clicked once go to city fragment
holder.cityImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Add code here
Intent singlePostIntent = new Intent(getActivity(), CitiesActivity.class);
singlePostIntent.putExtra("blog_id", post_key);
startActivity(singlePostIntent);
}
});
//Likes button
holder.likes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProccessLike = true;
String postId = model.getmUid();
mDatabaseLikesRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(mProccessLike) {
if (dataSnapshot.child(post_key).hasChild(current_user_id)) {
mDatabaseLikesRef.child(post_key).child(current_user_id).removeValue();
mProccessLike = false;
} else {
mDatabaseLikesRef.child(post_key).child(current_user_id).setValue("RandomValue");
mProccessLike = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
//
}
Btw it populates only one city if instead of String search_field = null; I write something like String search_field = "Calp, Spain";

Sending videolink from listview to videoview in same activity

I have a videoview and listview/gridview in my playvideo activity.
One video is already playing in the videoview. But now i want to play the other video which are showing in the listview/gridview how can i do that?
Playvideo Activity
public class playvideoactivity extends Activity {
GridViewWithHeaderAndFooter grid;
String videourl="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4";
private static final String url = "http://dakwf.org/api/bd_english.json";
private List<ChannelItem> chanellist = new ArrayList<ChannelItem>();
private static final String TAG = MainActivity.class.getSimpleName();
public static VideoView player;
public static ImageButton btnPlayPause;
private ImageView btnFullscreen;
private ProgressBar spinner;
private RelativeLayout mediaController;
private Handler btnHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (ProgressBar) findViewById(R.id.progressBar);
player=(VideoView) findViewById(R.id.player);
mediaController=(RelativeLayout) findViewById(R.id.media_controller);
spinner.setVisibility(View.VISIBLE);
mediaController.setVisibility(View.INVISIBLE);
btnPlayPause=(ImageButton) findViewById(R.id.btn_playpause);
btnFullscreen=(ImageView) findViewById(R.id.btn_fullscreen);
final CustomGridviewadapter customGridview= new CustomGridviewadapter(this,chanellist);
grid = (GridViewWithHeaderAndFooter) findViewById(R.id.grid_view);
setGridViewHeaderAndFooter();
grid.setAdapter(customGridview);
//----------- Creating volley request obj--------------------
JsonArrayRequest movieReq = new JsonArrayRequest(url,new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
ChannelItem item = new ChannelItem();
item.setTitle(obj.getString("title"));
item.setThumbnailUrl(obj.getString("image"));
// adding movie to movies array
chanellist.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
customGridview.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
//------------------- Mediacontroller Visiblity-------------------------------------
player.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(final View paramAnonymousView, MotionEvent paramAnonymousMotionEvent)
{
if (paramAnonymousMotionEvent.getAction() == 0){
if (MainActivity.this.mediaController.getVisibility() != View.INVISIBLE) {
}
MainActivity.this.mediaController.setVisibility(View.VISIBLE);
MainActivity.this.btnHandler.postDelayed(new Runnable(){
public void run(){
MainActivity.this.mediaController.setVisibility(View.INVISIBLE);
}
}, 2000L);
}
for (;;){
return true;
}
}
});
//------FullScreen Button -----
btnFullscreen.setOnClickListener(new View.OnClickListener(){
public void onClick(View paramAnonymousView) {
Intent i = new Intent(MainActivity.this, FullScreenView.class);
startActivity(i);
}
});
//------Play Pause Button ----------
btnPlayPause.setOnClickListener(new View.OnClickListener() {
public void onClick(View paramAnonymousView){
if ( (player != null) && (MainActivity.this.player.isPlaying()) ){
MainActivity.this.player.pause();
MainActivity.this.btnPlayPause.setBackgroundResource(R.drawable.btn_play);
return;
}
MainActivity.this.player.start();
MainActivity.this.btnPlayPause.setBackgroundResource(R.drawable.btn_pause);
return;
}
});
//----------------------------------------
try {
MediaController mController = new MediaController(MainActivity.this);
mController.setAnchorView(player);
Uri video = Uri.parse(videourl);
player.setMediaController(mController);
player.setVideoURI(video);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
player.setMediaController(null);
player.requestFocus();
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer arg0) {
player.start();
hidespinner();
}
});
}
// ------------ Header Gridview ----------------
#SuppressLint({"InflateParams", "SetTextI18n"})
private void setGridViewHeaderAndFooter() {
LayoutInflater layoutInflater = LayoutInflater.from(this);
View headerView = layoutInflater.inflate(R.layout.grid_header, null, false);
//locate views
TextView headerText = (TextView)headerView.findViewById(R.id.textViewheader);
headerText.setText("Suggestion");
headerView.setOnClickListener(onClickListener(0));
grid.addHeaderView(headerView);
}
private View.OnClickListener onClickListener(final int i) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
if (i == 0) {
// Toast.makeText(MainActivity.this, "Header Clicked!", Toast.LENGTH_SHORT).show();
} else {
// Toast.makeText(MainActivity.this, "Footer Clicked!", Toast.LENGTH_SHORT).show();
}
}
};
}
#Override
public void onDestroy() {
super.onDestroy();
hidespinner();
}
private void hidespinner() {
if (spinner != null) {
spinner.setVisibility(View.INVISIBLE);
spinner = null;
}
}
}
When opening starting the app you need to get the data and store on a variable or into database.
Create a ChannelList type List (List<ChannelList>) and store ChannelList data into it.
List<ChannelList> list = new ArrayList<>(); // containing all data
You can store Title, VideoUrl, iconUrl and add it to the list.
When clicking on a List Item you will get the position by using setOnItemClickListener.
And then use the position to get the clicked ChannelList position.
Suppose your list type variable is channelList.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ChannelList channelList= list.get(position);
// now you have all data of clicked ChannelList
// do whatever you like
//channelList.getVideoUrl(); etc as your getter method
}
}
});
For more about List, you can check it Here

firebase get data as array

I am trying to implement firebase into my Android app and I want to be able to pull all the entries in firebase in the order they display in into one string array to be put into a ListView
Here is the raw JSON:
[ 5, "quot", "waaaaa", "also a quote", "oh this one is a little longer man", "gosh really long. wow. im very inspired. golly gee wiz" ]
and the code I am using to try and get it:
public class MyActivity extends ListActivity {
ArrayList<String> LIST = new ArrayList<String>();
Boolean wow = true;
Context context = this;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Firebase.setAndroidContext(context);
updateList();
}
public void makeList(ArrayList<String> input){
setListAdapter(new ArrayAdapter<String>(this, R.layout.mylist,input));
ListView listView = getListView();
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
public void updateList() {
Firebase myFirebaseRef = new Firebase("https://admin1.firebaseio.com/");
myFirebaseRef.child("0").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println(snapshot.getValue());
int length = Integer.parseInt(snapshot.getValue().toString());
Firebase myFirebaseRef = new Firebase("https://admin1.firebaseio.com/");
for(int i=1; i<length; i++) {
String doIt = Integer.toString(i);
myFirebaseRef.child(doIt).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println(snapshot.getValue());
LIST.add(snapshot.getValue().toString());
}
#Override
public void onCancelled(FirebaseError error) {
}
});
}makeList(LIST);
}
#Override
public void onCancelled(FirebaseError error) {
}
});
}
}
I was thinking that I could set the first (0th) object to be the number of entries and then cycle through the entire file using .getValue but when this is run I get out of memory exceptions and the app force closes. All I am sure of is that the relevant firebase stuff is the issue and not the ListView. Thanks for any tips.
Firstly, your data is stored in a JSON data object (i.e. not an array). You do not want to store sequential, numeric ids in distributed data.
To listen for the first n objects, utilize the query methods and limitToFirst.
int n = 10;
String URL = "https://<your instance>.firebaseio.com";
Firebase ref = new Firebase(URL);
Query queryRef = ref.orderByKey().limitToFirst(n);
queryRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot snapshot, String previousChild) {
Map<String, String> value = (Map<String, String)snapshot.getValue();
System.out.println(snapshot.getKey() + " was " + value.get("message"));
}
// ....
});

Categories