使用SimpleDateFormat格式化日期时引发的ClassCastException

时间:2019-07-18 18:20:20

标签: java android locale simpledateformat

我正在制作一个Memo android应用,其中每个列表项都通过在class MyWidget(Widget): def __init__(self, **kwargs): super(MyWidget, self).__init__(**kwargs) with self.canvas: self.rect = Rectangle(pos=self.pos, size=self.size) self.bind(pos=self.update_rect, size=self.update_rect) def update_rect(self, *args): self.rect.pos = self.pos self.rect.size = self.size class Page(Screen): ... def add(self): ... self.list2[len(self.list1) - 1] = MyWidget(size_hint=(.1, .1), pos=(randint(100, 200), randint(250, 500))) self.add_widget(self.list2[len(self.list1) - 1]) 中检索其最后一次在TextView中修改的日期来显示,该ArrayList<Long>的值在RecyclerView的适配器内使用new Date(noteDates.get(position))进行了转换。但是,当我运行该应用程序时,它将引发java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Long并指向我的Adapter类中的以下代码:

@Override
public void onBindViewHolder(@NonNull NoteViewHolder holder, int position) {
    if (position == noteContents.size()) {
        //working code
    } else {
        holder.title.setText(noteTitles.get(position));
        holder.content.setText(noteContents.get(position));
        holder.date.setText(new SimpleDateFormat("yyyy/MM/DD", MainActivity.appLocale).format(new Date(noteDates.get(position)))); //here is the problem.
        holder.picture.setVisibility(View.GONE);
    }
}

MainActivity.appLocale指向我使用以下代码设置的当前语言环境:

public class MainActivity extends AppCompatActivity {
    //other codes
    public static Locale appLocale;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //other codes
        Configuration conf = getResources().getConfiguration();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) appLocale = conf.getLocales().get(0);
        else appLocale = conf.locale;
        //other codes
    }
    //other codes
}

并且NoteViewHolder是适配器的视图持有者:

public static class NoteViewHolder extends RecyclerView.ViewHolder {

    MaterialCardView noteCard;
    TextView title;
    TextView content;
    TextView date;
    ImageView picture;

    NoteViewHolder(View itemView) {
        super(itemView);
        noteCard = (MaterialCardView) itemView.findViewById(R.id.noteCard);
        title = (TextView) itemView.findViewById(R.id.dialogTitle);
        content = (TextView) itemView.findViewById(R.id.content);
        date = (TextView) itemView.findViewById(R.id.date);
        picture = (ImageView) itemView.findViewById(R.id.picture);
    }
}

请注意,在将Date算法添加到帐户中之前,所有这些代码都在工作。 这个问题有什么解决办法吗?预先感谢。

2 个答案:

答案 0 :(得分:1)

我的天哪,我刚刚想通了!我将列表项保存在Json文件中,并且有一些旧的日期项,它们不是long型的,而是字符串。我删除了应用数据,一切再次正常!

答案 1 :(得分:0)

holder.date.setText(new SimpleDateFormat("yyyy/MM/DD", MainActivity.appLocale).format(new Date(noteDates.get(position)))); //here is the problem.

在此行下

noteDates.get(position) -> Return String is issue

返回字符串值

但是应该很长。

例如new Date(7393265965);