Search code examples
javaandroidlocalesimpledateformat

ClassCastException thrown when using SimpleDateFormat to format a Date


I am making a Memo android app where each list item shows the date when it was last modified in a TextView by retrieving it form an ArrayList<Long> whose values are converted using new Date(noteDates.get(position)) inside the RecyclerView's Adapter. But when I run the app, it throws java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Long and points to the following code in my Adapter class:

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

Where MainActivity.appLocale points to the current locale which I set using the following code:

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
}

And NoteViewHolder is the Adapter's view holder:

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

Mind ya that all this code was working before adding Date algorithms into account. Is there any solution for this problem? Thanks in advance.


Solution

  • Oh my god I just figured it out! I save my list items in a Json file and I had old date items which weren't longs, but strings instead. I deleted app data and everything worked again!