- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图理解为什么我得到 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/
问题很简单:我正在寻找一种优雅的使用方式 CompletableFuture#exceptionally与 CompletableFuture#supplyAsync 一起.这是行不通的: priva
对于 Web 服务,我们通常使用 maven-jaxb2-plugin 生成 java bean,并在 Spring 中使用 JAXB2 编码。我想知道如何处理 WSDL/XSD 中声明的(SOAP-
这个问题已经有答案了: Array index out of bound behavior (10 个回答) 已关闭 8 年前。 我对下面的 C 代码感到好奇 int main(){
当在类的开头使用上下文和资源初始化 MediaPlayer 对象时,它会抛出 NullPointer 异常,但是当在类的开头声明它时(因此它是 null),然后以相同的方式初始化它在onCreate方
嘿 我尝试将 java 程序连接到 REST API。 使用相同的代码部分,我在 Java 6 中遇到了 Java 异常,并且在 Java 8 中运行良好。 环境相同: 信任 机器 unix 用户 代
我正在尝试使用 Flume 和 Hive 进行 Twitter 分析。为了从 twitter 获取推文,我在 flume.conf 文件中设置了所有必需的参数(consumerKey、consumer
我在 JavaFX 异常方面遇到一些问题。我的项目在我的 Eclipse 中运行,但现在我的 friend 也尝试访问该项目。我们已共享并直接保存到保管箱文件夹中。但他根本无法让它发挥作用。他在控制台
假设我使用 blur() 事件验证了电子邮件 ID,我正在这样做: $('#email').blur(function(){ //make ajax call , check if dupli
我这样做是为了从 C 代码调用非托管函数。 pCallback 是一个函数指针,因此在托管端是一个委托(delegate)。 [DllImport("MyDLL.dll")] public stati
为什么这段代码是正确的: try { } catch(ArrayOutOfBoundsException e) {} 这是错误的: try { } catch(IOException e) {} 这段
我遇到了以下问题:有导出函数的DLL。 代码示例如下:[动态链接库] __declspec(dllexport) int openDevice(int,void**) [应用] 开发者.h: __de
从其他线程,我知道我们不应该在析构函数中抛出异常!但是对于下面的例子,它确实有效。这是否意味着我们只能在一个实例的析构函数中抛出异常?我们应该如何理解这个代码示例! #include using n
为什么需要异常 引出 public static void main(String[
1. Java的异常机制 Throwable类是Java异常类型的顶层父类,一个对象只有是 Throwable 类的(直接或者间接)实例,他才是一个异常对象,才能被异常处理机制识别。JDK中内
我是 Python 的新手,我对某种异常方法的实现有疑问。这是代码(缩写): class OurException(Exception): """User defined Exception"
我已经创建了以下模式来表示用户和一组线程之间的关联,这些线程按他们的最后一条消息排序(用户已经阅读了哪些线程,哪些没有): CREATE TABLE table(user_id bigint, mes
我正在使用 Python 编写一个简单的自动化脚本,它可能会在多个位置引发异常。在他们每个人中,我都想记录一条特定的消息并退出程序。为此,我在捕获异常并处理它(执行特定的日志记录操作等)后引发 Sys
谁能解释一下为什么这会导致错误: let xs = [| "Mary"; "Mungo"; "Midge" |] Array.iter printfn xs 虽然不是这样: Array.iter pr
在我使用 Play! 的网站上,我有一个管理部分。所有 Admin Controller 都有一个 @With 和一个 @Check 注释。 断开连接后,一切正常。连接后,每次加载页面(任何页面,无论
我尝试连接到 azure 表存储并添加一个对象。它在本地主机上工作得很好,但是在我使用的服务器上我得到以下异常及其内部异常: Exception of type 'Microsoft.Wind
我是一名优秀的程序员,十分优秀!