当前位置: 首页 > 知识库问答 >
问题:

以人类可读的形式在FireBaseRecyclerView适配器中填充日期和时间

封锐藻
2023-03-14

我正在开发一个博客应用程序,在那里我创建了card_view,其中显示用户名、个人资料图片、发布时间和其他详细信息。到目前为止,除了一件事时间和日期,一切都很好。这是一件花了很多时间研究的事情,但问题是我的工作没有得到解决。

1.工作到现在的时间和日期

  • 我所做的是节省了TIMESTAMP中的用户发布时间。
  • 现在为了实现我的目标,即以人类可读的形式检索post_time,我已经做了很多关于如何将数据从时间戳格式更改为时间戳格式和年份、小时格式的研究。

我的post_时间在我的POJO中很长,并成功地存储在我的数据库中

在我的博客片段中,我正在检索我的详细信息。

2.博客。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));
        }

我在跟踪了大量有关Stackoverflow的代码后完成了上述代码,但从未得到解决方案。

我的解决方案搜索:

修复日期格式上的nullpointerexception的步骤

Java日期格式的非法参数

火基。时间戳文档

与日期类一起工作

在listview中以人类可读的形式填充日期和时间

为了将时间戳格式转换为人类可读的格式,我又做了一件事,如下所示:

将时间戳格式转换为小时和日期格式

当我在博客中实现上述代码时,我在我的logcat中得到了错误。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:com的本地模块描述符类。谷歌。火基。找不到身份验证。

数据库快照

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());

                    }

请帮助我,因为这对我来说非常重要,会让我的应用程序看起来更加用户友好。

使现代化

@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);
}

使现代化

新闻博客。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);
}}

共有2个答案

杨腾
2023-03-14

试试这个

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));
    }

您只需通过传入long int来创建一个日期对象

袁开宇
2023-03-14

请让我知道这是否有效。

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();
        }

}
 类似资料:
  • 问题内容: 我在用SQL Server填充同一项目的日期和时间时遇到麻烦。以下是三个简单的记录。 我希望我的结果在1行中,并且在Date_Time列中填入一个逗号,然后是逗号。 有人能帮我指出正确的方向/链接或简单的查询来解决问题吗? 谢谢,XH。 问题答案: 如果您使用的是SQL Server 2017或更高版本,则可以使用string_agg如下所示: 如果它在sql server 2017以

  • 我有一块碎片。加载的视图的onCreateView方法上的这个片段有一个ListView(a)(在适配器(a)中填充)。但是,此ListView(A)中有另一个ListView(B)。所以现在,我必须调用适配器(B)来填充这个listview(B)。如果我从片段调用它,我会得到一个空指针,如果我从适配器调用它(a),它不会崩溃,但不会工作。 如何调用另一个适配器中的适配器。 这是片段的代码: 其中

  • 问题内容: 有没有一种打印Python日期时间的格式,该格式不会在日期和时间上使用零填充? 我现在使用的格式: 结果: 2012年2月29日下午5:03 所需 : 2012年2月29日下午5:03 什么格式将月份表示为“ 2”而不是“ 02”,将时间表示为“ 5:03 PM”而不是“ 05:03 PM” 问题答案: 可用的格式化选项将全部为零填充。您当然可以滚动使用自己的格式化功能,但是在这种情况

  • 我无法填充Firebase回收适配器。我最终想做的是,用户搜索一个名称,数据库中的结果将填充回收人员视图。 数据库结构如下所示: 要填充的代码如下所示,全部位于: 现在我只想让它填充数据库中的所有用户,但似乎什么都没有填充。 是一个。 这是UsersViewHolder类:公共静态类UsersViewHolder扩展了RecyclerView。视图持有者{View mView;TextView m

  • 问题内容: 我要特别问的是,是否有人知道默认转换格式在哪里指定,是由JDBC规范在某处定义的,还是由单独的JDBC驱动程序决定的。如果是后者,那么另一个问题是Oracle 10g JDBC如何做到这一点? **添加了1月15日: 抱歉,我认为问题已经很清楚了,但显然不是。我不是想从数据库中检索日期值,也不需要关于执行该操作的方法的建议。 我不认为这是所引用问题的重复,这就是为什么我在这里提出一个单

  • 我在应用程序yml中启用了以下功能 实体类字段如下所示 在设置日期时,我正在使用 我如何实现这个Spring JPA和Java8类? 谢谢