Stephen
Stephen

Reputation: 10059

NullPointerException at ImageCatche

I doesn't know what exactly the error in ImagaeCatche.params.It shows the null pointer exception.I indicate the error number at the end of the line.

StackTrace:

 E/AndroidRuntime(1464): FATAL EXCEPTION: main
 E/AndroidRuntime(1464): Process: com.gems.android, PID: 1464
 E/AndroidRuntime(1464): java.lang.NullPointerException
 E/AndroidRuntime(1464):    at com.sit.fth.util.ImageCache.getDiskCacheDir(ImageCache.java:514)
 E/AndroidRuntime(1464):    at com.sit.fth.util.ImageCache$ImageCacheParams.<init>(ImageCache.java:463)
 E/AndroidRuntime(1464):    at com.sit.fth.frgment.HomeFragment.onCreateView(HomeFragment.java:82)
 E/AndroidRuntime(1464):    at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
 E/AndroidRuntime(1464):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
 E/AndroidRuntime(1464):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
 E/AndroidRuntime(1464):    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
 E/AndroidRuntime(1464):    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
 E/AndroidRuntime(1464):    at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
 E/AndroidRuntime(1464):    at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
 E/AndroidRuntime(1464):    at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
 E/AndroidRuntime(1464):    at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
 E/AndroidRuntime(1464):    at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
 E/AndroidRuntime(1464):    at android.view.View.measure(View.java:16497)
 E/AndroidRuntime(1464):    at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:719)
 E/AndroidRuntime(1464):    at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:455)
 E/AndroidRuntime(1464):    at android.view.View.measure(View.java:16497)
 E/AndroidRuntime(1464):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
 E/AndroidRuntime(1464):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
 E/AndroidRuntime(1464):    at android.view.View.measure(View.java:16497)
 E/AndroidRuntime(1464):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
 E/AndroidRuntime(1464):    at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327)
E/AndroidRuntime(1464):     at android.view.View.measure(View.java:16497)
 E/AndroidRuntime(1464):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
 E/AndroidRuntime(1464):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
 E/AndroidRuntime(1464):    at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
 E/AndroidRuntime(1464):    at android.view.View.measure(View.java:16497)
 E/AndroidRuntime(1464):    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1916)
 E/AndroidRuntime(1464):    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1113)
 E/AndroidRuntime(1464):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1295)
 E/AndroidRuntime(1464):    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
 E/AndroidRuntime(1464):    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
 E/AndroidRuntime(1464):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
 E/AndroidRuntime(1464):    at android.view.Choreographer.doCallbacks(Choreographer.java:574)
: E/AndroidRuntime(1464):   at android.view.Choreographer.doFrame(Choreographer.java:544)
 E/AndroidRuntime(1464):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
 E/AndroidRuntime(1464):    at android.os.Handler.handleCallback(Handler.java:733)
 E/AndroidRuntime(1464):    at android.os.Handler.dispatchMessage(Handler.java:95)
 E/AndroidRuntime(1464):    at android.os.Looper.loop(Looper.java:136)
 E/AndroidRuntime(1464):    at android.app.ActivityThread.main(ActivityThread.java:5017)
 E/AndroidRuntime(1464):    at java.lang.reflect.Method.invokeNative(Native Method)
 E/AndroidRuntime(1464):    at java.lang.reflect.Method.invoke(Method.java:515)
 E/AndroidRuntime(1464):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
 E/AndroidRuntime(1464):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
 E/AndroidRuntime(1464):    at dalvik.system.NativeStart.main(Native Method)

ImageCatche.java:

package com.sit.fth.util;

public class ImageCache {
private static final String TAG = "ImageCache";

// Default memory cache size in kilobytes
private static final int DEFAULT_MEM_CACHE_SIZE = 1024 * 5; // 5MB

// Default disk cache size in bytes
private static final int DEFAULT_DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB

// Compression settings when writing images to disk cache
private static final CompressFormat DEFAULT_COMPRESS_FORMAT = CompressFormat.JPEG;
private static final int DEFAULT_COMPRESS_QUALITY = 70;
private static final int DISK_CACHE_INDEX = 0;

// Constants to easily toggle various caches
private static final boolean DEFAULT_MEM_CACHE_ENABLED = true;
private static final boolean DEFAULT_DISK_CACHE_ENABLED = true;
private static final boolean DEFAULT_INIT_DISK_CACHE_ON_CREATE = false;

private DiskLruCache mDiskLruCache;
private LruCache<String, BitmapDrawable> mMemoryCache;
private ImageCacheParams mCacheParams;
private final Object mDiskCacheLock = new Object();
private boolean mDiskCacheStarting = true;

private HashSet<SoftReference<Bitmap>> mReusableBitmaps;

private ImageCache(ImageCacheParams cacheParams) {
    init(cacheParams);
   }


     public static ImageCache getInstance(
        FragmentManager fragmentManager, ImageCacheParams cacheParams) {

    // Search for, or create an instance of the non-UI RetainFragment
    final RetainFragment mRetainFragment = findOrCreateRetainFragment(fragmentManager);

    // See if we already have an ImageCache stored in RetainFragment
    ImageCache imageCache = (ImageCache) mRetainFragment.getObject();

    // No existing ImageCache, create one and store it in RetainFragment
    if (imageCache == null) {
        imageCache = new ImageCache(cacheParams);
        mRetainFragment.setObject(imageCache);
    }

    return imageCache;
}


public static class ImageCacheParams {

public int memCacheSize = DEFAULT_MEM_CACHE_SIZE;
public int diskCacheSize = DEFAULT_DISK_CACHE_SIZE;
public File diskCacheDir;
public CompressFormat compressFormat = DEFAULT_COMPRESS_FORMAT;
public int compressQuality = DEFAULT_COMPRESS_QUALITY;
public boolean memoryCacheEnabled = DEFAULT_MEM_CACHE_ENABLED;
public boolean diskCacheEnabled = DEFAULT_DISK_CACHE_ENABLED;
public boolean initDiskCacheOnCreate = DEFAULT_INIT_DISK_CACHE_ON_CREATE;


public ImageCacheParams(Context context, String diskCacheDirectoryName) {
    diskCacheDir = getDiskCacheDir(context, diskCacheDirectoryName); <-- 375th Error
}


public void setMemCacheSizePercent(float percent) {
    if (percent < 0.05f || percent > 0.8f) {
        throw new IllegalArgumentException("setMemCacheSizePercent - percent must be "
                + "between 0.05 and 0.8 (inclusive)");
    }
    memCacheSize = Math.round(percent * Runtime.getRuntime().maxMemory() / 1024);
  }
}

  private static boolean canUseForInBitmap(
    Bitmap candidate, BitmapFactory.Options targetOptions) {
  int width = targetOptions.outWidth / targetOptions.inSampleSize;
  int height = targetOptions.outHeight / targetOptions.inSampleSize;

  return candidate.getWidth() == width && candidate.getHeight() == height;
  }


 public static File getDiskCacheDir(Context context, String uniqueName) {
 // Check if media is mounted or storage is built-in, if so, try and use external cache dir
 // otherwise use internal cache dir
   final String cachePath =
        Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
                !isExternalStorageRemovable() ?    getExternalCacheDir(context).getPath() : <---402nd Error 
                        context.getCacheDir().getPath();

return new File(cachePath + File.separator + uniqueName);
}

}

HomeFragment.java:

package com.sit.fth.frgment;

public class HomeFragment extends BaseFragment {

    private View view;
    private ExpandableListView expListView;
    private ArrayList<String> childArrayList;

    List<String> listDataHeader;
    HashMap<String, List<String>> listDataChild = new HashMap<String, List<String>>();

    private int lastExpandedPosition = -1;
    int lastExpandedGroupPosition;
    private int mImageThumbSize;
    private ImageFetcher mImageFetcher;

    private LinearLayout loadingLayout;
    private TextView invisible;
    private List<ImgGallery> imggalleries;
    private LinearLayout listlayout;
    private int collapse = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.home_fragment, null);
        // mTabHost = (TabHost) mRoot.findViewById(android.R.id.tabhost);

        mImageThumbSize = getResources().getDimensionPixelSize(
                R.dimen.image_thumbnail_size);

        ((TextView) view.findViewById(R.id.txt_header)).setText("HOME");

        ImageCacheParams cacheParams = new ImageCacheParams(getActivity(),
                AppConstants.IMAGE_CACHE_DIR);  <---82nd Line Error

        cacheParams.setMemCacheSizePercent(0.25f); // Set memory cache to 25% of
                                                    // app memory

 }

Anybody can help me if you know how to solve these.Thank You.

Upvotes: 1

Views: 822

Answers (4)

Pararth
Pararth

Reputation: 8134

The value of AppConstants.IMAGE_CACHE_DIR and its reference is in the function:

public static File getDiskCacheDir(Context context, String uniqueName) {
 // Check if media is mounted or storage is built-in, if so, try and use external cache dir
 // otherwise use internal cache dir
   final String cachePath =
        Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
                !isExternalStorageRemovable() ?    getExternalCacheDir(context).getPath() : <---402nd Error 
                        context.getCacheDir().getPath();

return new File(cachePath + File.separator + uniqueName);
}  

That varies when using it for emulator, phone. i.e. the accessing of path on the sdCard.

So you need(ed) to check the scenario under what device were you getting that error.

Upvotes: 1

Stephen
Stephen

Reputation: 10059

SD card wasn't properly access in android->sdk->tools.I find these problem in Console.

Then creating a new Avd and accessing the new SD Card.I can solve my problem.

Upvotes: 1

Zoran
Zoran

Reputation: 1494

Did you maybe forget to include:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Edit: It seems that your getExternalCacheDir(context) returns null. Take a look at: http://developer.android.com/reference/android/content/Context.html#getExternalCacheDir%28%29. It says that it returns null "if external storage is not currently mounted so it could not ensure the path exists". You should check if it is null before calling getPath() with it and call instead context.getCacheDir().getPath().

Upvotes: 2

Jay Snayder
Jay Snayder

Reputation: 4338

I would take a look at this one here. I don't deal with Fragments all that frequently, but after backpedaling through your nice error line comments (we thank you for that) I would have to assume that the context is not ready at the point you call getActivity(). So, this would probably need to be called at a different moment in the life-cycle. And this is one problem of a couple that someone started that they had been following up.

NullPointer on getActivity() from Fragment

Perhaps if this does not solve your problem, then a follow-up solution might. Good luck.

Upvotes: 0

Related Questions