I want to get the name (String) and the location (String) from my firebase database into a listview of a fragment page of my app. It doesnt give any errors but the name and location text just dont appear on the app. thanks for help. I think there is a problem to get the strings from the firebase server.
Firebase hierarchy : FIREBASE -> Events -> XmasParty -> location = Germany
-> name = XmasParty
FRAGMENT :
public class RequestsFragment extends Fragment {
private Button create_event_btn;
private View mMainView2;
private RecyclerView mEventList;
private DatabaseReference mEventsDatabase;
private LinearLayoutManager mLayoutManager;
public void ChatsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mMainView2 = inflater.inflate(R.layout.fragment_requests, container, false);
mEventsDatabase = FirebaseDatabase.getInstance().getReference().child("Events");
mLayoutManager = new LinearLayoutManager(getContext());
create_event_btn = (Button) mMainView2.findViewById(R.id.create_btn);
mEventList = (RecyclerView) mMainView2.findViewById(R.id.event_list);
mEventList.setHasFixedSize(true);
mEventList.setLayoutManager(mLayoutManager);
create_event_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), Create_EventActivity.class);
startActivity(intent);
}
});
// Inflate the layout for this fragment
return mMainView2;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Events, RequestsFragment.EventsViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Events, EventsViewHolder>(
Events.class,
R.layout.users_single_layout,
RequestsFragment.EventsViewHolder.class,
mEventsDatabase
) {
#Override
protected void populateViewHolder(RequestsFragment.EventsViewHolder eventsViewHolder, Events events, int position) {
eventsViewHolder.setDisplayName(events.getName());
eventsViewHolder.setUserStatus(events.getLocation());
// usersViewHolder.setUserImage(users.getThumb_image(), getApplicationContext());
final String event_id = getRef(position).getKey();
eventsViewHolder.mView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Intent profileIntent = new Intent(UsersActivity.this, ProfileActivity.class);
// profileIntent.putExtra("user_id", user_id);
// startActivity(profileIntent);
}
});
}
};
mEventList.setAdapter(firebaseRecyclerAdapter);
}
public static class EventsViewHolder extends RecyclerView.ViewHolder {
View mView2;
public EventsViewHolder(View itemView2) {
super(itemView2);
mView2 = itemView2;
}
public void setDisplayName(String name){
TextView userNameView = (TextView) mView2.findViewById(R.id.user_single_name);
userNameView.setText(name);
}
public void setUserStatus(String status){
TextView userStatusView = (TextView) mView2.findViewById(R.id.user_single_status);
userStatusView.setText(status);
}
}
}
}
EVENTS CLASS
public class Events {
public String name;
public String location;
public String time;
public Events(){
}
public Events(String name, String location, String time) {
this.name = name;
this.location = location;
this.time = time;
}
public String getName() {return name;}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getTime() {return time;}
public void setTime(String time) {this.time = time;}
}
To get the value of location and name, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference yourRef = rootRef.child("Events").child("XmasParty");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String location = dataSnapshot.child("location").getValue(String.class);
String name = dataSnapshot.child("name").getValue(String.class);
Log.d("TAG", location + " / " + name);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
yourRef.addListenerForSingleValueEvent(eventListener);
The output will be:
Germany / XmasParty
Related
I have manage to get my document id in my AdminOfferFragment and I want to pass the value into the to EditOffer to update my data. I have tried using intent put extra to get my id in another activity but it still display null. So how can I pass my id after onClick in AdminOfferFragment to my EditOffer?
AdminOfferFragment
String id;
RecyclerView myRecycleView;
private FirestoreAdapter2 adapter;
FirebaseFirestore fStore;
private String email = "";
Button Btn;
Button Btn2;
FirebaseAuth fAuth;
String userId ="";
private Integer position = 0;
ArrayList<String> arraylist = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_admin_offer, container, false);
myRecycleView = v.findViewById(R.id.recyclerView);
Btn = v.findViewById(R.id.editBtn);
Btn2 = v.findViewById(R.id.deleteBtn);
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
Btn2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
startActivity(new Intent(getActivity(),LoginUI.class));
}
});
Query query = fStore.collection("offer");
PagedList.Config config = new PagedList.Config.Builder().setInitialLoadSizeHint(10).setPageSize(3).build();
FirestorePagingOptions<OfferInfo> options = new FirestorePagingOptions.Builder<OfferInfo>().setLifecycleOwner(this)
.setQuery(query, config, new SnapshotParser<OfferInfo>() {
#NonNull
#Override
public OfferInfo parseSnapshot(#NonNull DocumentSnapshot snapshot) {
OfferInfo offerInfo = snapshot.toObject(OfferInfo.class);
String itemId = snapshot.getId();
offerInfo.setItem_id(itemId);
return offerInfo;
}
}).build();
adapter = new FirestoreAdapter2(options, this);
myRecycleView.setHasFixedSize(true);
myRecycleView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
myRecycleView.setAdapter(adapter);
return v;
}
#Override
public void onItemClick(DocumentSnapshot snapshot, int position) {
OfferInfo offerInfo = snapshot.toObject(OfferInfo.class);
Log.d("Item_CLICK", "Clicked the item : " + position + "and the ID:" + offerInfo.getName());
Log.d("Item_CLICK", "Clicked the item : " + position + "and the ID:" + snapshot.getId());
this.userId = snapshot.getId();
id = snapshot.getId();
String reward_name = offerInfo.getName();
String reward_description = offerInfo.getDescription();
String reward_point = Integer.toString(offerInfo.getPoint());
this.position = position;
Intent intent = new Intent(getActivity(), EditOffer.class);
intent.putExtra("ID", id);
intent.putExtra("REWARD_NAME", reward_name);
intent.putExtra("REWARD_DESCRIPTION", reward_description);
intent.putExtra("REWARD_POINT", reward_point);
startActivity(intent);
}
public String getOfferId(){
return id;
}
EditOffer
public class EditOffer extends AppCompatActivity {
EditText offer1, description1, point1;
Button editBtn;
FirebaseFirestore fStore;
String id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_offer);
Intent intent = getIntent();
String reward_name = intent.getStringExtra("REWARD_NAME");
String reward_description = intent.getStringExtra("REWARD_DESCRIPTION");
String reward_point = intent.getStringExtra("REWARD_POINT");
offer1 = findViewById(R.id.Rewardinfo);
description1 = findViewById(R.id.description);
point1 = findViewById(R.id.point);
offer1.setText(reward_name);
description1.setText(reward_description);
point1.setText(reward_point);
id = intent.getStringExtra("ID");
editBtn = findViewById(R.id.Btn2);
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Editable newname = offer1.getText();
Editable newdescription = description1.getText();
Editable newpoint = point1.getText();
updateDocument(newname, newdescription, newpoint, id);
}
});
}
private void updateDocument(Editable newname, Editable newdescription, Editable newpoint, String id) {
this.id = id;
DocumentReference documentReference = fStore.collection("offer").document(id);
documentReference.update("name", newname);
documentReference.update("description", newdescription);
documentReference.update("point", newpoint)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(EditOffer.this,"Document Updated",Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(EditOffer.this,e.getMessage(),Toast.LENGTH_LONG).show();
Log.d("Androidview", e.getMessage());
}
});
}
}
FirestoreAdapter2
public class FirestoreAdapter2 extends FirestorePagingAdapter<OfferInfo, FirestoreAdapter2.OfferViewHolder> {
private OnItemClickListener onItemClickListener;
public FirestoreAdapter2(#NonNull FirestorePagingOptions<OfferInfo> options, OnItemClickListener onItemClickListener) {
super(options);
this.onItemClickListener = (OnItemClickListener) onItemClickListener;
}
#Override
protected void onBindViewHolder(#NonNull OfferViewHolder holder, int position, #NonNull OfferInfo model) {
holder.list_email.setText(model.getName());
holder.list_fname.setText(model.getDescription());
holder.list_point.setText(Integer.toString(model.getPoint()));
}
#NonNull
#Override
public OfferViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.offer_item, parent, false);
return new OfferViewHolder(view);
}
public class OfferViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView list_email;
private TextView list_fname;
private TextView list_point;
public OfferViewHolder(#NonNull View itemview) {
super(itemview);
list_email = itemView.findViewById(R.id.textView);
list_fname = itemView.findViewById(R.id.textView2);
list_point = itemView.findViewById(R.id.textView3);
itemview.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onItemClickListener.onItemClick(getItem(getAdapterPosition()), getAdapterPosition());
}
}
public interface OnItemClickListener{
void onItemClick(DocumentSnapshot snapshot, int position);
}
}
OfferInfo
public class OfferInfo {
private String item_id;
private String name;
private String description;
private int point;
private OfferInfo(){}
private OfferInfo(String name, String description, String item_id, int point){
this.name = name;
this.description = description;
this.point = point;
this.item_id = item_id;
}
public String getName(){
return name;
}
public void setEmail(String name){
this.name = name;
}
public String getDescription(){
return description;
}
public void setFName(String description){
this.description = description;
}
public String getItem_id() {
return item_id;
}
public void setItem_id(String item_id) {
this.item_id = item_id;
}
public int getPoint() {
return point;
}
public void setPoint(int point) {
this.point = point;
}
}
In your new activity you don't initialize the firestoreref, so add this in the opened activity:
fStore = FirebaseFirestore.getInstance();
i'm setting up a new online shop application and want to make a condition if value "state" in firebase database is "Not Payments" enable the buttons MYConfirmPayments and MYShowOrderBtn. And if value "state" in firebase database is "Waiting Payments Confirm" disable button MYConfirmPayments.
public class MyOrdersActivity extends AppCompatActivity {
private RecyclerView myOrderList;
private Query myOrdersRef;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_orders);
myOrdersRef = FirebaseDatabase.getInstance().getReference()
.child("Orders")
.orderByKey().equalTo(Prevalent.currentOnlineUser.getPhone());
myOrderList = findViewById(R.id.myOrders_list);
myOrderList.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart()
{
super.onStart();
FirebaseRecyclerOptions<UserOrders> options =
new FirebaseRecyclerOptions.Builder<UserOrders>()
.setQuery(myOrdersRef, UserOrders.class)
.build();
FirebaseRecyclerAdapter<UserOrders,MyOrdersActivity.UserOrdersViewHolder> adapter =
new FirebaseRecyclerAdapter<UserOrders, MyOrdersActivity.UserOrdersViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull MyOrdersActivity.UserOrdersViewHolder holder, final int position, #NonNull final UserOrders model)
{
holder.MYuserName.setText("Nama : " + model.getName());
holder.MYuserPhoneNumber.setText("Nomor Telepon : " + model.getPhone());
holder.MYuserTotalprice.setText("Total Harga = Rp " + model.getTotalAmount());
holder.MYuserDateTime.setText("Dipesan Pada: " + model.getDate() + " " + model.getTime());
holder.MYusershippingAddress.setText("Alamat: " + model.getAddress() + ", " + model.getCity());
holder.MYorderstate.setText("Status: "+ model.getState());
holder.MYconfirmPayments.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view)
{
String uID = getRef(position).getKey();
Intent intent = new Intent(MyOrdersActivity.this, ConfirmPaymentsActivity.class);
intent.putExtra("uid", uID);
startActivity(intent);
}
});
holder.MYshowOrderBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
String uID = getRef(position).getKey();
Intent intent = new Intent(MyOrdersActivity.this, AdminUserProductsActivity.class);
intent.putExtra("uid", uID);
startActivity(intent);
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
CharSequence options[] = new CharSequence[]
{
"Ya",
"Tidak"
};
AlertDialog.Builder builder = new AlertDialog.Builder(MyOrdersActivity.this);
builder.setTitle("Sudah Menerima Barang ini ?");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i)
{
if (i == 0)
{
String uID = getRef(position).getKey();
RemoverOrder(uID);
}
else
{
finish();
}
}
});
builder.show();
}
});
}
#NonNull
#Override
public MyOrdersActivity.UserOrdersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.orders_layout, parent, false);
return new MyOrdersActivity.UserOrdersViewHolder(view);
}
};
myOrderList.setAdapter(adapter);
adapter.startListening();
}
public static class UserOrdersViewHolder extends RecyclerView.ViewHolder
{
public TextView MYuserName, MYuserPhoneNumber, MYuserTotalprice, MYuserDateTime, MYusershippingAddress, MYorderstate;
public Button MYconfirmPayments, MYshowOrderBtn;
public UserOrdersViewHolder(View itemView)
{
super(itemView);
MYuserName = itemView.findViewById(R.id.myOrders_user_name);
MYuserPhoneNumber = itemView.findViewById(R.id.myOrders_phone_number);
MYuserTotalprice = itemView.findViewById(R.id.myOrders_total_price);
MYuserDateTime = itemView.findViewById(R.id.myOrders_date_time);
MYusershippingAddress = itemView.findViewById(R.id.myOrders_address_city);
MYorderstate = itemView.findViewById(R.id.myOrders_state);
MYconfirmPayments = itemView.findViewById(R.id.myConfirm_payments);
MYshowOrderBtn= itemView.findViewById(R.id.myShow_all_products);
}
}
private void RemoverOrder(String uID)
{
}
}
My UserOrders Class
public class UserOrders
{
private String name, phone, address, city, state, date, time, totalAmount;
public UserOrders()
{
}
public UserOrders(String name, String phone, String address, String city, String state, String date, String time, String totalAmount) {
this.name = name;
this.phone = phone;
this.address = address;
this.city = city;
this.state = state;
this.date = date;
this.time = time;
this.totalAmount = totalAmount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(String totalAmount) {
this.totalAmount = totalAmount;
}
}
And this My Firebase Database Structured
You can use this code :
database = FirebaseDatabase.getInstance().getReference();
database.child("Orders").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userDataSnapshot : dataSnapshot.getChildren()) {
UserOrders order = userDataSnapshot.getValue(UserOrders.class);
String state = order .getState();
if (state.equals("Not Payments")) {
MYConfirmPayments.setEnabled(true);
MYShowOrderBtn.setEnabled(true);
}else if (state.equals("Not Payments")){
MYConfirmPayments.setEnabled(false);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w("tag", "loadPost:onCancelled", databaseError.toException());
}
});
I am making an android app ,which is get order from customers,but i faced a problem . I am trying to Retrieve Data from Firebase and display in a list view. I can get the data back from Firebase but when it displays in the listview it just displays one data in many times. I want to be displayed on one line for each record. Can anyone see where i am going wrong??
Database Image
ListView Image
OrderHistory
public class OrderHistory
{
String ammount,photoId,trxId,name,copy,photoSize,date;
public OrderHistory(String name,String photoId,String trxId,String copy,String photoSize,String ammount,String date)
{
this.name = name;
this.ammount = ammount;
this.photoId = photoId;
this.copy = copy;
this.photoSize = photoSize;
this.trxId = trxId;
this.date = date;
}
public String getAmmount() {
return ammount;
}
public void setAmmount(String ammount) {
this.ammount = ammount;
}
public String getPhotoId() {
return photoId;
}
public void setPhotoId(String photoId) {
this.photoId = photoId;
}
public String getTrxId() {
return trxId;
}
public void setTrxId(String trxId) {
this.trxId = trxId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCopy() {
return copy;
}
public void setCopy(String copy) {
this.copy = copy;
}
public String getPhotoSize() {
return photoSize;
}
public void setPhotoSize(String photoSize) {
this.photoSize = photoSize;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
OrderHistoryAdapter
public class OrderHistoryAdapter extends BaseAdapter {
private List<OrderHistory> orderHistories;
Context context;
public OrderHistoryAdapter(Context context, List<OrderHistory> myOrderInformations) {
this.context = context;
this.orderHistories = myOrderInformations;
}
#Override
public int getCount() {
return orderHistories.size();
}
#Override
public Object getItem(int position) {
return orderHistories.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.show_my_order_history, parent, false);
final TextView txtName, txtdate, txtPhotoId, trxId,txtAmount,txtPhotoSize,txtCopy;
txtName = (TextView)view.findViewById(R.id.txtName);
txtdate = (TextView)view.findViewById(R.id.txtDate);
txtPhotoId = (TextView)view.findViewById(R.id.txtPhotoId);
trxId = (TextView)view.findViewById(R.id.txtTrx);
txtAmount = (TextView)view.findViewById(R.id.txtAmount);
txtPhotoSize = (TextView)view.findViewById(R.id.txtSize);
txtCopy = (TextView)view.findViewById(R.id.txtCopy);
txtName.setText(orderHistories.get(position).getName());
txtdate.setText(orderHistories.get(position).getDate());
txtPhotoId.setText(orderHistories.get(position).getPhotoId());
trxId.setText(orderHistories.get(position).getTrxId());
txtAmount.setText(orderHistories.get(position).getAmmount());
txtCopy.setText(orderHistories.get(position).getCopy());
txtPhotoSize.setText(orderHistories.get(position).getPhotoSize());
return view;
}
}
OrderHistoryList
public class OrderHistoryList extends AppCompatActivity
{
private DatabaseReference databaseReference;
private List<OrderHistory> orderHistories;
private static String phoneNumber;
private ListView listView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_my_order);
Firebase.setAndroidContext(this);
listView = (ListView)findViewById(R.id.listView);
getAllOrderFromFirebase();
}
private void getAllOrderFromFirebase()
{
orderHistories = new ArrayList<>();
databaseReference = FirebaseDatabase.getInstance().getReference("order");
String phone = getIntent().getExtras().getString("phone");
databaseReference.orderByChild("phone").equalTo(phone).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String amount, photoId, trxId, name, copy, photoSize, date;
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
name = snapshot.child("name").getValue(String.class);
photoId = snapshot.child("photoId").getValue(String.class);
amount = snapshot.child("totalAmount").getValue(String.class);
trxId = snapshot.child("trxId").getValue(String.class);
photoSize = snapshot.child("photoSize").getValue(String.class);
date = snapshot.child("date").getValue(String.class);
copy = snapshot.child("totalCopy").getValue(String.class);
orderHistories.add(new OrderHistory(name, photoId, trxId, copy, photoSize, amount, date));
}
OrderHistoryAdapter adapter;
adapter = new OrderHistoryAdapter(OrderHistoryList.this, orderHistories);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
I guess your problem is by the way you refer to your data so instead of this
databaseReference = FirebaseDatabase.getInstance().getReference("order");
use this
databaseReference = FirebaseDatabase.getInstance().getReference().child("order");
and you didn't use a query object to query your database reference
so now you don't query directly from databaseReference like the way you did it
instead you do this:
Query query=databaseReference.orderByChild("phone").equalTo(phone);
once you have a query that fits you now add on child listener and continue the rest of your code:
query.addChildEventListener(new ChildEventListener() {
//the rest of your code goes here(on child added/changed/......)
)};
I am using firebase to view timestamp and after I save the stored the timestamp in my firebase the issue is how to convert the int number value to correctly value like "1 hr" ...
When I retrieve the timestamp it get int number ex:"1487330278409"
here's my value which named "creationDate"
how to get timestamp ex: 3 hours ago, 1 day, just now.
here's my fragment
public class Challenges extends Fragment{
private RecyclerView mPostList;
private DatabaseReference mDatabase,mDatabaseFriends,mDatabaseLike;
private SwipeRefreshLayout mRefreshLayout;
private boolean mProcessLike = false;
private String AA;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mListener;
private Query mQuery;
private FirebaseUser mCurrentUser;
public Challenges() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MultiDex.install(getActivity());}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.challenges, container, false);
mListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
final FirebaseUser User = firebaseAuth.getCurrentUser();
if (User == null) {
Intent A = new Intent(getActivity(), Login.class);
startActivity(A);}}};
mPostList=(RecyclerView)v.findViewById(R.id.PostList);
mPostList.setHasFixedSize(true);
mPostList.setItemAnimator(new DefaultItemAnimator());
mPostList.setLayoutManager(new LinearLayoutManager(getActivity()));
//AA = getActivity().getIntent().getExtras().getString("QQ");
//Firebase
mDatabase= FirebaseDatabase.getInstance().getReference().child("Posts");
mDatabaseFriends= FirebaseDatabase.getInstance().getReference().child("Friends");
mDatabaseLike = FirebaseDatabase.getInstance().getReference().child("Likes");
mDatabase.keepSynced(true);
mDatabaseLike.keepSynced(true);
mAuth = FirebaseAuth.getInstance();
mCurrentUser = mAuth.getCurrentUser();
mRefreshLayout=(SwipeRefreshLayout)v.findViewById(R.id.RefreshLayout);
//mQuery = mDatabase.orderByChild("UID").equalTo(String.valueOf(mDatabaseFriends.child(mCurrentUser.getUid()).child("Accepted")));
mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
onStart();}});
return v;}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mListener);
mRefreshLayout.setRefreshing(true);
final FirebaseRecyclerAdapter<Getting_Posts, PostViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Getting_Posts, PostViewHolder>(
Getting_Posts.class, R.layout.post_card_design, PostViewHolder.class, mDatabase) {
#SuppressLint("SetTextI18n")
#Override
protected void populateViewHolder(final PostViewHolder viewHolder, final Getting_Posts model, int position) {
final String Post_Key = getRef(position).getKey();
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent A = new Intent(getActivity(), com.pcsoftgroup.test.activities.Single_view.class);
A.putExtra("Key", Post_Key);
startActivity(A);}
});
viewHolder.setUsername(model.getUsername());
viewHolder.setProfile(getActivity().getApplicationContext(), model.getProfile());
viewHolder.setDescribe(model.getDescribe());
viewHolder.setWallpaper(getActivity().getApplicationContext(), model.getWallpaper());
viewHolder.setLike(Post_Key);
viewHolder.setLikeNum(Post_Key);
viewHolder.setCommentNum(Post_Key);
viewHolder.mPostTime.setText(model.getTime());
//viewHolder.mPostTime.setText(model.getDate());
//viewHolder.mPostATime.setText(model.getTime());
viewHolder.mLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProcessLike = true;
mDatabaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessLike) {
if (dataSnapshot.child(Post_Key).hasChild(mCurrentUser.getUid())) {
mDatabaseLike.child(Post_Key).child(mCurrentUser.getUid()).removeValue();
mProcessLike = false;
} else {
mDatabaseLike.child(Post_Key).child(mCurrentUser.getUid()).setValue("LIKED");
mProcessLike = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
viewHolder.mShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
//sendIntent.putExtra(Intent.EXTRA_TEXT,viewHolder.mComment.getText().toString());
sendIntent.setType("text/plain");
Intent.createChooser(sendIntent, "Share via");
startActivity(sendIntent);
}
});
mRefreshLayout.setRefreshing(false);
mRefreshLayout.setEnabled(true);
}
};
mPostList.setAdapter(firebaseRecyclerAdapter);}
public static class PostViewHolder extends RecyclerView.ViewHolder{
//Main
View mView;
ImageButton mLike;
ImageButton mCommentBtn;
ImageButton mShare;
//Firebase
TextView mPostTime;
TextView mPostATime;
FirebaseAuth mAuth;
FirebaseUser mCurrentUser;
DatabaseReference mDatabaseLike;
DatabaseReference mDatabaseComment;
public PostViewHolder(View itemView) {
super(itemView);
//Main
mView=itemView;
mPostATime = (TextView) mView.findViewById(R.id.PostATime);
mLike=(ImageButton) mView.findViewById(R.id.PostLike);
mCommentBtn = (ImageButton) mView.findViewById(R.id.PostCommentBtn);
mShare = (ImageButton) mView.findViewById(R.id.PostShare);
mPostTime = (TextView) mView.findViewById(R.id.PostTime);
//Firebase
mAuth =FirebaseAuth.getInstance();
mCurrentUser=mAuth.getCurrentUser();
mDatabaseComment = FirebaseDatabase.getInstance().getReference().child("Comments");
mDatabaseLike= FirebaseDatabase.getInstance().getReference().child("Likes");
mDatabaseLike.keepSynced(true);
mDatabaseComment.keepSynced(true);
}
//Like
void setLike(final String Post_Key){
mDatabaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(Post_Key).hasChild(mCurrentUser.getUid())){
mLike.setImageResource(R.drawable.like_icon);
}else {mLike.setImageResource(R.drawable.unlike_icon);}}
#Override
public void onCancelled(DatabaseError databaseError) {}});}
void setLikeNum(final String Post_Key){
mDatabaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String A = String.valueOf(dataSnapshot.child(Post_Key).getChildrenCount());
TextView PostLikeNum = (TextView) mView.findViewById(R.id.PostLikeNum);
PostLikeNum.setText(A);}
#Override
public void onCancelled(DatabaseError databaseError) {}});}
void setCommentNum(final String Post_Key){
mDatabaseComment.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String C = String.valueOf(dataSnapshot.child(Post_Key).getChildrenCount());
TextView PostCommentNum = (TextView) mView.findViewById(R.id.PostCommentNum);
PostCommentNum.setText(C);}
#Override
public void onCancelled(DatabaseError databaseError) {}});}
//Username
public void setUsername(String Username){
TextView PostUsername = (TextView) mView.findViewById(R.id.PostUsername);
PostUsername.setText(Username);}
//Profile
void setProfile(Context ctx2, String Profile){
ImageView PostProfile = (ImageView) mView.findViewById(R.id.PostUserImage);
if (Profile == null){PostProfile.setVisibility(View.VISIBLE);}
else {PostProfile.setVisibility(View.VISIBLE);
Picasso.with(ctx2).load(Profile).resize(120,120).into(PostProfile);}}
//Describe
void setDescribe(String Describe){
TextView PostDescribe = (TextView) mView.findViewById(R.id.PostDesc);
PostDescribe.setText(Describe);}
//Image Load
void setWallpaper(Context ctx, String Image){
ImageView PostWallpaper = (ImageView) mView.findViewById(R.id.PostWallpaper);
if (Image == null){PostWallpaper.setVisibility(View.VISIBLE);}
else {
PostWallpaper.setVisibility(View.VISIBLE);
Picasso.with(ctx).load(Image).resize(1200,600).into(PostWallpaper);}}
}}
and here's my getter and setter java:
public class Getting_Posts {
private String Username;
private String Profile;
private String Describe;
private String Wallpaper;
private String Time;
public Getting_Posts() {
}
public Getting_Posts(String Time, String Username, String Profile, String Describe, String Wallpaper) {
this.Username = Username;
this.Profile = Profile;
this.Describe = Describe;
this.Wallpaper = Wallpaper;
this.Time = Time;
}
public String getDescribe() {
return Describe;
}
public void setDescribe(String describe) {
Describe = describe;
}
public String getWallpaper() {
return Wallpaper;
}
public void setWallpaper(String wallpaper) {
Wallpaper = wallpaper;
}
public String getUsername() {
return Username;
}
public void setUsername(String username) {
Username = username;
}
public String getProfile() {
return Profile;
}
public void setProfile(String profile) {
Profile = profile;
}
public String getTime() {
return Time;
}
public void setTime(String time) {
Time = time;
}
}
Any help please
The retrieved value is a long value representing Milliseconds elapsed since the Epoch time.
You can set this inside a Date object and get the normal human readable version:
Date currentDate = new Date(your_retreived_long_timestamp);
System.out.println(currentDate);
Difference between the currenttimestamp long value and an old timestamp will give the time passed since the old value..
eg : if currenttimestamp - oldtimestamp = 60000
It shows that the oldtimestamp happened a minute ago (60sec * 1000), similarly find the other values as you want
You can then use the current time and the obtained time and find the difference yourself.
This is SearchActivity.java
public class SearchActivity extends AppCompatActivity
{
/*UI*/
private EditText mSearchText;
private Button mSearchBtn;
private Toolbar mSearchToolbar;
private FragmentPagerAdapter mPagerAdapter;
private ViewPager mViewPager;
private String value;
private TextWatcher tw;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
mSearchText = (EditText)findViewById(R.id.activity_search_search_text);
mSearchBtn = (Button)findViewById(R.id.activity_search_search_btn);
mSearchToolbar = (Toolbar)findViewById(R.id.activity_search_toolbar);
setSupportActionBar(mSearchToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(null);
mSearchBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
value = mSearchText.getText().toString();
Toast.makeText(SearchActivity.this, "value test 1: " + value, Toast.LENGTH_LONG).show();
searchText(value);
}
});
}
private void searchText(final String value)
{
Toast.makeText(SearchActivity.this, "value test 2: " + value, Toast.LENGTH_LONG).show();
mPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager())
{
private final Fragment[] mFragments = new Fragment[]
{
new FragmentSearch(value)
};
#Override
public Fragment getItem(int position)
{
return mFragments[position];
}
#Override
public int getCount()
{
return mFragments.length;
}
};
mViewPager = (ViewPager) findViewById(R.id.activity_search_view_pager);
mViewPager.setAdapter(mPagerAdapter);
}
}
This is FragmentSearch.java
public class FragmentSearch extends MainFragment
{
public String value;
public FragmentSearch(String value)
{
this.value = value;
}
#Override
public Query getQuery(DatabaseReference databaseReference)
{
Toast.makeText(getActivity().this, "value test 3: " + value, Toast.LENGTH_LONG).show();
Query postsQuery = databaseReference.child("Post").orderByChild("title").equalTo(value);
return postsQuery;
}
}
This is MainFragment.java
public abstract class MainFragment extends Fragment
{
private DatabaseReference mDatabase;
private FirebaseRecyclerAdapter<Post, PostViewHolder> mAdapter;
private RecyclerView mRecycler;
private LinearLayoutManager mManager;
public MainFragment()
{
}
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_all_posts, container, false);
mDatabase = FirebaseDatabase.getInstance().getReference();
mRecycler = (RecyclerView)rootView.findViewById(R.id.messages_list);
mRecycler.setHasFixedSize(true);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
mManager = new LinearLayoutManager(getActivity());
mManager.setReverseLayout(true);
mManager.setStackFromEnd(true);
mRecycler.setLayoutManager(mManager);
Query postsQuery = getQuery(mDatabase);
mAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(Post.class, R.layout.item_post,
PostViewHolder.class, postsQuery)
{
#Override
protected void populateViewHolder(final PostViewHolder viewHolder, final Post model, final int position)
{
final DatabaseReference postRef = getRef(position);
final String postKey = postRef.getKey();
viewHolder.itemView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// Intent intent = new Intent(getActivity(), PostDetailActivity.class);
// intent.putExtra(PostDetailActivity.EXTRA_POST_KEY, postKey);
// startActivity(intent);
}
});
if(model.stars.containsKey(getUid()))
{
viewHolder.starView.setImageResource(R.drawable.ic_toggle_star_24);
}
else
{
viewHolder.starView.setImageResource(R.drawable.ic_toggle_star_outline_24);
}
viewHolder.bindToPost(model, new View.OnClickListener()
{
#Override
public void onClick(View starView)
{
DatabaseReference globalPostRef = mDatabase.child("Post").child(postRef.getKey());
DatabaseReference userPostRef = mDatabase.child("UserPost").child(model.uid).child(postRef.getKey());
onStarClicked(globalPostRef);
onStarClicked(userPostRef);
}
});
}
};
mRecycler.setAdapter(mAdapter);
}
private void onStarClicked(DatabaseReference postRef) {
postRef.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
Post p = mutableData.getValue(Post.class);
if (p == null) {
return Transaction.success(mutableData);
}
if (p.stars.containsKey(getUid())) {
// Unstar the post and remove self from stars
p.starCount = p.starCount - 1;
p.stars.remove(getUid());
} else {
// Star the post and add self to stars
p.starCount = p.starCount + 1;
p.stars.put(getUid(), true);
}
// Set value and report transaction success
mutableData.setValue(p);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
}
});
}
#Override
public void onDestroy()
{
super.onDestroy();
if (mAdapter != null)
{
mAdapter.cleanup();
}
}
public String getUid()
{
return FirebaseAuth.getInstance().getCurrentUser().getUid();
}
public abstract Query getQuery(DatabaseReference databaseReference);
}
This is PostViewHolder.java
public class PostViewHolder extends RecyclerView.ViewHolder
{
public TextView titleView;
public TextView authorView;
public ImageView starView;
public TextView numStarsView;
public TextView bodyView;
public PostViewHolder(View itemView)
{
super(itemView);
titleView = (TextView) itemView.findViewById(R.id.post_title);
authorView = (TextView) itemView.findViewById(R.id.post_author);
starView = (ImageView) itemView.findViewById(R.id.star);
numStarsView = (TextView) itemView.findViewById(R.id.post_num_stars);
bodyView = (TextView) itemView.findViewById(R.id.post_body);
}
public void bindToPost(Post post, View.OnClickListener starClickListener)
{
titleView.setText(post.title);
authorView.setText(post.author);
numStarsView.setText(String.valueOf(post.starCount));
bodyView.setText(post.body);
starView.setOnClickListener(starClickListener);
}
}
This is Post.java
#IgnoreExtraProperties
public class Post
{
public String uid;
public String author;
public String title;
public String body;
public int starCount = 0;
public String type;
public Map<String, Boolean> stars = new HashMap<>();
public Post()
{
}
public Post(String uid, String author, String title, String body, String type)
{
this.uid = uid;
this.author = author;
this.title = title;
this.body = body;
this.type = type;
}
#Exclude
public Map<String, Object> toMap()
{
HashMap<String, Object> result = new HashMap<>();
result.put("uid", uid);
result.put("author", author);
result.put("title", title);
result.put("body", body);
result.put("starCount", starCount);
result.put("stars", stars);
result.put("type", type);
return result;
}
}
Thank you so much for reading. I created a program to search title of the posts. When I type title in the EditText then press Search button, my toast1 test, toast2 test, and toast3 test give correct and same value and it successfully lists what I want with Query. But the problem is that when I type different text in EditText after deleting the previous text then press enter, toast3 test(in FragmentSearch.java) stays the same and does not change value. So, it just gives the previous result, not changed result. Can anyone assist me with this? Thank you!
The problem is that you only change the value on the FragmentSearch constructor. And this constructor is only called once, and not when you press Enter.
You should change your getQuery method to have this value as a parameter.
On your MainFragment.java:
public abstract Query getQuery(DatabaseReference databaseReference, String value);
On your FragmentSearch.java:
#Override
public Query getQuery(DatabaseReference databaseReference, String value)
{
this.value = value;
Toast.makeText(getActivity().this, "value test 3: " + value, Toast.LENGTH_LONG).show();
Query postsQuery = databaseReference.child("Post").orderByChild("title").equalTo(value);
return postsQuery;
}