Search code examples
javaandroidnumberformatexception

java.lang.NumberFormatException?


I'm new to android programming. I have problem in Chat App. When is send message to any user, user message stores in Firebase Database. But when i try to show all the chats of specific user, it gives me an error.

The problem is java.lang.NumberFormatException: null

Here's my Code where im getting error:

@Override
public void onBindViewHolder(@NonNull MyHolder myHolder, int i) {

    //get data
    String message = chatList.get(i).getMessage();
    String timestamp = chatList.get(i).getTimestamp();

    //convert time stamp to dd/mm/yyyy hr:mm am/pm
    Calendar cal = Calendar.getInstance(Locale.ENGLISH);
    cal.setTimeInMillis(Long.parseLong(timestamp));
    //cal.setTimeInMillis(Long.parseLong(timestamp));
    String dateTime = android.text.format.DateFormat.format("dd/MM/yyyy hh:mm aa", cal).toString();

    //set Data
    myHolder.messageTv.setText(message);
    myHolder.timeTv.setText(dateTime);

    //msg delivered/seen
    if (i == chatList.size()-1){
        if (chatList.get(i).isSeen()){
            myHolder.isSeenTv.setText("Seen");
        }
        else {
            myHolder.isSeenTv.setText("Delivered");
        }
    }
    else {
        myHolder.isSeenTv.setVisibility(View.GONE);
    }

}

enter image description here


Solution

  • Use try-catch block to handle NumberFormatException

    Calendar cal = Calendar.getInstance(Locale.ENGLISH);
    
    try {
        cal.setTimeInMillis(Long.parseLong(timestamp)); 
    } catch(Exception ex) {
        ex.printStackTrace();
    }
    
    String dateTime = android.text.format.DateFormat.format("dd/MM/yyyy hh:mm aa", cal).toString();