Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import android.content.Context;

import android.database.Cursor;

import android.net.Uri;
import android.provider.ContactsContract;

public class Main {
    /**
     * Looks up contact name in the address book by the phone number.
     * 
     * @param context the Android context.
     * @param phone the phone number to look up.
     * @return a contact name.
     */
    public static String lookupNameByPhone(Context context, String phone) {
        Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
        String[] projection = new String[] { ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.Contacts._ID };
        Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);

        try {
            while (cursor.moveToNext()) {
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

                if (name != null && name.length() > 0) {
                    return name;
                }
            }
        } finally {
            cursor.close();
        }

        return phone;
    }
}