Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import android.content.Context;

import android.database.Cursor;

import android.net.Uri;

import android.provider.ContactsContract.Contacts;

import android.telephony.PhoneNumberUtils;

public class Main {
    /**
     * Looks up a contacts display name by contact id - if not found, the
     * address (phone number) will be formatted and returned instead.
     */
    public static String getPersonName(Context context, String id, String address) {

        // Check for id, if null return the formatting phone number as the name
        if (id == null || "".equals(id.trim())) {
            if (address != null && !"".equals(address.trim())) {
                return PhoneNumberUtils.formatNumber(address);
            } else {
                return null;
            }
        }

        Cursor cursor = context.getContentResolver().query(Uri.withAppendedPath(Contacts.CONTENT_URI, id),
                new String[] { Contacts.DISPLAY_NAME }, null, null, null);

        if (cursor != null) {
            try {
                if (cursor.getCount() > 0) {
                    cursor.moveToFirst();
                    String name = cursor.getString(0);
                    return name;
                }
            } finally {
                cursor.close();
            }
        }

        if (address != null) {
            return PhoneNumberUtils.formatNumber(address);
        }

        return null;
    }
}