如何调用从另一个类方法,无需通过上下文? [英] How to call method from another class without passing context?

查看:140
本文介绍了如何调用从另一个类方法,无需通过上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在试图调用从公用事业类中的方法将引用此实用程序的方法创建一个新的光标。不幸的是,我的新类不会让我产生光标没有上下文。我试图通过上下文从调用活动的许多方面,但得到空指针异常在大多数情况下。

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.

下面是我的code中的部分:

Here is the portion of my code:

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

                    }
});

和工具类:

     public static void pickRandomItem() {   

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




}

使用上述code,它抛出的 getContentResolver错误(),和我做了传递方面都失败了所有的尝试。

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

我是相当新的节目为Android,并没有完全理解上下文的概念。任何帮助,您可以提供将大大AP preciated!

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!

推荐答案

创建扩展应用<一类/ A>为您的项目(你必须声明它在清单中太),在应用程序做出

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

在OnCreate(),它把它分配给现场

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

app = this;

和制作

public static MyApplication get()

在里面。当你需要一个背景下,你可以使用

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

MyApplication.get()

这篇关于如何调用从另一个类方法,无需通过上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆