0

Im using sliding menu in android and I'm having a lot of trouble to get the context throught the Fragment. The Main Activity:

    slide = new SlidingMenu(this);
    slide.setMode(SlidingMenu.LEFT);
    slide.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
    slide.setFadeDegree(0.35f);
    slide.setBehindOffsetRes(R.dimen.slidingmenu_offset);
    slide.setShadowWidthRes(R.dimen.slidingmenu_shadow_width);
    slide.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
    slide.setMenu(R.layout.left_panel);

    getActionBar().setDisplayHomeAsUpEnabled(true);

    getFragmentManager().beginTransaction().replace(R.id.leftPanel, new LeftPanel()).commit();

I tried using:

Context context;

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    Log.d("Spread",activity.toString());
    context = activity;
}

and

   this.getActivity()

It always return null. Whats the matter here?

EDIT: Use of the Context:

        com.nostra13.universalimageloader.core.ImageLoader imageLoader =  com.nostra13.universalimageloader.core.ImageLoader.getInstance();                           \
   imageLoader.init(ImageLoaderConfiguration.createDefault(context));

    DisplayImageOptions conf = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisc(true).build();
        if (((ParseFile)user.get("profilePicture")).getUrl() != null) imageLoader.displayImage(((ParseFile)user.get("profilePicture")).getUrl(), profPic, conf, new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {                  
            }
            @Override
            public void onLoadingCancelled(String imageUri, View view) {
            }
            @Override
            public void onLoadingFailed(String imageUri, View view,FailReason failReason) {

            }
            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {

            }
        });*/

2 Answers2

0

It will depend on where you are trying to use the context. It is possible that the onAttach() hasn't fired before you actually try and use that context. Therefore, your Context context; ends up being null. It's hard to tell without some additional code, so that is the only assumption that I can make thus far.

Jay Snayder
  • 4,298
  • 4
  • 27
  • 53
  • I edited the question. The onAttach() is called and the activity is not null. but when i use it, it crashes and tell me that context is null. – Rafael Gonçalves Oct 15 '13 at 20:28
0

On your code change: getFragmentManager().beginTransaction().replace(R.id.leftPanel, new LeftPanel(MainActivity.this)).commit();

LeftPanel{

Context  context;

LeftPanel(Context c)
{
        this.context = c;
}

}

You will get the right context in this case, hope this helps

rahstame
  • 2,148
  • 4
  • 23
  • 53