3

I am currently trying to call a method from a utility class that will reference a new cursor created for this utility method. Unfortunately, my new class will not let me create the cursor without context. I have tried numerous ways of passing context from the calling activity, but get null pointer exceptions in most cases.

Here is the portion of my code:

findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                        Tools.pickRandomItem();

                    }
});

and in the Tools Class:

     public static void pickRandomItem() {   

    Cursor cur = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, 
               null, null,MediaColumns.TITLE + " ASC");




}

Using the above code it throws an error on getContentResolver(), and all attempts I've made to pass context have failed.

I am fairly new to programming for Android, and don't fully understand the concept of contexts. Any help you could provide would be greatly appreciated!

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Josh
  • 2,685
  • 6
  • 33
  • 47
  • Even though this question is older, better discussion and clearer answers are happening on this duplicate question: http://stackoverflow.com/questions/7666589/using-getresources-in-non-activity-class – tir38 May 02 '16 at 19:31

2 Answers2

7

Create a class that extends Application for your project (you have to declare it in the Manifest too), in the Application make a

private static MyApplication app

in the onCreate() of it assign it to the field

app = this;

and make a

public static MyApplication get()

in it. When you need a Context you can use a

MyApplication.get()
apps
  • 942
  • 5
  • 8
2

A few hints on Context:

  1. Get Context in you View via getContext() and pass it to getContentResolver(context).

  2. Use application-context approach as described here by @apps.

  3. Don't store context inside Activity or Views. This leads to memory leaks.

Peter Knego
  • 79,991
  • 11
  • 123
  • 154
  • Thank you for the advice. Through your advice and more reading I have learned how critical context handling is to memory management. – Josh Nov 15 '10 at 02:09