Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

android - How to call method from another class without passing context?

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...