gpt4 book ai didi

java - Android Crashlytics 空指针异常

转载 作者:行者123 更新时间:2023-11-30 10:00:53 25 4
gpt4 key购买 nike

我试图理解为什么我得到 NullPointerException

这是 Crashlytics 报告:

Caused by java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String co.roomapp.klassroom.sdk.model.KRPostEvent.getCoverThumbUrl()' on a null object reference
at co.roomapp.klassroom.activity.KREventFormActivity.initUI + 150(KREventFormActivity.java:150)
at co.roomapp.klassroom.activity.KREventFormActivity.onCreate + 101(KREventFormActivity.java:101)
at android.app.Activity.performCreate + 7458(Activity.java:7458)
at android.app.Activity.performCreate + 7448(Activity.java:7448)
at android.app.Instrumentation.callActivityOnCreate + 1286(Instrumentation.java:1286)
at android.app.ActivityThread.performLaunchActivity + 3409(ActivityThread.java:3409)
at android.app.ActivityThread.handleLaunchActivity + 3614(ActivityThread.java:3614)
at android.app.servertransaction.LaunchActivityItem.execute + 86(LaunchActivityItem.java:86)
at android.app.servertransaction.TransactionExecutor.executeCallbacks + 108(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute + 68(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage + 2199(ActivityThread.java:2199)
at android.os.Handler.dispatchMessage + 112(Handler.java:112)
at android.os.Looper.loop + 216(Looper.java:216)
at android.app.ActivityThread.main + 7625(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run + 524(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main + 987(ZygoteInit.java:987)

有一个java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String co.roomapp.klassroom.sdk.model.KRPostEvent.getCoverThumbUrl()' on a null object reference.

但是你可以在我的类中看到实例是在实例化类时创建的 KRPostEvent event = new KRPostEvent();

任何人都可以告诉我这个变量事件 coule 是如何变为 null 的?这可能是由于生命周期?应该是强引用,不是GC收集的。

public class KREventFormActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {

ImageView btnCamera;
ImageView imgCover;
TextView btnNext;

EditText txtEventTitle;
EditText txtEventLocation;
EditText txtEventStart;
EditText txtEventEnd;

EditText txtEventDescription;
Button btnDelete;

Date startDate;
Date endDate;
boolean editMode = false;
KRPostEvent event = new KRPostEvent();
KRPost post;
KRKlass klass;

final Calendar myCalendar = Calendar.getInstance();

String filename;
Bitmap savedImage;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_form);

initVariables();
initUI();
}

private void initVariables(){

navigationHeaderView = (KRNavigationHeaderView) findViewById(R.id.navigationHeaderView);
editMode = getIntent().getBooleanExtra("editMode",false);

txtEventTitle = (EditText) findViewById(R.id.eventForm_txtEventTitle);
txtEventLocation = (EditText) findViewById(R.id.eventForm_txtEventLocation);
txtEventDescription = (EditText) findViewById(R.id.eventForm_txtEventDescription);
txtEventStart = (EditText) findViewById(R.id.eventForm_txtEventStart);
txtEventEnd = (EditText) findViewById(R.id.eventForm_txtEventEnd);

btnNext = (TextView) findViewById(R.id.eventForm_btnNext);
btnCamera = (ImageView) findViewById(R.id.eventForm_btnCamera);

imgCover = (ImageView) findViewById(R.id.eventForm_imgCover);
btnDelete = findViewById(R.id.btnDelete);

if(getIntent().hasExtra("event")) event = AppUtil.unserializeObject(getIntent().getStringExtra("event"), KRPostEvent.class);

if(getIntent().hasExtra("klassID") && getIntent().hasExtra("postID")){
KRKlass k = KRClient.getInstance().getKlasses().get(getIntent().getStringExtra("klassID"));
post = k.getPosts().get(getIntent().getStringExtra("postID"));
}
}

private void initUI(){

navigationHeaderView.lblTitle.setText((editMode)?R.string.str_title_event_edit:R.string.str_title_event_new);

if(NavigationContoller.getInstance().isRoot(navigationName,this)){
navigationHeaderView.enableCloseButton();
}
navigationHeaderView.setListener(new KRNavigationHeaderViewListener() {
@Override
public void onBack() {
KREventFormActivity.this.onBack();
}
});


if(event.getCoverThumbUrl() != null){
Glide.with(this).load(event.getCoverThumbUrl()).fitCenter().placeholder(R.drawable.classroom).fitCenter().error(R.drawable.classroom).fitCenter().dontAnimate().into(imgCover);

}else{
if(event.getCoverImage() != null){
imgCover.setImageBitmap(event.getCoverImage());
}
}

txtEventTitle.setText(event.getTitle());
txtEventDescription.setText(event.getDescription());
txtEventLocation.setText(event.getLocation());

if(event.getStartDate() != null){
startDate = event.getStartDate();
txtEventStart.setText( DateUtil.convertDateToPrettyString(startDate));
}


if(event.getEndDate() != null){
endDate = event.getEndDate();
txtEventEnd.setText( DateUtil.convertDateToPrettyString(endDate));
}

final TimePickerDialog.OnTimeSetListener startTimePicker = new TimePickerDialog.OnTimeSetListener() {

@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
myCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
myCalendar.set(Calendar.MINUTE, minute);
myCalendar.set(Calendar.SECOND , 0);
myCalendar.set(Calendar.MILLISECOND , 0);
updateTextFieldStartDate();
}
};

final DatePickerDialog.OnDateSetListener startDatePicker = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
new TimePickerDialog(KREventFormActivity.this, startTimePicker, myCalendar
.get(Calendar.HOUR_OF_DAY), myCalendar.get(Calendar.MINUTE),
DateFormat.is24HourFormat(KREventFormActivity.this)).show();
}
};

txtEventStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(startDate != null){
myCalendar.setTime(startDate);
}
new DatePickerDialog(KREventFormActivity.this, startDatePicker, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});

final TimePickerDialog.OnTimeSetListener endTimePicker = new TimePickerDialog.OnTimeSetListener() {

@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
myCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
myCalendar.set(Calendar.MINUTE, minute);
myCalendar.set(Calendar.SECOND , 0);
myCalendar.set(Calendar.MILLISECOND , 0);
updateTextFieldEndDate();
}
};

final DatePickerDialog.OnDateSetListener endDatePicker = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
new TimePickerDialog(KREventFormActivity.this, endTimePicker, myCalendar
.get(Calendar.HOUR_OF_DAY), myCalendar.get(Calendar.MINUTE),
DateFormat.is24HourFormat(KREventFormActivity.this)).show();
}
};

txtEventEnd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(endDate != null){
myCalendar.setTime(endDate);
}
new DatePickerDialog(KREventFormActivity.this, endDatePicker, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});


btnDelete.setVisibility(post != null ? View.VISIBLE : View.GONE);

btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MessageDialog.showAlertMsg(KREventFormActivity.this, KREventFormActivity.this.getString(R.string.str_dialog_title_delete_post), KREventFormActivity.this.getString(R.string.str_dialog_content_delete_post), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
post.delete(new KRApiHandler(){
@Override
public void onSuccess() {
NavigationContoller.getInstance().dismiss(navigationName,KREventFormActivity.this);
}
});
}
}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
}
});
txtEventStart.setInputType(InputType.TYPE_NULL);
txtEventEnd.setInputType(InputType.TYPE_NULL);

txtEventTitle.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {

}

@Override
public void afterTextChanged(Editable s) {
KREventFormActivity.this.checkValid();
}
});

btnNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveEvent();
}
});

btnCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addImage();
}
});

checkValid();
}

private void onBack(){
setResult(RESULT_CANCELED);
NavigationContoller.getInstance().pop(navigationName,this);
overridePendingTransition(R.anim.noanim, R.anim.slide_up_leave);
}

private void checkValid(){
if(txtEventTitle.getText().toString().trim().isEmpty() || startDate == null || endDate == null){
btnNext.setVisibility(View.GONE);
}else{
btnNext.setVisibility(View.VISIBLE);
}
}

private void updateTextFieldStartDate(){
checkValid();
startDate = myCalendar.getTime();
txtEventStart.setText( DateUtil.convertDateToPrettyString(startDate));
checkValid();
}

private void updateTextFieldEndDate(){
checkValid();
endDate = myCalendar.getTime();
txtEventEnd.setText( DateUtil.convertDateToPrettyString(endDate));
checkValid();
}

private void saveEvent(){

event.setTitle(txtEventTitle.getText().toString().trim());
if(txtEventLocation.getText() != null) event.setLocation(txtEventLocation.getText().toString().trim());
if(txtEventDescription.getText() != null) event.setDescription(txtEventDescription.getText().toString().trim());
if(startDate != null) event.setStartDate(startDate);
if(endDate != null) event.setEndDate(endDate);
if(savedImage != null) event.setCoverImage(savedImage);

if(post != null){

MessageDialog.showAlertMsg(this, getString(R.string.app_name), getString(R.string.remind_update_post),R.string.str_label_yes, R.string.str_label_no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
_finish(true);
}
}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
_finish(false);
}
});

}else{
Intent intent = new Intent();
intent.putExtra("event", event);
setResult(RESULT_OK,intent);

NavigationContoller.getInstance().pop(navigationName,this);
}
}

private void _finish(boolean remind){

if(remind){
post.setRemindType(KRPostType.event);
}else{
post.setRemindType(null);
}
post.setEvent(event);
if(post.getEvent() != null && post.getEvent().getCoverImage() != null){
ProgressDlg.showProgressProcess(this,getString(R.string.str_guide_upload_event));
ProgressDlg.pd.setMax(100);
}

btnNext.setEnabled(false);

post.send(null, new KRApiHandler(){

@Override
public void onSuccess() {
ProgressDlg.closeprocess(KREventFormActivity.this);
NavigationContoller.getInstance().pop(navigationName,KREventFormActivity.this);
}

@Override
public void onError(KRException e) {
ProgressDlg.closeprocess(KREventFormActivity.this);
btnNext.setEnabled(true);
MessageDialog.showAlertMsg(KREventFormActivity.this, getString(R.string.str_title_error), e.getMessage());
}

@Override
public void onProgress(final long bytesWritten, final long totalSize) {
KREventFormActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
//ProgressDlg.pd.setMax((int)totalSize);
if(ProgressDlg.pd != null){
int prg = (int)(bytesWritten*1.0/totalSize*100);
ProgressDlg.pd.setProgress(0);
ProgressDlg.pd.setProgress(prg);
}

}
});
}
});
}

private void addImage(){
showTakePhotosDialog();

}

private void showTakePhotosDialog() {
String[] perms = {Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE};
if(EasyPermissions.hasPermissions(this,perms)){
final CharSequence[] items = {this.getString(R.string.str_label_gallery), this.getString(R.string.str_label_camera), this.getString(R.string.str_label_cancel)};
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(this.getString(R.string.str_guide_picture));
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (items[item] == getString(R.string.str_label_gallery)) {
chooseFromGallery();
}
if (items[item] == getString(R.string.str_label_camera)) {
takePhoto();
}
if (items[item] == getString(R.string.str_label_cancel)) {
builder.setCancelable(true);
}
}
});
AlertDialog alert = builder.create();
alert.show();
}else{
EasyPermissions.requestPermissions(this,this.getString(R.string.str_guide_permission_camera),Constants.kPERMISSION_CAMERA_STORAGE,perms);
}
}

private void chooseFromGallery(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
this.startActivityForResult(intent, Constants.kGALLERY);
}

public void takePhoto() {

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
filename = "IMG-" + (new Date()).getTime()+".jpg";
intent.putExtra(MediaStore.EXTRA_OUTPUT, AppUtil.CacheUrifromFilename(this,filename));
this.startActivityForResult(intent, Constants.kCAMERA);
}


//Delegate Photo
public void didFinishTakingPicture(){
Uri selectedImage = AppUtil.CacheUrifromFilename(this,filename);

File source = AppUtil.getFile(KREventFormActivity.this,selectedImage);
File f = AppUtil.moveImageToDir(KREventFormActivity.this, "Klassroom", source, KRUtils.getFlagForKey(Constants.FLAG_KEEP_LOCAL,true));

String n = "TMP-"+f.getName();
CropImage.activity(Uri.fromFile(f)).setGuidelines(CropImageView.Guidelines.ON).setOutputCompressQuality(80).setOutputUri(AppUtil.CacheUrifromFilename(this,n)).start(this);

}

public void didSelectImagesFromGallery(Uri fileuri){
if("content".equalsIgnoreCase(fileuri.getScheme())){
String mimeType = getContentResolver().getType(fileuri);

if(mimeType.contains("image")) {
Cursor returnCursor = getContentResolver().query(fileuri, null, null, null, null);
returnCursor.moveToFirst();
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
String fileName = returnCursor.getString(nameIndex);
try {
InputStream is = this.getContentResolver().openInputStream(fileuri);
byte[] bytesArray = IOUtils.toByteArray(is);
KRFile f1 = new KRFile();
f1.setFileName(fileName);
f1.setMimeType("image");
f1.setData(bytesArray);

File f = f1.toFile();
String n = "TMP-"+f.getName();
CropImage.activity(Uri.fromFile(f)).setGuidelines(CropImageView.Guidelines.ON).setOutputCompressQuality(80).setOutputUri(AppUtil.CacheUrifromFilename(this,n)).start(this);

} catch (Exception e) {

}
}else{
MessageDialog.showAlertMsg(this,getString(R.string.app_name),getString(R.string.str_dialog_content_cantimportfile));
}

}else{
File f = AppUtil.getFile(this,fileuri);

if(f.exists()) {
String[] acceptedmim = {"jpg","jpeg","png"};
boolean c = false;
for(String s:acceptedmim){
if(FilenameUtils.getExtension(f.getPath()).toLowerCase().contains(s)){
c = true;
}
}
if(c) {
String n = "TMP-"+f.getName();
CropImage.activity(Uri.fromFile(f)).setGuidelines(CropImageView.Guidelines.ON).setOutputCompressQuality(80).setOutputUri(AppUtil.CacheUrifromFilename(this,n)).start(this);
}else{
MessageDialog.showAlertMsg(this,getString(R.string.app_name),getString(R.string.str_dialog_content_cantimportfile));
}
}
}
}

public void didEditPhoto(final Uri imageUri)
{

new AsyncTask<Integer, Void, Void>() {
@Override
protected Void doInBackground(Integer... params) {
File f = AppUtil.getFile(KREventFormActivity.this,imageUri);
try {
if(f != null && f.exists()) {
savedImage = Glide.with(KREventFormActivity.this).load(f).asBitmap().fitCenter().into(1280, 1280).get();

filename = null;

KREventFormActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
imgCover.setImageBitmap(savedImage);
}
});
}
} catch (Exception e) {
e.printStackTrace();
}

return null;
}
}.execute();

}


public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
switch (requestCode) {
case Constants.kCAMERA:
didFinishTakingPicture();
break;
case Constants.kGALLERY:
didSelectImagesFromGallery(data.getData());
break;
case CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE:
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
didEditPhoto(result.getUri());
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
break;
default:
break;
}
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(requestCode,permissions,grantResults,this);
}

@Override
public void onPermissionsGranted(int requestCode, List<String> perms) {
if(requestCode == Constants.kPERMISSION_CAMERA_STORAGE){
showTakePhotosDialog();
}
}

@Override
public void onPermissionsDenied(int requestCode, List<String> perms) {

}
}

最佳答案

是的,你把它声明为

KRPostEvent event = new KRPostEvent();

但是这个调用:

if(getIntent().hasExtra("event")) 
event = AppUtil.unserializeObject(getIntent().getStringExtra("event"), KRPostEvent.class);

将为您的 event 变量重新分配一个新值。在你的例子中,一个 null

关于java - Android Crashlytics 空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57798581/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com