1

I'm working on a blog app where I've created the card_view in which the user name, profile picture, time of post and other details are displayed. As of now everything is fine except one thing the time and date. Now this is a thing which is taking a hell lot of time on researching but the thing is that my work is not getting solved.

1. Work till now on Time and date

  • What I've done is I've saved the user posting time in TIMESTAMP.
  • Now in order to achieve my goal i.e., to retrieve the post_time in human readable form I've done a lot of researches on how to change the data from timestamp form to nonth and year, hours format.

My post_time is in LONG in my POJO and it is being stored in my database successfully

In my BlogFragment I'm retrieving my details.

2. Blog.java

public void setPost_time(Long post_time){
            TextView time = (TextView) mView.findViewById(R.id.post_time);
            DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            Date date = null;
            try {
                date = dateFormat.parse(post_time.toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            time.setText(dateFormat.format(date));
        }

I've done the above code after following a lot of codes on Stackoverflow but never got a solution.

My searches for solution:

To fix nullpointerexception on date format

Java Illegal argument on the date format

Firebase.TIMESTAMP Docs

Working with date class

Populate the date and time in human readable form in listview

I've tried one more thing in order to convert the TIMESTAMP format to human readable format which goes like this:

Convert timestamp format into hour and date format

I got the error in my logcat when I implemented the above code in Blog.java

3. LogCat

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.aadarshkumarsingh.project1, PID: 10460
              com.google.firebase.database.DatabaseException: Failed to convert a value of type java.lang.String to long
                  at com.google.android.gms.internal.zzbqi.zzaA(Unknown Source)
                  at com.google.android.gms.internal.zzbqi.zzc(Unknown Source)
                  at com.google.android.gms.internal.zzbqi.zzb(Unknown Source)
                  at com.google.android.gms.internal.zzbqi.zza(Unknown Source)
                  at com.google.android.gms.internal.zzbqi.zzb(Unknown Source)
                  at com.google.android.gms.internal.zzbqi$zza.zze(Unknown Source)
                  at com.google.android.gms.internal.zzbqi$zza.zzaG(Unknown Source)
                  at com.google.android.gms.internal.zzbqi.zze(Unknown Source)
                  at com.google.android.gms.internal.zzbqi.zzb(Unknown Source)
                  at com.google.android.gms.internal.zzbqi.zza(Unknown Source)
                  at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
                  at com.firebase.ui.database.FirebaseRecyclerAdapter.parseSnapshot(FirebaseRecyclerAdapter.java:151)
                  at com.firebase.ui.database.FirebaseRecyclerAdapter.getItem(FirebaseRecyclerAdapter.java:140)
                  at com.firebase.ui.database.FirebaseRecyclerAdapter.onBindViewHolder(FirebaseRecyclerAdapter.java:183)
                  at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5825)
                  at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:5858)
                  at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5094)
                  at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4970)
                  at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2029)
                  at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1414)
                  at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1377)
                  at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:578)
                  at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3315)
                  at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3124)
                  at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1549)
                  at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:305)
                  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
                  at android.view.Choreographer.doCallbacks(Choreographer.java:683)
                  at android.view.Choreographer.doFrame(Choreographer.java:616)
                  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6077)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.

My database looks like this: Firebase App Database

Database Snapshot

mDatabaseUsers.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        //now getting the title,desc and image inside the specified field in our
                        //databse
                        newPost.child("title").setValue(title_val);
                        newPost.child("desc").setValue(title_desc);
                        newPost.child("image").setValue(downloadUrl.toString());
                        //for future purpose if we want the app to have a feature of
                        //visiting the user's profile
                        newPost.child("uid").setValue(mCurrentUser.getUid());
                        newPost.child("post_time").setValue(ServerValue.TIMESTAMP);
                        //returns the data from the users database object
                        newPost.child("username").setValue(dataSnapshot.child("name").getValue());
                        newPost.child("userpic").setValue(dataSnapshot.child("image").getValue());

                    }

Please help me with this, as it is very important to me and will make my app look more user friendly.

UPDATE

@Override
public void onStart() {
    super.onStart();

    FirebaseRecyclerAdapter<NewsBlog, BlogViewHolder> firebaseRecyclerAdapter =
            new FirebaseRecyclerAdapter<NewsBlog, BlogViewHolder>(
                    NewsBlog.class,
                    R.layout.blog_row,
                    BlogViewHolder.class,
                    mChildRef) {
                @Override
                protected void populateViewHolder(BlogViewHolder viewHolder, NewsBlog model, int position) {

                    viewHolder.setTitle(model.getTitle());
                    viewHolder.setImage(getContext(),model.getImage());
                    viewHolder.setDesc(model.getDesc());
                    viewHolder.setUsername(model.getUsername());
                    viewHolder.setPost_time(model.getPost_time());
                    viewHolder.setUserpic(getContext(),model.getUserpic());
                }
            };

    mBlogList.setAdapter(firebaseRecyclerAdapter);
}

UPDATE

NewsBlog.java

public class NewsBlog {

String image;
String desc;
String title;
String username;
Long post_time;
String userpic;


public NewsBlog(){

}

public NewsBlog(String image, String desc, String title, String username,
                String userpic, Long post_time) {
    this.image = image;
    this.desc = desc;
    this.title = title;
    this.post_time = post_time;

    this.username = username;
    this.userpic = userpic;

}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public String getDesc() {
    return desc;
}

public void setDesc(String desc) {
    this.desc = desc;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public Long getPost_time() {
    return post_time;
}

public void setPost_time(Long post_time) {
    this.post_time = post_time;
}

public String getUserpic() {
    return userpic;
}

public void setUserpic(String userpic) {
    this.userpic = userpic;
}}

Blog.java

public class Blog extends Fragment {

private RecyclerView mBlogList;

private DatabaseReference mDatabse,mChildRef;

private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;

private DatabaseReference mDatabaseUsers,mChildUsers;

public Blog() {
    // 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_blog, container, false);

    mDatabse = FirebaseDatabase.getInstance().getReference();
    mChildRef = mDatabse.child("Blog");
    mChildRef.keepSynced(true);

    mDatabaseUsers = FirebaseDatabase.getInstance().getReference();
    mChildUsers = mDatabaseUsers.child("Users");
    mChildUsers.keepSynced(true);

    mBlogList = (RecyclerView) view.findViewById(R.id.blog_list);

    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
    linearLayoutManager.setReverseLayout(true);
    linearLayoutManager.setStackFromEnd(true);

    mBlogList.setHasFixedSize(true);
    mBlogList.setLayoutManager(linearLayoutManager);

    return view;
}

@Override
public void onStart() {
    super.onStart();

    FirebaseRecyclerAdapter<NewsBlog, BlogViewHolder> firebaseRecyclerAdapter =
            new FirebaseRecyclerAdapter<NewsBlog, BlogViewHolder>(
                    NewsBlog.class,
                    R.layout.blog_row,
                    BlogViewHolder.class,
                    mChildRef) {
                @Override
                protected void populateViewHolder(BlogViewHolder viewHolder, NewsBlog model, int position) {

                    viewHolder.setTitle(model.getTitle());
                    viewHolder.setImage(getContext(),model.getImage());
                    viewHolder.setDesc(model.getDesc());
                    viewHolder.setUsername(model.getUsername());
                    viewHolder.setPost_time(model.getPost_time());
                    viewHolder.setUserpic(getContext(),model.getUserpic());
                }
            };

    mBlogList.setAdapter(firebaseRecyclerAdapter);
}

public static class BlogViewHolder extends RecyclerView.ViewHolder{

    View mView;

    public BlogViewHolder(View itemView) {
        super(itemView);

        mView = itemView;
    }

    public void setTitle(String title){
        TextView post_title = (TextView) mView.findViewById(R.id.post_title);
        post_title.setText(title);
    }

    public void setImage(Context ctx, String image){
        ImageView post_image = (ImageView) mView.findViewById(R.id.post_image);
        Picasso.with(ctx).load(image).into(post_image);
    }

    public void setDesc(String desc){
        TextView post_desc = (TextView) mView.findViewById(R.id.post_desc);
        post_desc.setText(desc);
    }

    public void setUsername(String username){
        TextView mUsername = (TextView) mView.findViewById(R.id.post_username);
        mUsername.setText(username);
    }

    public void setPost_time(Long post_time){
        TextView time = (TextView) mView.findViewById(R.id.post_time);
        DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        Date date = null;
        try {
            date = dateFormat.parse(post_time.toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        time.setText(dateFormat.format(date));
    }

    public void setUserpic(Context ctx, String userpic){
        ImageView userImage = (ImageView) mView.findViewById(R.id.post_userpic);
        Picasso.with(ctx).load(userpic).into(userImage);
    }
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setHasOptionsMenu(true);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.blog_menu, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    if(id == R.id.blog_items1){
        //for checking whether the user has logged in or not
        mAuth = FirebaseAuth.getInstance();

        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                if(firebaseAuth.getCurrentUser() == null){
                    ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("Login");
                    Login login = new Login();
                    android.support.v4.app.FragmentTransaction fragmentTransaction =
                            getActivity().getSupportFragmentManager().beginTransaction();
                    fragmentTransaction.replace(R.id.fragment_container, login);
                    fragmentTransaction.commit();

                } else {
                    ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("AddBlog");
                    PostActivity postActivity = new PostActivity();
                    android.support.v4.app.FragmentTransaction fragmentTransaction =
                            getActivity().getSupportFragmentManager().beginTransaction();
                    fragmentTransaction.replace(R.id.fragment_container, postActivity);
                    fragmentTransaction.commit();
                }
            }
        };

        mAuth.addAuthStateListener(mAuthListener);

        mAuth.removeAuthStateListener(mAuthListener);

    }else if(id == R.id.logout) {
        //logout action
        mAuth = FirebaseAuth.getInstance();

        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                if(firebaseAuth.getCurrentUser() != null){
                    mAuth.signOut();
                    Toast.makeText(getContext()," Successfully Logged Out!",Toast.LENGTH_SHORT)
                            .show();
                    ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("Login");
                    Login login = new Login();
                    android.support.v4.app.FragmentTransaction fragmentTransaction =
                            getActivity().getSupportFragmentManager().beginTransaction();
                    fragmentTransaction.replace(R.id.fragment_container, login);
                    fragmentTransaction.commit();

                }else{
                    Toast.makeText(getContext(),"Log in first!",Toast.LENGTH_SHORT)
                            .show();
                }
            }
        };
        mAuth.addAuthStateListener(mAuthListener);


        mAuth.removeAuthStateListener(mAuthListener);
    }

    return super.onOptionsItemSelected(item);
}}
Community
  • 1
  • 1
Alok
  • 8,452
  • 13
  • 55
  • 93
  • Can you post your post your Database Snapshot? – Drew Szurko Feb 23 '17 at 20:56
  • I've added the Database Snapshot, have a look at it. I'm hoping to have a positive reply from your side. Thank you! – Alok Feb 23 '17 at 21:05
  • Thanks. I see you setting `post_time` using `newPost.child("post_time").setValue(ServerValue.TIMESTAMP);` to set the time in Firebase, which is working, but where are you retrieving `post_time` for your `setPost_time` method? – Drew Szurko Feb 23 '17 at 21:17
  • I've uploaded the setPost_time() and in there I'm trying to convert that TIMESTAMP into the required format, but I'm getting error again and again causing my app to crash every time when it populates the data from the database in the recyclerview. I'm retrieving the data in my **FireBaseRecyclerAdapter** in other fragment that is in Blog.java which is main activity for showing blog in my recyclerview – Alok Feb 23 '17 at 21:20
  • Added my FirebaseRecyclerViewAdapter in the update section, check this if it can help. – Alok Feb 23 '17 at 21:25
  • Thanks. Last thing, could you post your full NewsBlog POJO and Blog class? Hopefully we can get this solved. – Drew Szurko Feb 23 '17 at 21:29
  • Done. Check this up! – Alok Feb 23 '17 at 21:35
  • Check out my answer and let me know if it works. Thanks! – Drew Szurko Feb 23 '17 at 23:44

2 Answers2

1

try this

public void setPost_time(Long post_time){
        TextView time = (TextView) mView.findViewById(R.id.post_time);
        DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        Date date = null;
        try {
            date = new Date(post_time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        time.setText(dateFormat.format(date));
    }

You can simply create a Date object by passing in the long int

xxfast
  • 697
  • 5
  • 14
  • your code is working fine too, but drew's code made my work go smooth. Thanks alot buddy. However could you tell me how to show the time as facebook like **just now and 3 hrs and it changes with the time spent and becomes Feb 23 automatically** Just want to learn – Alok Feb 24 '17 at 13:46
1

Please let me know if this works.

public void setPost_time(Long post_time){

        TextView time = (TextView) mView.findViewById(R.id.post_time);
        SimpleDateFormat sfd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

        try {
            time.setText(sfd.format(new Date(post_time)));
        } catch (ParseException e) {
            e.printStackTrace();
        }

}
Drew Szurko
  • 1,601
  • 1
  • 16
  • 32
  • It worked for me Drew! That is the beauty of a brilliant mind. Thank you so much. however the try and catch was not at all necessary in the above code in my case. Thanks alot once again. One more thing why am I getting the error could you please explain. I want to learn that. – Alok Feb 24 '17 at 13:41