-1

自从过去几天以来,我一直在到处寻找使用我已经存储在变量中的电话号码来检索联系人姓名的方法,不幸的是,到目前为止我发现的所有内容似乎都在使用已弃用的函数/呼叫。

当然,我尝试过自己的方式,但我觉得我的 Android/JAVA 知识还不足以理解这个概念,当我尝试运行任何东西时,总是会出现一些错误或强制关闭。

到目前为止,我能找到的最好的东西是这样的:

public String getContactName(final String phoneNumber) 
    {  
        Uri uri;
        String[] projection;

        if (Build.VERSION.SDK_INT >= 5)
        {
            uri = Uri.parse("content://com.android.contacts/phone_lookup");
            projection = new String[] { "display_name" };
        }
        else
        { 
            uri = Uri.parse("content://contacts/phones/filter");
            projection = new String[] { "name" }; 
        } 

        uri = Uri.withAppendedPath(uri, Uri.encode(phoneNumber)); 
        Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null); 

        String contactName = "";

        if (cursor.moveToFirst()) 
        { 
            contactName = cursor.getString(0);
        } 

        cursor.close();
        cursor = null;

        return contactName; 
    }

但是通过使用这段代码,Eclipse 告诉我:无法解析上下文。我发现的很多代码和解释都在使用这个Context东西,但是即使在阅读了这个之后我仍然不明白:什么是 Android 上的 'Context'?

任何帮助将不胜感激,非常感谢

4

1 回答 1

0

If you're using this inside an activity, then a context is what you get by using this. So basically here, instead of calling context.getContentResolver(), call this.getContentResolver() or simply just getContentResolver().

Eclipse complains basically because you're trying to call a method of something called context which Eclipse doesn't know because it hasn't been declared anywhere. It would work if you previously did something like Context context = this;, but that's really useless.

getContentResolver() is a method declared and defined by Activity which is a class that your activity extends, therefore you can call it just like that.

I hope it helps. As to what this context really is, I am sorry, but I can't help you with that as I am not even sure I understand it correctly.

Also, please notice, that I haven't checked the code you posted and I don't know if it works for obtaining a contact's name from a phone number. Just wanted to help you with getting rid of the context cannot be resolved error.

于 2013-05-08T18:44:07.153 回答