我正在使用api来获取数据,当我按下UserProfileActivity的后退按钮并返回ImageViewerActivty时,我遇到了此错误,我已经搜索了StackOverflow,但找不到解决方案,那就太好了如果有人可以指出我的解决方案。
// UserProfileActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
profileImg=(CircularImageView)findViewById(R.id.userImg);
name=(TextView)findViewById(R.id.profileUserName);
location=(TextView)findViewById(R.id.profileLocation);
bio=(TextView)findViewById(R.id.profileBio);
total_photos=(TextView)findViewById(R.id.profilePhotos);
instName=(TextView)findViewById(R.id.profileInsta);
rv=(RecyclerView)findViewById(R.id.profileRv);
gridLayoutManager = new GridLayoutManager(this, 2);
rv.hasFixedSize();
rv.setLayoutManager(gridLayoutManager);
Glide.with(this)
.load(getIntent().getStringExtra("profileImg"))
.centerCrop()
.into(profileImg);
name.setText(getIntent().getStringExtra("user"));
location.setText(getIntent().getStringExtra("location"));
bio.setText(getIntent().getStringExtra("bio"));
instName.setText(getIntent().getStringExtra("instaName"));
username=getIntent().getStringExtra("username");
//RECENT PHOTOS FIRST FETCH
UnsplashService service= ApiClient.getClient().create(UnsplashService.class);
Call<List<PhotoModel>> call=service.getUserProfile(username,API_KEY,1,PAGE_LIMIT);
call.enqueue(new Callback<List<PhotoModel>>() {
@Override
public void onResponse(Call<List<PhotoModel>> call, Response<List<PhotoModel>> response) {
List<PhotoModel> photoModelList=response.body();
adapter = new InfinitePhotoAdapter(UserProfileActivity.this, photoModelList);
adapter.notifyDataSetChanged();
rv.setAdapter(adapter);
}
@Override
public void onFailure(Call<List<PhotoModel>> call, Throwable t) {
}
});
infiniteScrollListener = new InfiniteScrollListener(gridLayoutManager) {
@Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
updatephotos(username,page);
}
};
rv.addOnScrollListener(infiniteScrollListener);
}
// ImageViewer
public class ImageViewerActivity extends AppCompatActivity {
private static final String DIR_NAME ="WallUp Wallpapers";
private static final String LOG_TAG =ImageViewerActivity.class.getSimpleName() ;
private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE =2 ;
ImageView detailImg;
CircularImageView profileImg;
TextView user,location;
Uri imageUri;
DownloadManager downloadManager;
Button downloadBtn,setBtn;
long downloadReference;
Bitmap bmp;
private String filename="Wallpaper.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_viewer);
detailImg=(ImageView)findViewById(R.id.detailImg);
profileImg=(CircularImageView)findViewById(R.id.profileImg);
user=(TextView)findViewById(R.id.user);
downloadBtn=(Button)findViewById(R.id.downloadBtn);
setBtn=(Button)findViewById(R.id.setBtn);
location=(TextView)findViewById(R.id.location);
//Getting User Details from Intent
user.setText(getIntent().getStringExtra("user"));
location.setText(getIntent().getStringExtra("location"));
Glide.with(getApplicationContext())
.load(getIntent().getStringExtra("Image"))
.centerCrop()
.into(detailImg);
Glide.with(getApplicationContext())
.load(getIntent().getStringExtra("profileImage"))
.centerCrop()
.into(profileImg);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setSharedElementEnterTransition(TransitionInflater.from(this).inflateTransition(R.transition.shared_element_transition));
detailImg.setTransitionName("sharedTransition");
}
imageUri=Uri.parse(getIntent().getStringExtra("Image"));
downloadBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DownloadData(imageUri);
}
});
setBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
detailImg.buildDrawingCache();
bmp=detailImg.getDrawingCache();
settingWallpaper(bmp);
}
});
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(downloadReceiver, filter);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant
return;
}
}
profileImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i=new Intent(ImageViewerActivity.this,UserProfileActivity.class);
i.putExtra("username",getIntent().getStringExtra("username"));
i.putExtra("name",getIntent().getStringExtra("user"));
i.putExtra("profileImg",getIntent().getStringExtra("profileImage"));
i.putExtra("bio",getIntent().getStringExtra("bio"));
i.putExtra("instaName",getIntent().getStringExtra("instaName"));
i.putExtra("totalPhotos",getIntent().getExtras().getInt("total_photos"));
i.putExtra("location",getIntent().getStringExtra("location"));
startActivity(i);
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! do the
downloadBtn.setEnabled(true);
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
downloadBtn.setEnabled(false);
}
return;
}
// other 'switch' lines to check for other
// permissions this app might request
}
}
private void settingWallpaper(Bitmap bmp){
WallpaperManager wallManager = WallpaperManager.getInstance(getApplicationContext());
try {
wallManager.setBitmap(bmp);
Toast.makeText(ImageViewerActivity.this, "Wallpaper Set Successfully!!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(ImageViewerActivity.this, "Setting WallPaper Failed!!", Toast.LENGTH_SHORT).show();
}
}
private long DownloadData (Uri uri) {
File direct =
new File(Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
.getAbsolutePath() + "/" + DIR_NAME + "/");
if (!direct.exists()) {
direct.mkdir();
Log.d(LOG_TAG, "dir created for first time");
}
// Create request for android download manager
downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(uri);
//Setting title of request
request.setTitle("Wallpaper");
//Setting description of request
request.setDescription("Wallup Wallpapers")
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES,
File.separator + DIR_NAME + File.separator + filename);
//Enqueue download and save into referenceId
downloadReference = downloadManager.enqueue(request);
return downloadReference;
}
private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//check if the broadcast message is for our enqueued download
long referenceId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (referenceId ==downloadReference ) {
Toast toast = Toast.makeText(ImageViewerActivity.this,
"Image Download Complete", Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 25, 400);
toast.show();
}
}
};
@Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(downloadReceiver, filter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(downloadReceiver);
}
}
//这是错误
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sohail.wallupwallpapers, PID: 2837
java.lang.RuntimeException: Unable to destroy activity {com.sohail.wallupwallpapers/com.sohail.wallupwallpapers.Activities.UserProfileActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:4586)
at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:4609)
at android.app.ActivityThread.-wrap7(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1692)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:750)
at com.pkmmte.view.CircularImageView.refreshBitmapShader(CircularImageView.java:341)
at com.pkmmte.view.CircularImageView.invalidate(CircularImageView.java:262)
at android.widget.ImageView.setImageDrawable(ImageView.java:514)
at com.bumptech.glide.request.target.ImageViewTarget.onLoadCleared(ImageViewTarget.java:70)
at com.bumptech.glide.request.GenericRequest.clear(GenericRequest.java:323)
at com.bumptech.glide.manager.RequestTracker.clearRequests(RequestTracker.java:94)
at com.bumptech.glide.RequestManager.onDestroy(RequestManager.java:221)
at com.bumptech.glide.manager.ActivityFragmentLifecycle.onDestroy(ActivityFragmentLifecycle.java:64)
at com.bumptech.glide.manager.SupportRequestManagerFragment.onDestroy(SupportRequestManagerFragment.java:147)
at android.support.v4.app.Fragment.performDestroy(Fragment.java:2588)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1566)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1759)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1827)
at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3244)
at android.support.v4.app.FragmentManagerImpl.dispatchDestroy(FragmentManager.java:3235)
at android.support.v4.app.FragmentController.dispatchDestroy(FragmentController.java:265)
at android.support.v4.app.FragmentActivity.onDestroy(FragmentActivity.java:390)
at android.support.v7.app.AppCompatActivity.onDestroy(AppCompatActivity.java:209)
at android.app.Activity.performDestroy(Activity.java:7195)
at android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1161)
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:4573)
at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:4609)
at android.app.ActivityThread.-wrap7(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1692)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
答案 0 :(得分:0)
这看起来像是您正在使用的第三方代码中的错误。请从他们的项目中查看此错误,以寻求帮助,如果看起来像您遇到的相同问题,请做出贡献。
https://github.com/Pkmmte/CircularImageView/issues/52
他们建议设置一个占位符图像可以防止此问题。
答案 1 :(得分:0)
只需添加一个占位符。
滑行
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.ic_placeholder);
requestOptions.error(R.drawable.ic_error);
Glide.with(context)
.setDefaultRequestOptions(requestOptions)
.load(url).into(holder.imageView);
对于毕加索
Picasso.with(context)
.load(url)
.placeholder(R.drawable.placeholder)
.into(imageView)
答案 2 :(得分:0)
if (userImageUrl.matches("(?!file\\b)\\w+?:\\/\\/.*")) {
// Not a local file
// image server url
LogClass.e("userImageUrl", "Not a local file");
Glide.with(DrawerActivity.this).load(userImageUrl).into(imgProfile);
} else {
// local path
LogClass.e("userImageUrl", "local file");
File file = new File(userImageUrl);
String filePath = file.getPath();
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
imgProfile.setImageBitmap(bitmap);
}