Android Firebase - how to get child node data - android

I have node of "genresComments" that saves comments of each user to for each video id. It goes like that Genre -> video ID -> user ID:Data.
What im trying to get is all the user's id and their data (The data i mean:comment,profilePicture,username).
thats the query that should point to that data
Query query = FirebaseDatabase.getInstance().getReference(Params.GENRESCOMMENTS).child(genre).child(videoID);
But i'm sure that it points only on the "users id" and not bringing me the inside data that i need.
My question is how do i get for each "video id" all his "user id" and his data (comment,profilePicture,username).
EDIT
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
videoID = getArguments().getString(Params.VIDEOID);
genre = getArguments().getString(Params.GENRE);
progressBar.setVisibility(View.VISIBLE);
if(videoID != null){
Query query = FirebaseDatabase.getInstance().getReference(Params.GENRESCOMMENTS).child(genre).child(videoID);
options = new FirebaseRecyclerOptions.Builder<Comment>().setQuery(query,Comment.class).build();
adapter = new FirebaseRecyclerAdapter<Comment,CommentsViewHolder>(options) {
#Override
protected void onBindViewHolder(CommentsViewHolder holder, int position, Comment model) {
holder.userName.setText(model.getUserName());
holder.comment.setText(model.getComment());
Glide.with(getContext()).load(model.getUserProfile()).into(holder.userProfile);
}
#Override
public CommentsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.comment_item,parent,false);
return new CommentsViewHolder(view) ;
}
};
}
if(adapter != null) {
rvComments.setAdapter(adapter);
rvComments.setLayoutManager(new LinearLayoutManager(getContext()));
}
}
I use this query for recycler view

Do like below code (it may get errors): learn about event listener first
FirebaseDatabase.getInstance().getReference(Params.GENRESCOMMENTS).child(genre).child(videoID).addValueEventListener(new ValueEventListener(Datasnapshot snap){
for(DataSnapshot s:snap.getChildren()){
Comment c=s.getValue(Comment.class);
//c.getPRofilePic c.getComment();
}
});
class Comment {
private String comment;
private String profilePic;
private String username;
//getter setter
}

Related

Firebase add new child when an item on adapter is non-zero

Hello so I have a function in an app where you will add a data from the adapter if the quantity is non-zero and it will be saved to the firebase realtime database. What i wanna do is if the other item in adapter is non-zero it will add a child to the database but instead firebase is just replacing the item instead of adding a new child what should i do?
here is the code
public class UsualFragRViewAdapter extends RecyclerView.Adapter <UsualFragRViewAdapter.ViewHolder> {
private List<FragmentsUsualModels> items;
private Context context;
public UsualFragRViewAdapter( Context context,List<FragmentsUsualModels> items ) {
this.context = context;
this.items = items;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_usual_array, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
final FragmentsUsualModels arrayitems = items.get(position);
holder.itemName.setText(arrayitems.getItemName());
holder.price.setText(String.valueOf("$ " +arrayitems.getPrice()));
holder.quantity.setNumber(arrayitems.getQuantity());
holder.card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
holder.quantity.setOnValueChangeListener(new ElegantNumberButton.OnValueChangeListener() { //all items are located in its positions
#Override
public void onValueChange(ElegantNumberButton view, int oldValue, int newValue) { //Need to pass all non-zero items as chatview
arrayitems.setQuantity(String.valueOf(newValue));
if (newValue !=0){
String datavalue = holder.itemName.getText().toString();
String dataprice = holder.price.getText().toString();
String dataquantity = holder.quantity.getNumber().toString();
DatabaseReference data = FirebaseDatabase.getInstance().getReference("itemdata");
data.child("dataname").setValue(datavalue);
data.child("dataprice").setValue(dataprice);
data.child("dataquantity").setValue(dataquantity);
Log.d(TAG, "the new value of this data is: " +dataquantity);
Log.d(TAG, "the itemname of this position is: "+datavalue);
Log.d(TAG, "the price of this item in this position is: " +dataprice);
}
Log.d(TAG, "user changed the quantity in this position to " +arrayitems);
}
});
}
#Override
public int getItemCount() {
return items.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CardView card;
ImageView image;
TextView itemName;
TextView price;
ElegantNumberButton quantity;
Button donebtn;
public ViewHolder(#NonNull View itemView) {
super(itemView);
card = itemView.findViewById(R.id.ucard);
image = itemView.findViewById(R.id.uimage);
itemName = itemView.findViewById(R.id.uitemName);
price = itemView.findViewById(R.id.uprice);
quantity = itemView.findViewById(R.id.uquantity);
donebtn = itemView.findViewById(R.id.udonebtn);
}
}
}
If you want to generate a new child node under a location, call push() on that DatabaseReference. So to create a new child node under itemdata:
DatabaseReference data = FirebaseDatabase.getInstance().getReference("itemdata");
DatabaseReference newData = data.push();
Now you can write the data to this new location as:
newData.child("dataname").setValue(datavalue);
newData.child("dataprice").setValue(dataprice);
newData.child("dataquantity").setValue(dataquantity);
One additional change to consider is the reducing the number of writes. Your current code does a separate setValue() call for each property. This works, but it means that any listeners will get called three times, once for each property.
While this may be what you want, it is quite common to want these writes to appear as one operation. If that is the case, you can perform a single setValue() with:
Map<String,Object> values = new HashMap<>();
values.put("dataname", datavalue);
values.put("dataprice", dataprice);
values.put("dataquantity", dataquantity);
newData.setValue(values);
The end result will be exactly the same as before, but now with a single write operation.
You should use push() to create unique id for database item
dataBase.child(/*CHILD*/).push().setValue(dataValue);

How do I filter Firestore data?

My app allows Users to create Charts, which are stored in the Firestore database like this:
charts
> documentKey1
> description = "Example description"
> name = "Chart name 1"
> uId = user1Id_string
> documentKey2
> description = "Another example description"
> name = "Chart name 2"
> uId = user2Id_string
> documentKey3
> description = "Example description again"
> name = "Chart name 3"
> uId = user1Id_string
Each User can have multiple Charts. Currently, my MainActivity retrieves all of the current user's charts from the database, sorts them into a given order (set by the user), and shows them in a FirebaseRecyclerView within a Fragment.
The MainActivity has 2 Fragments in a ViewPager. The relevant one is FragmentMyCharts which contains:
public class FragmentMyCharts extends FragmentChartsList {
public FragmentMyCharts() {}
public Query getQuery(FirebaseFirestore databaseReference,
String orderBy,
Query.Direction direction) {
// Specify the query which is used to retrieve this user's charts
return databaseReference.collection("charts")
.whereEqualTo("uid", getUid())
.orderBy(orderBy, direction);
}
}
This extends FragmentChartsList, which is as follows:
public abstract class FragmentChartsList extends Fragment {
private FirebaseFirestore mDatabaseRef;
private ChartListAdapter mAdapter;
private RecyclerView mRecycler;
private String mOrder = "name", mFilter;
private Query.Direction mDirection = Query.Direction.DESCENDING;
private TextView mLoadingList, mEmptyList;
public FragmentChartsList() {}
#Override
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
// Inflate layout, and find Recycler View which will hold the list
View rootView = inflater.inflate(
R.layout.fragment_charts_list, container, false);
mRecycler = rootView.findViewById(R.id.charts_list);
mRecycler.setHasFixedSize(true);
mLoadingList = rootView.findViewById(R.id.loading_list);
mEmptyList = rootView.findViewById(R.id.empty_list);
// Set up Layout Manager, and set Recycler View to use it
LinearLayoutManager mManager = new LinearLayoutManager(getActivity());
mManager.setReverseLayout(true);
mManager.setStackFromEnd(true);
mRecycler.setLayoutManager(mManager);
// Connect to the database
mDatabaseRef = FirebaseFirestore.getInstance();
setOrderAndFilter(mOrder, mDirection, mFilter);
return rootView;
}
public abstract Query getQuery(FirebaseFirestore databaseReference,
String orderBy,
Query.Direction direction);
public void setOrderAndFilter(String order, Query.Direction direction, String filterString) {
mOrder = order;
mDirection = direction;
mFilter = filterString;
Query mChartsQuery = getQuery(mDatabaseRef, mOrder, mDirection);
// Update recycler options
FirestoreRecyclerOptions<Chart> recyclerOptions = new FirestoreRecyclerOptions.Builder<Chart>()
.setQuery(mChartsQuery, Chart.class)
.build();
mAdapter = new ChartListAdapter(recyclerOptions, getActivity());
mAdapter.startListening();
mRecycler.setAdapter(mAdapter);
mChartsQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
if (queryDocumentSnapshots != null) {
// Hide "loading lists" text
mLoadingList.setVisibility(View.GONE);
if(queryDocumentSnapshots.size() > 0) {
mEmptyList.setVisibility(View.GONE);
mRecycler.setVisibility(View.VISIBLE);
}else {
// If number of Charts = 0,
// if we have filtered, show "no results"
// otherwise, show "no charts"
mEmptyList.setVisibility(View.VISIBLE);
mRecycler.setVisibility(View.GONE);
}
}
}
});
}
This references the ChartListAdapter class, which is defined like this:
public class ChartListAdapter extends FirestoreRecyclerAdapter<Chart, ChartViewHolder> {
private Activity mActivity;
public ChartListAdapter(FirestoreRecyclerOptions<Chart> recyclerOptions, Activity activity) {
super(recyclerOptions);
mActivity = activity;
}
#Override
protected void onBindViewHolder(#NonNull ChartViewHolder holder, int position, #NonNull Chart model) {
final String chartKey = this.getSnapshots().getSnapshot(position).getId();
model.setKey(chartKey);
// Set click listener for the chart
// On click, the user can view the chart
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mActivity, ActivityViewChart.class);
intent.putExtra("ChartKey", chartKey);
mActivity.startActivity(intent);
}
});
// Implement long-click menu
mActivity.registerForContextMenu(holder.itemView);
// Bind Chart to ViewHolder
holder.bindToChart(model);
}
#NonNull
#Override
public ChartViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_chart, parent, false);
return new ChartViewHolder(view);
}
}
So, currently this retrieves all of the current user's charts, and sorts and displays them. What I want to be able to do is filter the results, so the user can enter some search text, and only charts whose names or descriptions contain that text are shown.
My understanding is that I can't do this as part of the Firestore query, so my idea was to retrieve the full list of charts, and then loop over them all, remove any that don't meet the criteria, and then show the rest (there are unlikely to be hundreds of charts in the list; most users will have around 10).
I can't figure out how to do this, and I'm not even sure whether it's the best way. The obvious place to do it seems to be when I add the snapshotListener to the ChartsQuery in FragmentChartsList, but I can't find a way to remove an individual snapshot from the list. Alternatively, can I put all the items into the recyclerView and then remove the ones that I don't want?
Can anyone point me in the right direction? Everything I've found online seems to be about removing a recyclerView item and deleting it from the database, which I don't want to do.
You can use the following query for search filter functionality.
databaseReference.collection("charts")
.whereEqualTo("uid", getUid())
.orderBy("name")
.startAt(searchText)
.endAt(searchtText + "\uf8ff");
Pass search text to startAt() and endAt() function and name is your documentField.
And pass this query to firestoreAdapter it will provide you with the result record.

Why is firebase recycler adapter returning null

I am really stuck here, I need to get the Post class value that is held in users/user_id/latest_post only some users have this value. so I thought:
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
if (dataSnapshot.hasChild("latest_post")) {
Post latest = dataSnapshot.child("latest_post").getValue(Post.class);
latest_posts = latest;
post = latest;
}
}
should work, it does in getting me the values and ignoring the ones that don't contain a latest_posts child. But my recycler adapter and view-holder doesn't seem to use this and when I try setting up the recycler view is says the value it's trying to get is null.
FirebaseRecyclerOptions<Post> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<Post>()
.setQuery(query, Post.class)
.build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Post, PostHolder>(firebaseRecyclerOptions) {
#Override
protected void onBindViewHolder(#NonNull PostHolder postHolder, int position, #NonNull Post post) {
postHolder.setPost(post);
}
#Override
public PostHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_content, parent, false);
return new PostHolder(view);
}
};
Here is the rest of the firebase adapter ^ and then here is the setPost function:
void setPost(Post post) {
String key = post.getPost_id();
Integer reads = post.getReads();
String titleString = post.getTitle();
String bodyString = post.getBody();
String usernameString = post.getAuthor();
String category = post.getCategory();
System.out.println("setPost " + usernameString);
...
}
Top of file I am holding:
Post post;
which is updated with the values in the childEventListener. Any ideas where I am messing up? Thank you.
UPDATE:
I have made these changes using my User class which contains the Post class (latest_post):
void setupRecycler(Query query) {
query = FirebaseDatabase.getInstance()
.getReference()
.child("users");
FirebaseRecyclerOptions<User> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<User>()
.setQuery(query, User.class)
.build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<User, PostHolder>(firebaseRecyclerOptions) {
#Override
protected void onBindViewHolder(#NonNull PostHolder postHolder, int position, #NonNull User user) {
if (user.getLatest_post().getAuthor() != null) {
postHolder.setPost(user);
}
}
#Override
public PostHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_content, parent, false);
return new PostHolder(view);
}
};
}
Now I am trying to filter when the setPost(user) is called so it only lets through if the latest_posts value is not null. But I must be misunderstanding something, because it gives me the first two names but still attempts to use the vaues which dont have latest_post which results in crashing due to null.
UPDATE 2:
Getting closer, this works:
query = FirebaseDatabase.getInstance()
.getReference()
.child("users").orderByChild("latest_post");
I'm guessing because it orders them by the users that have latest_post, but it crashes if I scroll to the bottom because Then all the rest are still there, so it attempts to set a string value to a textView when it is null. How do I exclude these pesky things?
It was because you can't filter a query to exclude posts that do not exist, and you do not have access to the list that firebaseRecyclerAdapter uses. The only solution to accurately and safely filter the data the way I needed was to use a custom recyclerView Adapter, and a list of my class, and filter and order the list as needed after the query.

FirestoreRecyclerAdapter - how do I know when data has been retrieved?

I'm retrieving data using a FirestoreRecyclerAdapter, and, on completion, I need to check whether any items have been retrieved or not. I can't figure out how to do this.
I'm calling it from a class called FragmentChartsList, shown below. This should set up the adapter initially, with "name" as the value for mOrder. Later, the Activity which contains this Fragment can call setOrderField() with a different value of mOrder, which the user has selected from a Spinner.
Each time setOrderField() is called, a new adapter instance is created and attached to the recyclerView. At this point I need to check whether the new version of the adapter contains any data, and either show a "no Charts found" message, or show the Charts which were retrieved (obviously if the list is just being sorted, then the number of items remains the same, but I'm going to be expanding this to allow the user to filter the Charts by different criteria, so the number of Charts returned will change).
Currently, setOrderField() calls refreshViewOnNewData(), which should find out how many Charts are being shown; if it's 0, it should show the "no Charts found" message, and if it's >0 it should show the RecyclerView containing the Charts.
At the moment, I'm always getting a value of 0 when I try to count the Charts. I suspect it's because the adapter hasn't finished retrieving them from the database yet, but I can't find anything that allows me to add some kind of "onComplete" listener so that I know it's finished.
Can anyone suggest how I can achieve this?
public abstract class FragmentChartsList extends Fragment {
private FirebaseFirestore mDatabaseRef;
private ChartListAdapter mAdapter;
private Query mChartsQuery;
private RecyclerView mRecycler;
private String mOrder = "name";
private TextView mLoadingList, mEmptyList;
public FragmentChartsList() {}
#Override
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(
R.layout.fragment_charts_list, container, false);
mRecycler = rootView.findViewById(R.id.charts_list);
mRecycler.setHasFixedSize(true);
mLoadingList = rootView.findViewById(R.id.loading_list);
mEmptyList = rootView.findViewById(R.id.empty_list);
// Set up Layout Manager, and set Recycler View to use it
LinearLayoutManager mManager = new LinearLayoutManager(getActivity());
mManager.setReverseLayout(true);
mManager.setStackFromEnd(true);
mRecycler.setLayoutManager(mManager);
// Connect to the database
mDatabaseRef = FirebaseFirestore.getInstance();
setOrderField(mOrder); // Initialised to "name"
return rootView;
}
#Override
public void onStart() {
super.onStart();
mAdapter.startListening();
}
#Override
public void onStop() {
super.onStop();
mAdapter.stopListening();
}
#Override
public void onDestroy() {
super.onDestroy();
mAdapter.stopListening();
}
// HELPER FUNCTIONS
public void setOrderField(String order) {
mOrder = order;
mChartsQuery = getQuery(mDatabaseRef, mOrder);
// Update recycler options
FirestoreRecyclerOptions<Chart> recyclerOptions = new FirestoreRecyclerOptions.Builder<Chart>()
.setQuery(mChartsQuery, Chart.class)
.build();
mAdapter = new ChartListAdapter(recyclerOptions, getActivity());
mAdapter.startListening();
mRecycler.swapAdapter(mAdapter, true);
refreshViewOnNewData();
}
private void refreshViewOnNewData() {
// Hide "loading" text
mLoadingList.setVisibility(View.GONE);
// Check number of charts being shown
//if (mAdapter != null && (mAdapter.getCount() > 0)) {
// If > 0, show Charts
mEmptyList.setVisibility(View.GONE);
mRecycler.setVisibility(View.VISIBLE);
} else {
// If number of Charts = 0
// show "no charts"
mEmptyList.setVisibility(View.VISIBLE);
mRecycler.setVisibility(View.GONE);
}
}
}
The adapter class looks like this:
public class ChartListAdapter extends FirestoreRecyclerAdapter<Chart, ChartViewHolder> {
private Activity mActivity;
private int mCount;
public ChartListAdapter(FirestoreRecyclerOptions<Chart> recyclerOptions, Activity activity) {
super(recyclerOptions);
mActivity = activity;
}
#Override
protected void onBindViewHolder(#NonNull ChartViewHolder holder, int position, #NonNull Chart model) {
final String chartKey = this.getSnapshots().getSnapshot(position).getId();
model.setKey(chartKey);
// Set click listener for the chart
// On click, the user can view the chart
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mActivity, ActivityViewChart.class);
intent.putExtra("ChartKey", chartKey);
mActivity.startActivity(intent);
}
});
// Implement long-click menu
mActivity.registerForContextMenu(holder.itemView);
// Bind Chart to ViewHolder
holder.bindToChart(model);
}
#NonNull
#Override
public ChartViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_chart, parent, false);
return new ChartViewHolder(view);
}
#Override
public void onDataChanged() {
super.onDataChanged();
mCount = getItemCount();
}
public int getCount() {
return mCount;
}
}
Figured this out... I needed to set a listener on the query instead.
So, instead of having the call to refreshViewOnNewData from setOrder above, I now have:
mChartsQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
if (queryDocumentSnapshots != null) {
mLoadingList.setVisibility(View.GONE);
if(queryDocumentSnapshots.size() > 0) {
mEmptyList.setVisibility(View.GONE);
mRecycler.setVisibility(View.VISIBLE);
}else {
mEmptyList.setVisibility(View.VISIBLE);
mRecycler.setVisibility(View.GONE);
}
}
}
});
}
Also removed mCount from the adapter class, along with getCount and onDataChanged

How can i view the Firebase data (ListView format) in different activity?

i want to view all the datas in list view in another activity. no in the same activity where the data generated. check this image.
here data shows in same activity in where i inserted via firebase . i want show the list view part in another activity . how can i do that ? and how can i see the last inserted data on top?
code for viewing data .
#Override
protected void onStart() {
super.onStart();
databaseBazars.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
abc.clear();
for( DataSnapshot ds :dataSnapshot.getChildren()) {
ADeposit ks = ds.getValue(ADeposit.class);
abc.add(ks);
}
DepositList adapter = new DepositList(AdminloginEnter.this,abc);
deposit.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
and here code for inserting data
private void Add(){
String dt= ki.getText().toString().trim();
String ct = costt.getText().toString().trim();
String nm = spn.getSelectedItem().toString();
if(!TextUtils.isEmpty(dt)){
String id= databaseBazars.push().getKey();
ADeposit bz= new ADeposit(id,nm,ct,dt);
databaseBazars.child(id).setValue(bz);
Toast.makeText(this,"Inserted",Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(this,"Please Enter Valid Data",Toast.LENGTH_SHORT).show();
}
}
and here is the deposit list class .
import com.sonalirod.alwayswhite.Model.ADeposit;
import java.util.List;
public class DepositList extends ArrayAdapter<ADeposit> {
private Activity context;
private List<ADeposit> abc;
public DepositList(Activity context,List<ADeposit>abc){
super(context, R.layout.list_layout_deposit,abc);
this.context=context;
this.abc=abc;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View ListViewItem= inflater.inflate(R.layout.list_layout_deposit,null,true);
TextView texviewname=(TextView) ListViewItem.findViewById(R.id.namet);
TextView textviewcost=(TextView) ListViewItem.findViewById(R.id.amountt);
TextView textviewdate =(TextView) ListViewItem.findViewById(R.id.datu);
ADeposit ad = abc.get(position);
texviewname.setText(ad.getName());
textviewcost.setText(ad.getAmount());
textviewdate.setText(ad.getDat());
return ListViewItem;
}
}
who helps for the viewing from firebase. if anyone want i can provide the model class also . but my code is perfectly work. i just want to know **how can i show that list view in another activity ** also how can i see the last inserted data on first(upper) place .
To retrieve data in the other activity, you need to use a listener there example valueEventListener, to sort the data do this:
//inside onDatachange or onChildAdded
String inputs= dataSnapshot.child("ks").getValue().toString();
arraylist.add(inputs);
HashSet<String> hashSet = new HashSet<String>();
hashSet.addAll(arraylist);
arraylist.clear();
arraylist.addAll(hashSet);
//Alphabetic sorting.
Collections.sort(editlists);
adapter= new ArrayAdapter<>(Activity.this, android.R.layout.simple_list_item_1, arraylist);
list.setAdapter(adapter);
First retrieve the add normally, add them to your arraylist then you will be able to use HashSet to sort it (last item added will be in on last)

Categories

Resources