0

I need a class to get the artists, albums and tracks on the device, which I will then use JNI to call upon.

At the moment, in its barebones, the following causes a crash.

public class AndroidMediaLibray extends Activity {
    public void getArtists() {
        getContentResolver();
    }
}

How do I get this to not crash?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Jacob
  • 1,335
  • 1
  • 14
  • 28
  • You should post the logcat. Or at least tell us what exception you get. – MalaKa Aug 17 '13 at 14:51
  • 08-17 14:44:58.754 11871-11871/? E/AndroidRuntime: FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.NullPointerException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2308) Not sure if that helps. Not used to Java at all. – Jacob Aug 17 '13 at 14:54
  • This looks like you are trying to call the `getArtist()` from the `onCreate` of the `MainActivity`. Am I right? – MalaKa Aug 17 '13 at 15:04
  • You are correct. I'm guessing this is bad. :P Where should it be? – Jacob Aug 17 '13 at 15:39

1 Answers1

0

The problem you have, is that you need to call getContentResolver() on a Context. If you call it in an Activity, you automatically call it on the Context of the Activity. But you (probably) never really start AndroidMediaLibrary. Please refer to the documentation of activities. If you want to have the DB call in an extra class, you may have a look at the following code. I have created a class with static methods. I just need to pass the context of my given Activity to that class. In your case that class might look like this:

public class AndroidMediaLibrary {

    public static List<String> getArtists(Context context){

        ArrayList<String> retVal = new ArrayList<String>();

        ContentResolver resolver = context.getContentResolver();        

        // some more stuff here.. 

        return retVal;
    }
}

You may call that function from your MainActivity with:

List<String> myValues = DBUtils.someFunction(MainActivity.this);
MalaKa
  • 3,734
  • 2
  • 18
  • 31
  • Thanks. That did the trick. I didn't use the static implementation, but not sure if that matters. Thanks a lot for the help! – Jacob Aug 17 '13 at 17:33
  • It works without a static implementation, too. The problem was, that you were trying to access to `Context` of the `AndroidMediaLibrary` activity that was not available. I think some more basic understanding by reading the documentation would help a lot. – MalaKa Aug 17 '13 at 17:44
  • It might help. I plan on using Qt, and as little Java as possible. I only intend to use it if I need to implement platform specific features. – Jacob Aug 17 '13 at 18:05