How to chain queries in firebase android? - android

I want to get all the missions for a specific user (constraint num 1),
but only the available users (constraint num 2).
I know I can overcome one constraint by 'order by' and 'equalTo' functions,
but i'm failing at overcoming the second one.
This is my firebase db:
This is my current result at the app (A finished mission is there! I don't want it!):
This is my relevant code:
public class PendingFragmentUser extends Fragment {
private String TAG = "dDEBUG";
private RecyclerView mPendingList;
private DatabaseReference mMissionsDb;
private FirebaseAuth mAuth;
private String mCurrent_user_id;
private View mMainView;
Query queries;
public PendingFragmentUser() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mMainView = inflater.inflate(R.layout.fragment_pending_user, container, false);
mPendingList = (RecyclerView)mMainView.findViewById(R.id.pending_recycler_user);
mAuth = FirebaseAuth.getInstance();
mCurrent_user_id = mAuth.getCurrentUser().getUid();
mMissionsDb = FirebaseDatabase.getInstance().getReference().child("Missions");
queries = mMissionsDb.orderByChild("user_uid").equalTo(mCurrent_user_id);
mMissionsDb.keepSynced(true);
mPendingList.setHasFixedSize(true);
mPendingList.setLayoutManager(new LinearLayoutManager(getContext()));
// Inflate the layout for this fragment
return mMainView;
}
#Override
public void onStart() {
super.onStart();
final FirebaseRecyclerAdapter<Mission, PendingFragmentUser.MissionsViewHolder> firebaseMissionsUserRecyclerAdapter = new FirebaseRecyclerAdapter<Mission, PendingFragmentUser.MissionsViewHolder>(
Mission.class,
R.layout.missions_single_layout,
PendingFragmentUser.MissionsViewHolder.class,
queries
) {
#Override
protected void populateViewHolder(PendingFragmentUser.MissionsViewHolder missionViewHolder, final Mission missionModel, final int missionPosition) {
// Log.d(TAG, "inside populateViewHolder" + missionModel.getType() + " , " + missionModel.getDescription());
missionViewHolder.setMissionName(missionModel.getType());
missionViewHolder.setMissionDescription(missionModel.getDescription());
missionViewHolder.setMissionStatus(missionModel.getStatus());
}
};
mPendingList.setAdapter(firebaseMissionsUserRecyclerAdapter);
}
public static class MissionsViewHolder extends RecyclerView.ViewHolder {
View mView;
Button button ;
public MissionsViewHolder(View itemView) {
super(itemView);
mView = itemView;
button = (Button)mView.findViewById(R.id.pending_single_button);
}
public void setMissionName(String name){
TextView mMissionNameView = mView.findViewById(R.id.mission_single_name);
mMissionNameView.setText(name);
}
public void setMissionStatus(String status){
TextView mMissionStatusView = mView.findViewById(R.id.mission_single_status);
mMissionStatusView.setText(status);
if (status.equals("Available")){
mMissionStatusView.setTextColor(Color.parseColor("#008000"));;
} else {
mMissionStatusView.setTextColor(Color.parseColor("#FF0000"));;
}
}
public void setMissionDescription(String description){
TextView mMissionDescriptionView = mView.findViewById(R.id.mission_single_description);
mMissionDescriptionView.setText(description);
}
}
}
How can I overcome this firebase limitations?
To filter all missions for specific user:
queries = mMissionsDb.orderByChild("user_uid").equalTo(mCurrent_user_id);
And now I would like to do:
queries = mMissionsDb.orderByChild("user_uid").equalTo(mCurrent_user_id).orderByChild("status").equalTo("Available");
But it's not possible in firebase.
In addition, I have to use real-time adapter because it's critical the my UI shows exactly the DB with minimum delay in changes at the DB. Thanks

Related

FirebaseRecyclerAdapter model returning null values

I'm trying to make a comment system for posts on my social media app. In my database each post has a section inside of "comments" table, like so:
"hypno--######" is the title of the social media post. It Contains the comment, user id of the user who posted the comment, and a unixtimestamp when the comment was posted. Each comment is titled after the time it was posted.
This is the Comment class
public class comment {
public String uID;
public String comment_t;
public long unixTimestamp;
public comment() {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public comment(String uID, String comment_t, long unixTimestamp) {
this.uID = uID;
this.comment_t = comment_t;
this.unixTimestamp = unixTimestamp;
}
public String getuID() {
return uID;
}
public void setuID(String uID) {
this.uID = uID;
}
public String getComment() {return comment_t;}
public void setComment() {this.comment_t = comment_t; }
public long getUnixTimestamp() {
return unixTimestamp;
}
}
This is the Comment Adapter:
Public class Adapter_Comment extends FirebaseRecyclerAdapter<comment, Adapter_Comment.ViewHolder_com> {
private DatabaseReference mDatabase;
private static final String TAG = "RecyclerViewAdapter";
private Context mContext;
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
private static AppCompatActivity unwrap(Context context) {
while (!(context instanceof Activity) && context instanceof ContextWrapper) {
context = ((ContextWrapper) context).getBaseContext();
}
return (AppCompatActivity) context;
}
public Adapter_Comment(#NonNull FirebaseRecyclerOptions<comment> options) {
super(options);
//this.mContext = mContext;
}
#NonNull
#Override
public ViewHolder_com onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_comment, parent, false);
mDatabase = FirebaseDatabase.getInstance().getReference();
return new ViewHolder_com(view);
}
#Override
protected void onBindViewHolder(#NonNull ViewHolder_com holder, int position, #NonNull comment model) {
mDatabase = FirebaseDatabase.getInstance().getReference();
long dv = model.getUnixTimestamp()*-1000;
Date df = new java.util.Date(dv);
String vv = new SimpleDateFormat("MM dd, yyyy hh:mma", Locale.ENGLISH).format(df);
holder.time.setText(vv);
String com = model.getComment();
holder.comment_text.setText(com);
mDatabase.child("users").child(model.getuID()).child("profileUrl").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists())
{
final String picUrl = snapshot.getValue(String.class);
Glide.with(holder.postPfp.getContext()).load(picUrl).into(holder.postPfp);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) { }
});
holder.postPfp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//AppCompatActivity activity = (AppCompatActivity) v.getContext();
AppCompatActivity activity = unwrap(v.getContext());
Fragment OtherProfileFragment = new OtherProfileFragment();
Bundle bundle = new Bundle();
bundle.putString("key", model.getuID());
OtherProfileFragment.setArguments(bundle);
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, OtherProfileFragment).addToBackStack(null).commit();
}
});
}
public class ViewHolder_com extends RecyclerView.ViewHolder {
TextView comment_text;
CircleImageView postPfp;
TextView time;
RelativeLayout comment_layout;
public ViewHolder_com(#NonNull View itemView) {
super(itemView);
postPfp = itemView.findViewById(R.id.iv_comment_icon);
comment_text = itemView.findViewById(R.id.tv_comment_text);
time = itemView.findViewById(R.id.tv_comment_time);
comment_layout = itemView.findViewById(R.id.comment_layout);
}
}
}
This is Comment Fragment:
public class CommentFragment extends Fragment {
private DatabaseReference mDatabase;
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
View view;
String value;
RecyclerView recyclerView;
Query query;
TextView comment_text;
long unixTime = System.currentTimeMillis() / 1000L;
public long globalUnix;
Button comment_post;
String comment_string;
Adapter_Comment adapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_comment, container, false);
value = getArguments().getString("key");
mDatabase = FirebaseDatabase.getInstance().getReference();
recyclerView = view.findViewById(R.id.recyclerv_comment);
comment_text = view.findViewById(R.id.tv_comment_type);
comment_post = view.findViewById(R.id.btn_comment_post);
globalUnix = (unixTime * -1);
comment_post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(comment_text.getText().toString() == NULL){
Toast.makeText(getActivity(), "No Comment Typed", Toast.LENGTH_LONG).show();
}
else{
comment com = new comment();
com.uID = user.getUid();
com.comment_t = comment_text.getText().toString();
com.unixTimestamp = globalUnix;
mDatabase.child("comments").child(value).child(globalUnix + "").setValue(com);
}
}
});
initRecyclerView();
return view;
}
private void initRecyclerView(){
//Log.d(TAG, "initRecyclerView: init recyclerView");
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
query = FirebaseDatabase.getInstance().getReference().child("comments").orderByValue();
FirebaseRecyclerOptions<comment> options = new FirebaseRecyclerOptions.Builder<comment>().setQuery(query, comment.class).build();
adapter = new Adapter_Comment(options);
recyclerView.setAdapter(adapter);
adapter.startListening();
adapter.notifyDataSetChanged();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
Inside of the adapter I'm using the comment model, to get the uID, comment and timestamp to fill the holder, however when i set these values im getting null values. Is there something im missing when trying to connect the adapter/firebase and model/holder?
long dv = model.getUnixTimestamp()*-1000;
Date df = new java.util.Date(dv);
String vv = new SimpleDateFormat("MM dd, yyyy hh:mma", Locale.ENGLISH).format(df);
holder.time.setText(vv);
String com = model.getComment();
holder.comment_text.setText(com);
mDatabase.child("users").child(model.getuID()).child("profileUrl").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists())
{
final String picUrl = snapshot.getValue(String.class);
Glide.with(holder.postPfp.getContext()).load(picUrl).into(holder.postPfp);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) { }
});
There's really too much going on in here, but...
As far as I can see you're creating a FirebaseUI adapter on FirebaseDatabase.getInstance().getReference().child("comments"). FirebaseUI adapters show the direct child nodes of the node you pass in, so in your case it'll create one view for the hypno---...196 node. You're trying to read a Comment object from there, but don't exist until one level lower in your JSON.
So you can:
Either show the comments for one post, by basing the adapter off of that. So: FirebaseDatabase.getInstance().getReference().child("comments").child("hypno---...196") (which the real key in there).
Or you can show one piece of information about each post, for example its key.
If you want to show a flat list of comments for all posts through the FirebaseUI adapter, you'll have to store a flat list of comments across all posts in your database too.

New user is part of a group it was never added to

I'm currently working on an app in which users can create groups and add members to groups. Today I created a new user to test the app. When I logged in this new user I checked to see if it was a part of any groups, which I didn't expect it to be seeing as it was new. And it wasn't. But then when I logged in my usual user and clicked groups I saw the name of the test user. Why does it appear that this user is a part of a group it was never added to?
It should be noted that when looking through my firebase this test user doesn't appear to have been invited either. I'm using firestore recycler adapter to fetch data in a recyclerView.
Below is the code for my adapter responsible for adding members to a specific group.
FirestoreMemberAdapter.java:
public class FirestoreMemberAdapter extends FirestoreRecyclerAdapter<MemberModel, FirestoreMemberAdapter.MemberViewHolder> {
private static final String TAG = FirestoreMemberAdapter.class.getSimpleName();
private Context context;
private String projectId;
private String projectName;
public FirestoreMemberAdapter(#NonNull FirestoreRecyclerOptions<MemberModel> options, Context context, String projectId, String projectName) {
super(options);
this.context = context;
this.projectName = projectName;
this.projectId = projectId;
}
#Override
protected void onBindViewHolder(#NonNull MemberViewHolder holder, int position, #NonNull final MemberModel model) {
holder.mTextView.setText(model.getName());
if (model.getProfile_image() == null) {
Picasso.get().load(R.drawable.profile_image).into(holder.mImageview);
} else {
Picasso.get().load(model.getProfile_image()).into(holder.mImageview);
}
holder.mLinearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: Clicked on FirestoreMemberAdapter ");
Intent intent = new Intent(context, ProfileMemberPage.class);
intent.putExtra(StringCreator.PROJECT_TITLE, projectName);
intent.putExtra(StringCreator.PROJECT_ID, projectId);
intent.putExtra(StringCreator.NAME, model.getName());
intent.putExtra(StringCreator.EMAIL, model.getEmail());
intent.putExtra(StringCreator.USER_ID, model.getUser_id());
intent.putExtra(StringCreator.USER_INFORMATION, model.getUser_information());
context.startActivity(intent);
}
});
}
#NonNull
#Override
public MemberViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_projectmembers, parent, false);
return new MemberViewHolder(view);
}
public class MemberViewHolder extends RecyclerView.ViewHolder {
private LinearLayout mLinearLayout;
private TextView mTextView;
private ImageView mImageview;
public MemberViewHolder(#NonNull View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.memberTitle);
mLinearLayout = itemView.findViewById(R.id.layout_members);
mImageview = itemView.findViewById(R.id.memberImage);
}
}
}
Here is the activity in wihch the adapter is used.
projectClicked.java:
//widgets
private RecyclerView recyclerViewMembers;
private TextView projectName;
private Button cameraBtn;
private FloatingActionButton addUserBtn;
//Firebase
private FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
private Query query;
private FirestoreRecyclerOptions<MemberModel> options;
private FirestoreMemberAdapter adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_project_clicked);
projectName = findViewById(R.id.projectName);
addUserBtn = findViewById(R.id.addUserBtn);
cameraBtn = findViewById(R.id.cameraBtn);
initRecyclerView();
addUserBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent newIntent = new Intent(projectClicked.this, UserToProject.class);
Bundle projectBundle = getIntent().getExtras();
if (projectBundle != null) {
newIntent.putExtras(projectBundle);
}
startActivity(newIntent);
}
});
}
private void initRecyclerView() {
Log.d(TAG, "InitRecyclerView: init recyclerview");
if (getIntent().hasExtra(StringCreator.PROJECT_TITLE) && getIntent().hasExtra(StringCreator.PROJECT_ID)) {
final String pName = getIntent().getStringExtra(StringCreator.PROJECT_TITLE);
final String pID = getIntent().getStringExtra(StringCreator.PROJECT_ID);
projectName.setText(pName);
recyclerViewMembers = findViewById(R.id.recyclerView_members);
query = firebaseFirestore.collection("users");
options = new FirestoreRecyclerOptions.Builder<MemberModel>().setQuery(query, MemberModel.class).build();
adapter = new FirestoreMemberAdapter(options, projectClicked.this, pID, pName);
recyclerViewMembers.setHasFixedSize(true);
recyclerViewMembers.setAdapter(adapter);
recyclerViewMembers.setLayoutManager(new LinearLayoutManager(projectClicked.this));
}
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
Hope this makes sense, please reach out if it doesn't. Thank you in advance.
As #McSlinPlay mentioned, the reason could be pointed out to your code in projectClicked.java where you created your query and all the users (including the test user) are part of this collection:
query = firebaseFirestore.collection("users");

How to retrieve just specific data in Recycler View using Firebase Database?

I have a problem with retrieving specific data from Firebase Realtime Database. My problem is that I want to display in RecyclerView just the materials that has the Course_ID (as you can see in the image below) equals to the Course_ID (see Course -> Teacher-Courses in Firebase). How can I accomplish that thing? I will attach the code used in the RecyclerView and the class that contains the model.
As a mention: 1.I have tried to add all the course id's from Firebase and store them to a List, but the app doesn't show anything and 2. In another class I have an Intent that sends me here and also send a extra String with Course_ID that I have accesed.
I am waiting for your responses. Thank you!
FileMaterial.class
public class FileMaterial {
private String Course_ID;
private String Denumire_material;
private String Locatie_material;
private String Teacher_ID;
public FileMaterial() {
}
public FileMaterial(String course_ID, String denumire_material, String locatie_material, String teacher_ID) {
Course_ID = course_ID;
Denumire_material = denumire_material;
Locatie_material = locatie_material;
Teacher_ID = teacher_ID;
}
public String getCourse_ID() {
return Course_ID;
}
public void setCourse_ID(String course_ID) {
Course_ID = course_ID;
}
public String getDenumire_material() {
return Denumire_material;
}
public void setDenumire_material(String denumire_material) {
Denumire_material = denumire_material;
}
public String getLocatie_material() {
return Locatie_material;
}
public void setLocatie_material(String locatie_material) {
Locatie_material = locatie_material;
}
public String getTeacher_ID() {
return Teacher_ID;
}
public void setTeacher_ID(String teacher_ID) {
Teacher_ID = teacher_ID;
}
CourseMaterial.class
public class CourseMaterial extends AppCompatActivity {
private RecyclerView recyclerView;
private DatabaseReference reference, userReference;
private FirebaseAuth mAuth;
FirebaseRecyclerOptions<FileMaterial> options;
FirebaseRecyclerAdapter<FileMaterial, CourseMaterial.FileViewHolder> adapter;
ImageView btnAddMaterial;
ImageView deleteMaterial;
StorageReference storageReference;
FirebaseStorage firebaseStorage;
String urlReference;
String value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_material);
value = getIntent().getStringExtra("course id").toString();
mAuth = FirebaseAuth.getInstance();
reference = FirebaseDatabase.getInstance().getReference().child("Materials").child(mAuth.getCurrentUser().getUid());
recyclerView = findViewById(R.id.recyclerView_fileMaterials);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
btnAddMaterial = findViewById(R.id.addMaterials);
btnAddMaterial.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(CourseMaterial.this, UploadFile.class));
}
});
}
#Override
public void onStart() {
super.onStart();
options = new FirebaseRecyclerOptions.Builder<FileMaterial>().setQuery(reference, FileMaterial.class).build();
adapter = new FirebaseRecyclerAdapter<FileMaterial, FileViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final FileViewHolder fileViewHolder, int i, #NonNull final FileMaterial fileMaterial) {
fileViewHolder.denumire_material.setText(fileMaterial.getDenumire_material());
}
#NonNull
#Override
public FileViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.youtube_view,parent, false);
FileViewHolder fileViewHolder = new FileViewHolder(v);
return fileViewHolder;
}
};
adapter.startListening();
recyclerView.setAdapter(adapter);
}
public static class FileViewHolder extends RecyclerView.ViewHolder{
TextView denumire_material, dataMaterial;
ImageView deleteMaterial;
public FileViewHolder(#NonNull View itemView) {
super(itemView);
denumire_material = itemView.findViewById(R.id.txtDenMaterial);
deleteMaterial = itemView.findViewById(R.id.imgDeleteMaterial);
}
}
Maybe make a query and pass it to the options of the adapter:
#Override
public void onStart() {
super.onStart();
Query query = reference.orderByChild("Course_ID").equalTo(value);
options = new FirebaseRecyclerOptions.Builder<FileMaterial>().setQuery(query, FileMaterial.class).build();
.......
.......
.......

Recycleview for Firebase nested child unable to show

I am trying to populate view of nested child from a user's rewards, but I am unable to show anything out on my android App. Any advice on how do I proceed with it? Please see below regarding the codes iIhave coded so far.
My model
public class myrewards{
String barImg;
public myrewards()
{
}
public myrewards(String barImg) {
this.barImg = barImg;
}
public String getBarImg() {
return barImg;
}
public void setBarImg(String barImg) {
this.barImg = barImg;
}
}
My Viewholder
public class RewardViewHolder extends RecyclerView.ViewHolder{
View mView;
public RewardViewHolder(#NonNull View itemView) {
super(itemView);
mView = itemView;
}
public void setRewardDetail(Context ctx, String barImg)
{
ImageView rImg = mView.findViewById(R.id.rImage);
Picasso.with(ctx).load(barImg).into(rImg);
}
}
My Main Activity
public class MyRewardsActivity extends AppCompatActivity {
private static final String TAG = MyRewardsActivity.class.getSimpleName();
private RecyclerView rRecycleView;
private DatabaseReference myReward, userRef, voucherRef;
private FirebaseAuth mAuth;
private String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_rewards);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("My Rewards");
rRecycleView = findViewById(R.id.my_reward);
rRecycleView.setHasFixedSize(true);
rRecycleView.setLayoutManager(new LinearLayoutManager(this));
mAuth = FirebaseAuth.getInstance();
userID = mAuth.getCurrentUser().getUid();
myReward = FirebaseDatabase.getInstance().getReference().child("User").child(userID);
userRef = FirebaseDatabase.getInstance().getReference().child("User").child(userID);
System.out.println("YOUR REWARD= " + myReward);
}
#Override
protected void onStart() {
super.onStart();
final FirebaseRecyclerAdapter<myrewards, RewardViewHolder> firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<myrewards, RewardViewHolder>
(
myrewards.class,
R.layout.barrewards,
RewardViewHolder.class,
myReward
)
{
#Override
protected void populateViewHolder(RewardViewHolder viewHolder, myrewards model, int position) {
viewHolder.setRewardDetail(getApplicationContext() ,model.getBarImg());
}
};
rRecycleView.setAdapter(firebaseRecyclerAdapter);
}
}
Image shown below:
I am not sure whether I used the correct way to code as I been using this way to retrieve my other data( which are not nested child) from my database, really appericate any helps and thank you in advance.

Sort data Decreasing - Firebase Query [duplicate]

This question already has an answer here:
Sort firebase data in descending order using negative timestamp
(1 answer)
Closed 5 years ago.
I have a database structure like this (sample):
ID_EMPRESA
-name:
-adress:
-status: Aberto
-timestamp: 0154254521
-status_timestamp: Aberto_0154254521
I need to populate my RecyclerView with data from a Firebase reference
Since it is not possible to work with multiple queries when querying Firebase data, according to the structure of the database I tried the following filter:
mDatabase.child(ID_EMPRESA).orderByChild("status_timeStamp").startAt("Open").endAt("Open\uf8ff")
So I retrieve the data that has status: Open
Code RecyclerDapter:
FirebaseRecyclerAdapter<CardPedidos_row, CardPedidosViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<CardPedidos_row, CardPedidosViewHolder>(
CardPedidos_row.class,
R.layout.card_agendamentos_row,
CardPedidosViewHolder.class,
mDatabase.child(ID_EMPRESA).orderByChild("status_timeStamp").startAt("Open").endAt("Open\uf8ff")
)
How could I recover the data in descending order, since it already has the timestamp stored.
As it is, it is bringing Ascending
FullCode - Fragment:
public class PedidosTab1 extends Fragment {
private RecyclerView mCardPedidos;
private DatabaseReference mDatabaseEmpresa;
private DatabaseReference mDatabaseAgendamentos;
private FirebaseAuth mAuth;
private FirebaseUser mCurrentUser;
private TextView mTextPadrao;
private Query query;
public PedidosTab1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_pedidos_tab1, container, false);
/*Recuperando instancia do Firebase*/
mAuth = FirebaseAuth.getInstance();
mCurrentUser = mAuth.getCurrentUser();
mDatabaseEmpresa = FirebaseDatabase.getInstance().getReference().child("Empresas").child(mCurrentUser.getUid());
mDatabaseAgendamentos = FirebaseDatabase.getInstance().getReference().child("Vendas_Empresas");
/*Atributos tela*/
mTextPadrao = (TextView) view.findViewById(R.id.tvPedTab1_textPadrao);
/*RecyclerView*/
mCardPedidos = (RecyclerView) view.findViewById(R.id.cardListaPedidos);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
mCardPedidos.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
carregarPedidos();
return view;
}
private void carregarPedidos() {
mDatabaseAgendamentos.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(mCurrentUser.getUid()).exists()){
carregarDadosRecycler();
} else {
mTextPadrao.setVisibility(View.VISIBLE);
mCardPedidos.setVisibility(View.GONE);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void carregarDadosRecycler() {
FirebaseRecyclerAdapter<CardPedidos_row, CardPedidosViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<CardPedidos_row, CardPedidosViewHolder>(
CardPedidos_row.class,
R.layout.card_agendamentos_row,
CardPedidosViewHolder.class,
mDatabaseAgendamentos.child(mCurrentUser.getUid()).orderByChild("status_timeStamp").startAt("Aberto").endAt("Aberto\uf8ff")
) {
#Override
protected void populateViewHolder(final CardPedidosViewHolder viewHolder, final CardPedidos_row model, int position) {
final String pedido_key = getRef(position).getKey();
String nome_servico = model.getEmpresa_nome();
String nome_empresa = model.getEmpresa_nome();
final String id_empresa = model.getEmpresa_id();
String valor_servico = model.getServico_valor();
String hora = model.getAgenda_hora();
String data = model.getAgenda_data();
String status = model.getStatus_situacao();
String timeStamp = model.getTimestamp_criacaoDt();
viewHolder.setServico_nome(model.getServico_nome());
viewHolder.setAgenda_data(model.getAgenda_data());
viewHolder.setAgenda_hora(model.getAgenda_hora());
viewHolder.setServico_valor(model.getServico_valor());
viewHolder.setEmpresa_nome(model.getEmpresa_nome());
viewHolder.setStatus_situacao(model.getStatus_situacao());
viewHolder.setTimestamp_criacaoDt(model.getTimestamp_criacaoDt());
/*Clique na View*/
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*Intent detalhePedido = new Intent(getActivity().getApplication(), DetalhePedido.class);
detalhePedido.putExtra("id_empresa", id_empresa);
detalhePedido.putExtra("id_venda", pedido_key);
startActivity(detalhePedido);*/
Intent detalhePedido = new Intent(getActivity().getApplication(), DetalhePedido.class);
detalhePedido.putExtra("id_pedido", pedido_key);
startActivity(detalhePedido);
}
});
}
};
mCardPedidos.setAdapter(firebaseRecyclerAdapter);
}
public static class CardPedidosViewHolder extends RecyclerView.ViewHolder{
View mView;
public CardPedidosViewHolder ( View itemView ){
super(itemView);
mView = itemView;
}
public void setServico_nome(String servico_nome){
TextView cardNome_servico = (TextView) mView.findViewById(R.id.tvNomeServico_CardAg);
cardNome_servico.setText(servico_nome);
}
public void setEmpresa_nome(String empresa_nome){
TextView cardNome_empresa = (TextView) mView.findViewById(R.id.tvNomeEmpresa_CardAg);
cardNome_empresa.setText(empresa_nome);
}
public void setServico_valor(String servico_valor){
TextView cardValor_servico = (TextView) mView.findViewById(R.id.tvValor_CardAg);
cardValor_servico.setText(servico_valor);
}
public void setAgenda_data(String agenda_data){
TextView cardData = (TextView) mView.findViewById(R.id.tvData_CardAg);
cardData.setText(agenda_data);
}
public void setAgenda_hora(String agenda_hora){
TextView cardHora = (TextView) mView.findViewById(R.id.tvHora_CardAg);
cardHora.setText(agenda_hora);
}
public void setStatus_situacao(String status_situacao){
TextView cardStatus = (TextView) mView.findViewById(R.id.tvStatus_CardAg);
cardStatus.setText(status_situacao);
}
public void setTimestamp_criacaoDt(String timestamp_criacao){
TextView cardTimeStamp = (TextView) mView.findViewById(R.id.tvTimeStamp);
cardTimeStamp.setText(timestamp_criacao);
}
}
}
This should work!
Add the getItem(int position) method to your FirebaseRecyclerAdapter as:
#Override
public CardPedidos_row getItem(int position) {
return super.getItem(getCount() - position - 1);
}
This will return a list in reverse order.
FirebaseRecyclerAdapter<CardPedidos_row, CardPedidosViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<CardPedidos_row,CardPedidosViewHolder>(
CardPedidos_row.class,
R.layout.card_agendamentos_row,
CardPedidosViewHolder.class,
mDatabaseAgendamentos.child(mCurrentUser.getUid()).orderByChild("status_timeStamp").startAt("Aberto").endAt("Aberto\uf8ff")
) {
#Override
public CardPedidos_row getItem(int position) {
return super.getItem(getCount() - position - 1);
}
#Override
protected void populateViewHolder(final CardPedidosViewHolder viewHolder, final CardPedidos_row model, int position) { ....

Categories

Resources