Так что это мой дизайн, и текстовое представление моего требуемого времени находится внизу слева, именно там я просматриваю свои x дней, и по умолчанию в настоящее время он обычно не вычисляет дни.
Поэтому у меня возникла проблема с получением даты публикации изображения и вычислением x дней между начальной и текущей датами независимо для каждого сообщения.
Итак, япытался получить дату разницы с отметкой времени в методе пытался вызвать этот метод к другому методу, чтобы установить разницу дней между начальной и текущей датой в моем TextView. Я пробовал несколько способов получить только результат по умолчанию, возможно, я использую это неправильно?
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ImageViewHolder> {
private Context mContext;
private List<Post> mPosts;
private Post post;
private FirebaseUser firebaseUser;
public PostAdapter(Context context, List<Post> posts){
mContext = context;
mPosts = posts;
}
@NonNull
@Override
public PostAdapter.ImageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.post_item, parent, false);
return new PostAdapter.ImageViewHolder(view);
}
@Override
public void onBindViewHolder( final PostAdapter.ImageViewHolder holder, final int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final Post post = mPosts.get(position);
if(post.getPostimage() != null) {
Glide.with(mContext.getApplicationContext()).load(post.getPostimage())
.apply(new RequestOptions().placeholder(R.drawable.placeholder))
.into(holder.post_image);
}
else
{
Glide.with(mContext.getApplicationContext()).load("https://firebasestorage.googleapis.com/v0/b/araba-92732.appspot.com/o/placeholder.png?alt=media&token=b98a5c60-1ebf-4d14-bad4-b4e707c59d56")
.apply(new RequestOptions().placeholder(R.drawable.placeholder))
.into(holder.post_image);
}
if (post.getCarType() == null
&& post.getPrice() == null
&& post.getModel() == null
&& post.getDistance() == null
&& post.getColor() == null
&& post.getLocation() == null){
holder.carType2.setVisibility(View.GONE);
holder.price.setVisibility(View.GONE);
holder.model.setVisibility(View.GONE);
holder.distance.setVisibility(View.GONE);
holder.color.setVisibility(View.GONE);
holder.tvLocation.setVisibility(View.GONE);
}
else {
holder.carType2.setVisibility(View.VISIBLE);
holder.carType2.setText(post.getCarType());
holder.price.setVisibility(View.VISIBLE);
holder.price.setText(post.getPrice());
holder.model.setVisibility(View.VISIBLE);
holder.model.setText(post.getModel());
holder.distance.setVisibility(View.VISIBLE);
holder.distance.setText(post.getDistance());
holder.color.setVisibility(View.VISIBLE);
holder.color.setText(post.getColor());
holder.tvLocation.setVisibility(View.VISIBLE);
holder.tvLocation.setText(post.getLocation());
}
publisherInfo(holder.image_profile, holder.tvPublisher, post.getPublisher());
isLiked(post.getPostid(), holder.like);
isSaved(post.getPostid(), holder.save);
nrLikes(holder.likes, post.getPostid());
if(firebaseUser != null) {
holder.like.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (holder.like.getTag().equals("like")) {
FirebaseDatabase.getInstance().getReference().child("Likes").child(post.getPostid())
.child(firebaseUser.getUid()).setValue(true);
addNotification(post.getPublisher(), post.getPostid());
} else {
FirebaseDatabase.getInstance().getReference().child("Likes").child(post.getPostid())
.child(firebaseUser.getUid()).removeValue();
}
}
});
holder.save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (holder.save.getTag().equals("save")) {
FirebaseDatabase.getInstance().getReference().child("Saves").child(firebaseUser.getUid())
.child(post.getPostid()).setValue(true);
} else {
FirebaseDatabase.getInstance().getReference().child("Saves").child(firebaseUser.getUid())
.child(post.getPostid()).removeValue();
}
}
});
}
holder.image_profile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", MODE_PRIVATE).edit();
editor.putString("profileid", post.getPublisher());
editor.apply();
((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
}
});
holder.post_image.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", MODE_PRIVATE).edit();
editor.putString("postid", post.getPostid());
editor.apply();
((FragmentActivity) mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new PostDetailFragment()).commit();
}
});
holder.likes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(mContext, FollowersActivity.class);
intent.putExtra("id", post.getPostid());
intent.putExtra("title", "likes");
mContext.startActivity(intent);
}
});
holder.more.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
PopupMenu popupMenu = new PopupMenu(mContext, view);
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.edit:
editPost(post.getPostid());
return true;
case R.id.delete:
final String id = post.getPostid();
FirebaseDatabase.getInstance().getReference("Posts")
.child(post.getPostid()).removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
deleteNotifications(id, firebaseUser.getUid());
}
}
});
return true;
case R.id.report:
Toast.makeText(mContext, "Reported clicked!", Toast.LENGTH_SHORT).show();
return true;
default:
return false;
}
}
});
popupMenu.inflate(R.menu.post_menu);
if (!post.getPublisher().equals(firebaseUser.getUid())){
popupMenu.getMenu().findItem(R.id.edit).setVisible(false);
popupMenu.getMenu().findItem(R.id.delete).setVisible(false);
}
else if (post.getPublisher().equals(firebaseUser.getUid())){
popupMenu.getMenu().findItem(R.id.report).setVisible(false);
}
popupMenu.show();
}
});
}
@Override
public int getItemCount() {
return mPosts.size();
}
class ImageViewHolder extends RecyclerView.ViewHolder {
ImageView image_profile, post_image, like, save, more;
TextView carType2, likes, carType, price, model, distance, color, tvLocation, tvPublisher, iTP;
ImageViewHolder(View itemView) {
super(itemView);
image_profile = itemView.findViewById(R.id.image_profile);
carType2 = itemView.findViewById(R.id.carType2);
post_image = itemView.findViewById(R.id.post_image);
like = itemView.findViewById(R.id.like);
save = itemView.findViewById(R.id.save);
likes = itemView.findViewById(R.id.likes);
carType = itemView.findViewById(R.id.carType);
price = itemView.findViewById(R.id.price);
model = itemView.findViewById(R.id.model);
distance = itemView.findViewById(R.id.distance);
color = itemView.findViewById(R.id.color);
tvLocation = itemView.findViewById(R.id.tvLocation);
tvPublisher = itemView.findViewById(R.id.tvPublisher);
iTP = itemView.findViewById(R.id.image_time_posted);
more = itemView.findViewById(R.id.more);
}
private void setupWidgets(){
String timestampDiff = getTimestampDifference();
if(!timestampDiff.equals("0")){
iTP.setText(timestampDiff + " DAYS AGO");
}else{
iTP.setText("TODAY");
}
}
private String getTimestampDifference(){
String difference = "";
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.GERMAN);
sdf.setTimeZone(TimeZone.getTimeZone("German"));//google 'android list of timezones'
Date today = c.getTime();
sdf.format(today);
Date timestamp;
final String photoTimestamp = post.getPostimage();
try {
timestamp = sdf.parse(photoTimestamp);
difference = String.valueOf(Math.round(((today.getTime() - timestamp.getTime()) / 1000 / 60 / 60 / 24)));
} catch (ParseException e) {
difference = "0";
}
return difference;
}
}
Это мой домашний фрагмент, содержащий RV сообщений
package com.capstone.araba.Fragments;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.capstone.araba.Adapter.PostAdapter;
import com.capstone.araba.Model.Post;
import com.capstone.araba.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.TimeZone;
public class HomeFragment extends Fragment
{
private PostAdapter postAdapter;
private List<Post> postList;
private FirebaseUser firebaseUser;
private List<String> followingList;
private ProgressBar progress_circular;
private EditText search_bar, search_bar2;
private TextView iTP;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_home_fragment, container, false);
RecyclerView recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getContext());
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(mLayoutManager);
search_bar = view.findViewById(R.id.search_bar);
search_bar2 = view.findViewById(R.id.search_bar2);
postList = new ArrayList<>();
postAdapter = new PostAdapter(getContext(), postList);
recyclerView.setAdapter(postAdapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(),
LinearLayoutManager.HORIZONTAL, false);
progress_circular = view.findViewById(R.id.progress_circular);
search_bar.clearFocus();
search_bar2.clearFocus();
checkFollowing();
readPostsSearch();
search_bar.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
searchPosts(charSequence.toString(),"carType");
}
@Override
public void afterTextChanged(Editable editable) {
}
});
search_bar2.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
searchPosts(charSequence.toString(),"location");
}
@Override
public void afterTextChanged(Editable editable) {
}
});
return view;
}
private void searchPosts(String s, String type){
final Query query = FirebaseDatabase.getInstance().getReference("Posts").orderByChild(type)
.startAt(s.toUpperCase())
.endAt(s.toLowerCase() + "\uf8ff");
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
postList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Post post = snapshot.getValue(Post.class);
postList.add(post);
}
postAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void readPostsSearch() {
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (search_bar.getText().toString().equals("") || search_bar2.getText().toString().equals("")) {
postList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Post post = snapshot.getValue(Post.class);
progress_circular.setVisibility(View.GONE);
postList.add(post);
}
postAdapter.notifyDataSetChanged();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void checkFollowing(){
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
assert firebaseUser != null;
followingList = new ArrayList<>();
if(firebaseUser != null) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Follow")
.child(Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser()).getUid())
.child("following");
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
followingList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
followingList.add(snapshot.getKey());
}
readPosts();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
private void readPosts(){
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
postList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Post post = snapshot.getValue(Post.class);
// for (String id : followingList){
// if (post.getPublisher().equals(id)){
postList.add(post);
progress_circular.setVisibility(View.GONE);
// }
// }
}
postAdapter.notifyDataSetChanged();
progress_circular.setVisibility(View.GONE);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}