致命异常:AsyncTask#1尝试在空对象引用上调用虚拟方法'long java.util.Date.getTime()'

时间:2019-01-21 19:45:05

标签: java android

每次尝试插入数据库时​​,我总是会遇到此致命异常:AsyncTask#1错误。当我开始使用@Typeconverter将日期转换为插入之前很久时,它就开始了。

在转换为日期对象之前,我尝试解析很长时间。

我的错误:

E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: detailor.stylus.org.detailor, PID: 11340
java.lang.RuntimeException: An error occured while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:304)
    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()' on a null object reference
    at detailor.stylus.org.detailor.DateTypeCoverter.convertDateToLong(DateTypeCoverter.java:11)
    at detailor.stylus.org.detailor.JobsDao_Impl$1.bind(JobsDao_Impl.java:210)
    at detailor.stylus.org.detailor.JobsDao_Impl$1.bind(JobsDao_Impl.java:36)
    at androidx.room.EntityInsertionAdapter.insert(EntityInsertionAdapter.java:63)
    at detailor.stylus.org.detailor.JobsDao_Impl.insert(JobsDao_Impl.java:438)
    at detailor.stylus.org.detailor.DetailorRepository$InsertJobsAsyncTask.doInBackground(DetailorRepository.java:122)
    at detailor.stylus.org.detailor.DetailorRepository$InsertJobsAsyncTask.doInBackground(DetailorRepository.java:113)
    at android.os.AsyncTask$2.call(AsyncTask.java:292)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
    at java.lang.Thread.run(Thread.java:818) 

片段类:

public class MeasurementPreviewFragment extends Fragment {
private TextView displayDate;
private View view;
private EditText editText, editText1, editText2, editText3, editText4, editText5, editText6, editText7, editText8,
        editText9, editText10, editText11, editText12, editText13, editText14, editText15, editText16;
private LinearLayout linearLayout, linearLayout2;
private Button finish;
private Date dateToStr;
private DetailorViewModel detailorViewModel;

private ImageView sampleImage;
private Button samplePick;
static final int REQUEST_CODE_GALLERY = 999;
private Bitmap bitmap;
private DatePickerDialog.OnDateSetListener dateSetListener;
private Date deadline;


public MeasurementPreviewFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    view = inflater.inflate(R.layout.fragment_measurement_preview, container, false);
    finish = view.findViewById(R.id.finish); finish.setTypeface(MainActivity.typeface);
    linearLayout = view.findViewById(R.id.layout);
    linearLayout2 = view.findViewById(R.id.layout2);

    samplePick = view.findViewById(R.id.pickSample);
    sampleImage = view.findViewById(R.id.sampleDisplay);
    samplePick.setOnClickListener(v -> requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_GALLERY));

    detailorViewModel = ViewModelProviders.of(this).get(DetailorViewModel.class);

    Date today = new Date();
    dateToStr = (today);

    editText = view.findViewById(R.id.eneck); editText.setTypeface(MainActivity.typeface);
    editText1 = view.findViewById(R.id.echest); editText1.setTypeface(MainActivity.typeface);
    editText2 = view.findViewById(R.id.eshirtlength); editText2.setTypeface(MainActivity.typeface);
    editText3 = view.findViewById(R.id.eshoulderwidth); editText3.setTypeface(MainActivity.typeface);
    editText4 = view.findViewById(R.id.earmlength); editText4.setTypeface(MainActivity.typeface);
    editText5 = view.findViewById(R.id.ewrist); editText5.setTypeface(MainActivity.typeface);
    editText6 = view.findViewById(R.id.einseam); editText6.setTypeface(MainActivity.typeface);
    editText7 = view.findViewById(R.id.esleevelength); editText7.setTypeface(MainActivity.typeface);
    editText8 = view.findViewById(R.id.ebicep); editText8.setTypeface(MainActivity.typeface);
    editText9 = view.findViewById(R.id.ehip); editText9.setTypeface(MainActivity.typeface);
    editText10 = view.findViewById(R.id.ewaist); editText10.setTypeface(MainActivity.typeface);
    editText11 = view.findViewById(R.id.etrouseroutseam); editText11.setTypeface(MainActivity.typeface);
    editText12 = view.findViewById(R.id.etrouserinseam); editText12.setTypeface(MainActivity.typeface);
    editText13 = view.findViewById(R.id.ecrotch); editText13.setTypeface(MainActivity.typeface);
    editText14 = view.findViewById(R.id. ethigh); editText14.setTypeface(MainActivity.typeface);
    editText15 = view.findViewById(R.id.eknee); editText15.setTypeface(MainActivity.typeface);
    editText16 = view.findViewById(R.id.eseat); editText16.setTypeface(MainActivity.typeface);

    displayDate = view.findViewById(R.id.editText1);
    displayDate.setOnClickListener(v -> {
        Calendar calendar =  Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog dialog = new DatePickerDialog(getActivity(),
                android.R.style.Theme_Holo_Light_Dialog,
                dateSetListener,
                year,month,day);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();

    });

    dateSetListener = (v, year, month, dayOfMonth) -> {
        month = month +1;
        String date = dayOfMonth + "/" + month + "/" + year;
        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
        try {
            deadline = format.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        displayDate.setText(deadline.toString()); displayDate.setTypeface(MainActivity.typeface);
    };

    sortOut();
    finish.setOnClickListener(v -> finish());
    return view;
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int grantResult[]){
    if (requestCode == REQUEST_CODE_GALLERY){
        if (grantResult.length > 0 && grantResult[0]==PackageManager.PERMISSION_GRANTED){
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent, REQUEST_CODE_GALLERY);
        } else {
            Toast.makeText(getActivity(), "You have no permission", Toast.LENGTH_SHORT).show();
        }
        return;
    }
    super.onRequestPermissionsResult(requestCode, permissions, grantResult);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
    if (requestCode == REQUEST_CODE_GALLERY && data != null){
        Uri uri = data.getData();
        try {
            Context context = MainActivity.getContextofApplication();
            InputStream stream = context.getContentResolver().openInputStream(uri);

            bitmap = BitmapFactory.decodeStream(stream);
            sampleImage.setImageBitmap(bitmap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    //super.onActivityResult(requestCode, resultCode, data);
}

private void sortOut(){

    if (NewJobFragment.maleclothtype.equalsIgnoreCase("shirt")){
        editText.setText(NewJobFragment.neck);
        editText1.setText(NewJobFragment.chest);
        editText2.setText(NewJobFragment.shirtlength);
        editText3.setText(NewJobFragment.shoulderwidth);
        editText4.setText(NewJobFragment.armlength);
        editText5.setText(NewJobFragment.wrist);
        editText6.setText(NewJobFragment.inseam);
        editText7.setText(NewJobFragment.sleevelength);
        editText8.setText(NewJobFragment.bicep);
        linearLayout2.setVisibility(View.GONE);
    }
    if (NewJobFragment.maleclothtype.equalsIgnoreCase("trouser")){
        editText9.setText(NewJobFragment.hip);
        editText10.setText(NewJobFragment.waist);
        editText11.setText(NewJobFragment.trouserout);
        editText12.setText(NewJobFragment.trouserin);
        editText13.setText(NewJobFragment.crotch);
        editText14.setText(NewJobFragment.thigh);
        editText15.setText(NewJobFragment.knee);
        editText16.setText(NewJobFragment.seat);
        linearLayout.setVisibility(View.GONE);
    }
    else {
        editText.setText(NewJobFragment.neck);
        editText1.setText(NewJobFragment.chest);
        editText2.setText(NewJobFragment.shirtlength);
        editText3.setText(NewJobFragment.shoulderwidth);
        editText4.setText(NewJobFragment.armlength);
        editText5.setText(NewJobFragment.wrist);
        editText6.setText(NewJobFragment.inseam);
        editText7.setText(NewJobFragment.sleevelength);
        editText8.setText(NewJobFragment.bicep);
        editText9.setText(NewJobFragment.hip);
        editText10.setText(NewJobFragment.waist);
        editText11.setText(NewJobFragment.trouserout);
        editText12.setText(NewJobFragment.trouserin);
        editText13.setText(NewJobFragment.crotch);
        editText14.setText(NewJobFragment.thigh);
        editText15.setText(NewJobFragment.knee);
        editText16.setText(NewJobFragment.seat);
    }
}

    private byte[] imageViewToByte(ImageView image){
    if (bitmap==null){
        return null;
    }
        Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
        byte[] byteArray = outputStream.toByteArray();
        return byteArray;

}

    private void finish(){

    String name = NewJobFragment.name;
    String phone = NewJobFragment.mobile;
    String address = NewJobFragment.address;
    String gender = NewJobFragment.gender;
    String status = "ongoing";
    Date started = dateToStr;
    String clothtype =NewJobFragment.maleclothtype;

    String neck = editText.getText().toString();
    String chest = editText1.getText().toString();
    String shirtlength = editText2.getText().toString();
    String shoulderwidth = editText3.getText().toString();
    String armlength = editText4.getText().toString();
    String wrist = editText5.getText().toString();
    String inseam = editText6.getText().toString();
    String sleevelength = editText7.getText().toString();
    String bicep = editText8.getText().toString();
    String hip = editText9.getText().toString();
    String waist = editText10.getText().toString();
    String trouserout = editText11.getText().toString();
    String trouserin = editText12.getText().toString();
    String crotch = editText13.getText().toString();
    String thigh = editText14.getText().toString();
    String knee = editText15.getText().toString();
    String seat = editText16.getText().toString();

    /*if (deadline==null){
        Toast.makeText(getActivity(), "Please specify Job's deadline", Toast.LENGTH_LONG).show();
        return;
    }*/

        DetailorJobs jobs = new DetailorJobs(name, phone, address, gender, neck, chest, waist,
                seat, shirtlength, shoulderwidth, armlength, wrist, hip, inseam, sleevelength,
                trouserout, trouserin, crotch, thigh, knee, null, bicep, null, null,
                null, null, null, null, null,
                status, started, deadline, null, clothtype, imageViewToByte(sampleImage));
        detailorViewModel.insert(jobs);
        Toast.makeText(getActivity(), "New job started: "+dateToStr.toString(), Toast.LENGTH_SHORT).show();
        redirect();
}

private void redirect(){
    Intent intent = new Intent(getActivity(), MainActivity.class);
    startActivity(intent);
    getFragmentManager().popBackStack();
}

}

MyDAO:

@Dao
public interface JobsDao {
@Insert
void insert(DetailorJobs jobs);

@Update
void update(DetailorJobs jobs);

}

我的DateTypeConverter:

public class DateTypeCoverter {

@TypeConverter
public Long convertDateToLong(Date date){
    return date.getTime();
}

@TypeConverter
public Date convertLongToDate(long time){
    return new Date(time);
}

}

我的实体类:

@Entity(tableName = "Jobs")
public class DetailorJobs {

@PrimaryKey(autoGenerate = true)
private int _id;

private String name;
private String phonenumber;
private String address;
private String gender;
private String neck;
private String chest;
private String waist;
private String seat;
private String shirtlength;
private String shoulderwidth;
private String armlength;
private String wrist;
private String hip;
private String inseam;
private String sleevelength;
private String trouseroutseam;
private String trousetinseam;
private String crotch;
private String thigh;
private String knee;
private String fullchest;
private String bicep;
private String bust;
private String bra;
private String armholedepth;
private String neckdepth;
private String trouserbottomround;
private String slitcut;
private String busttobust;
private String status;
private Date started;
private Date deadline;
private Date ended;
private String clothtype;

@ColumnInfo(typeAffinity = ColumnInfo.BLOB)
private byte[] sample;

public DetailorJobs(String name, String phonenumber, String address, String gender, String neck,
                    String chest, String waist, String seat, String shirtlength, String shoulderwidth,
                    String armlength, String wrist, String hip, String inseam, String sleevelength,
                    String trouseroutseam, String trousetinseam, String crotch, String thigh, String knee,
                    String fullchest, String bicep, String bust, String bra, String armholedepth, String neckdepth,
                    String trouserbottomround, String slitcut, String busttobust, String status,
                    Date started, Date deadline, Date ended, String clothtype, byte[] sample) {
    this.name = name;
    this.phonenumber = phonenumber;
    this.address = address;
    this.gender = gender;
    this.neck = neck;
    this.chest = chest;
    this.waist = waist;
    this.seat = seat;
    this.shirtlength = shirtlength;
    this.shoulderwidth = shoulderwidth;
    this.armlength = armlength;
    this.wrist = wrist;
    this.hip = hip;
    this.inseam = inseam;
    this.sleevelength = sleevelength;
    this.trouseroutseam = trouseroutseam;
    this.trousetinseam = trousetinseam;
    this.crotch = crotch;
    this.thigh = thigh;
    this.knee = knee;
    this.fullchest = fullchest;
    this.bicep = bicep;
    this.bust = bust;
    this.bra = bra;
    this.armholedepth = armholedepth;
    this.neckdepth = neckdepth;
    this.trouserbottomround = trouserbottomround;
    this.slitcut = slitcut;
    this.busttobust = busttobust;
    this.status = status;
    this.started = started;
    this.deadline = deadline;
    this.ended = ended;
    this.clothtype = clothtype;
    this.sample = sample;
}

}

我的存储库类:

public class DetailorRepository {

private JobsDao jobsDao;

public DetailorRepository(Context context){
    DetailorDatabase database = DetailorDatabase.getInstances(context);
    jobsDao = database.jobsDao();
}

public void insert(DetailorJobs jobs) {
    new InsertJobsAsyncTask(jobsDao).execute(jobs);
}

public void update(DetailorJobs jobs){
    new UpdateJobsAsyncTask(jobsDao).execute(jobs);
}


private static class InsertJobsAsyncTask extends AsyncTask<DetailorJobs, Void, Void>{
    private JobsDao jobsDao;

    private InsertJobsAsyncTask(JobsDao jobsDao){
        this.jobsDao = jobsDao;
    }

    @Override
    protected Void doInBackground(DetailorJobs... detailorJobs) {
        jobsDao.insert(detailorJobs[0]);
        return null;
    }
}

private static class UpdateJobsAsyncTask extends AsyncTask<DetailorJobs, Void, Void>{
    private JobsDao jobsDao;

    private UpdateJobsAsyncTask(JobsDao jobsDao){
        this.jobsDao = jobsDao;
    }

    @Override
    protected Void doInBackground(DetailorJobs... detailorJobs) {
        jobsDao.update(detailorJobs[0]);
        return null;
    }
}

}

我的数据库:

@Database(entities = {DetailorJobs.class}, version = 3)
@TypeConverters({DateTypeCoverter.class})
public abstract class DetailorDatabase extends RoomDatabase {

private static DetailorDatabase instances;

public abstract JobsDao jobsDao();

public static synchronized DetailorDatabase getInstances(Context context){
    if (instances == null){
        instances = Room.databaseBuilder(context.getApplicationContext(),
                DetailorDatabase.class, "DetailorDB")
                .fallbackToDestructiveMigration()
                .addCallback(roomCallback)
                .build();
    }
    return instances;
}

private static RoomDatabase.Callback roomCallback = new RoomDatabase.Callback(){
    @Override
    public void onCreate(@NonNull SupportSQLiteDatabase db) {
        super.onCreate(db);
    }
};

}

1 个答案:

答案 0 :(得分:0)

看起来您正在使用以下构造函数参数创建DetailerJob

.... null, clothtype, imageViewToByte(sampleImage));

null末尾的第三位是您的ended对象参数。

您的“房间”日期转换器不希望该列为空

public class DateTypeCoverter {

  @TypeConverter
  public Long convertDateToLong(Date date){
    return date.getTime(); //<-- provoking your NPE
    //recommend
    //return date == null ? null : date.getTime()
  }

  @TypeConverter
  public Date convertLongToDate(long time){//<-- change long to Long
    return new Date(time);
    //recommend
    //return time == null? null : new Date(time)
  }
} 

建议将null传递到该列或其他表示该列没有日期的数据

convertLongToDate也必须牢记这一点,例如使用Long代替long,以便它可以为空

我在上面的代码中提出了建议