Looking for a way to search for contacts by number in Nativescript? Learn how to use the `getContactsByNumber(number

Using the nativescript-contacts plugin with nativescript 5.0, Angular, and webpack.

Is there a way to retrieve the contact name based on the phone number?

The main issue is that I want to display a list of recent phone calls, but there is one problem.

Let me give you an example: 1. A call from an unknown number is received at 9:00 am. This displays the contact name as "unknown" with the caller's number in the list.

  1. After ending this call at 9:10 am, the number is added to contacts.

  2. At 10:00 am, a call from the same number is received.

  3. Now, when I view the call log list in my Android App, I see two calls like this ->

10:00 am Jim Corbet 999988887777 9:00 am unknown 999988887777

Instead, I would like to display distinct phone log entries with the contact name if it is saved. === Or I will try querying the nativescript-contacts plugin to retrieve the contact name using the number (since this feature is not currently available).

I have attempted using Set() without success. I am struggling with implementing GROUP BY in my queries due to limited understanding.

Just to clarify, there are no errors in the program.

Here is the code related to the call logs:

var utilsModule = require("tns-core-modules/utils/utils");
public CallLog = android.provider.CallLog;
public Log = android.util.Log;
public Uri = android.net.Uri;
var callUri = this.Uri.parse("content://call_log/calls");
var strOrder = android.provider.CallLog.Calls.DATE + " DESC";
var context = utilsModule.ad.getApplicationContext();
var cr=context.getContentResolver();
var curCallLogs = cr.query(callUri, null, null, null, strOrder);
//I only need the latest 30 calls
for(var i=0;i<30;i++){
    curCallLogs.moveToNext();
    var strName=curCallLogs.getString(curCallLogs.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME));
    callobject.callerNumber=curCallLogs.getString(curCallLogs.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
}

Answer №1

If you need to extract a name using a phone number, there is a way to do it natively. Below is a basic example showing how to convert Java code to TypeScript. To access native APIs in TypeScript, tns-platform-declarations are used, and user permissions are granted with nativescript-permissions to read and access contacts.

let phoneNumber = "0888111111";
let lookupUri = android.net.Uri.withAppendedPath(android.provider.ContactsContract.PhoneLookup.CONTENT_FILTER_URI, android.net.Uri.encode(phoneNumber));
let contentResolver = application.android.context.getContentResolver();
let contactLookup = contentResolver.query(lookupUri, [android.provider.BaseColumns._ID,
    android.provider.ContactsContract.ContactsColumns.DISPLAY_NAME ], null, null, null);

if (contactLookup != null && contactLookup.getCount() > 0) {

    contactLookup.moveToNext();
    let name = contactLookup.getString(contactLookup.getColumnIndex(android.provider.ContactsContract.ContactsColumns.DISPLAY_NAME));
    console.log(`Found name  ${name} for number ${phoneNumber}`);
} else {
    console.log("No such number in the contacts")
}

It's important to parse the number carefully as the format may vary. For instance, if the contact is saved with the country code + local operator number, searching for just the local number may not yield results (e.g. 359 888111111 will not match 0888111111).

To see a complete demo project implementing the above, visit here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Karma struggles to identify angular directives

Our project structure is based on the Angular2-webpack-starter. The project compiles, builds, and displays in the browser without any issues. However, we encounter an error when attempting to run test cases using karma and jasmine. FAILED TESTS: XXXXXX ...

Having an issue in Angular 2 where the correct function is not triggered when a button is placed within a selectable anchor

Within an anchor element, I have a button that triggers its own click listener for an editing popup module. The anchor itself has another click listener assigned to it. For example: <a (click)="onClick(myId)" class="list-group-item clearfix"> < ...

Angular 2: Enhancing User Experience with Pop-up Dialogs

Looking to implement a popup dialog that requests user input and returns the value. The popup component is included in the root component, positioned above the app's router outlet. Within the popup component, there is an open() method that toggles a ...

Guide on showing the content of an uploaded file as an object in JavaScript using file reader

When using the file upload function to upload a json file and read its contents, I am encountering an issue where the result is in string format instead of object. How can I display it as an object? Here is my code: .html <div class="form-group"> ...

Implementing optional default values in React props using conditional types

I have a dilemma with conditional props types When attempting to set a default value for my optional prop within the conditional type, it causes issues with the types export type ChatBase = { id: string; title: string; } type ChatCardProps = { title: ...

Tips for setting up a responsive dropdown field in an Angular 6 reactive form for an Edit page

When creating a drop down field with API values, I encountered an issue where all data was displayed on the edit page instead of just the previously stored value. The drop down field showed all options instead of the selected one. Below is the code for the ...

Alter the command from 'require' to an 'import'

Utilizing https://www.npmjs.com/package/json-bigint with native BigInt functionality has been a challenge. In the CommonJS environment, the following code is typically used: var JSONbigNative = require('json-bigint')({ useNativeBigInt: true }); ...

Incorporate a service into a base class in Angular2 to ensure its functionality extends to all derived classes

I have multiple classes with a hierarchical inheritance structure as follows: class A (an abstract class) class B extends A class C extends B I am looking to incorporate a service into class A to enable a function that utilizes notifications. How can I ...

Error: Namespace declaration does not have a type annotation - TypeScript/Babel

After creating my app using the command npx create-react-app --typescript, I encountered an issue with generated code and namespaces causing Babel to throw an error. Here are the steps I took to try and resolve the issue: I ejected the project Updated b ...

Test fails in Jest - component creation test result is undefined

I am currently working on writing a Jest test to verify the creation of a component in Angular. However, when I execute the test, it returns undefined with the following message: OrderDetailsDeliveryTabComponent › should create expect(received).toBeTru ...

Typescript classes implementing data hydration and dehydration techniques

Exploring ways to share TypeScript classes or interfaces between a React + TS frontend and node + TS backend. Converting class instances into JSON poses a challenge as TS types are removed during compile time. Considering options for defining objects in a ...

What is the reason behind useEffect giving warnings for unnecessary fields that are not included in the dependencies array?

After reviewing the documentation for useEffect, I am puzzled by the warnings I receive for every variable and function used within useEffect, despite not having a dependency on them. Take a look at my useEffect below: const [updatedComm, setUpdatedComm] ...

Issue: This feature cannot be accessed when using the Angular CLI outside of a project workspace during a legacy application migration

Currently working on updating a legacy Angular application where I need to address some vulnerabilities. After updating the node image in the Docker file (which was also updated previously), I encountered the following issues. Unfortunately, I'm havin ...

having trouble integrating and utilizing TypeScript with socket.io

Trying to utilize the npm typescript @types/socket.io definition. To set it up, I followed these steps: npm install --save @types/socket.io npm install --save socket.io After that, my package.json now looks like this: ... "devDependencies": { ...

Setting up the Angular JS environment manually, without relying on an Integrated

I am a complete beginner when it comes to Angular JS. I recently inherited an Angular JS application that I need to run on a server without using any Integrated Development Environment (IDE). I have tried researching online for methods to run the applicat ...

Angular - Ensuring correct rendering of a subcomponent with input parameter on the first update

Here is a snippet of code showcasing a list of educations and a component: <cdk-virtual-scroll-viewport itemSize="5" class="list-scroll"> <app-education-item *ngFor="let education of loadedEducations" ...

What could be the reason for the crash caused by ngModel?

The usage of [(ngModel)] within a *ngFor-Loop is causing an endless loop and crashing the browser. This is how my HTML looks: <div class="container"> <div class="row" *ngFor="let item of controlSystemTargetViewModel.values; let index = i ...

What steps are required to generate dist/app.js from a script file in my TypeScript project?

I am currently working on a project using node, express, and TypeScript. When I run npm run build, everything builds without any issues. However, when I attempt to run npm run start, I encounter the following error: @ruler-mobility/[email protected] /User ...

Deno.Command uses backslashes instead of quotes for input containment

await new Deno.Command('cmd', { args: [ '/c', 'start', `https://accounts.spotify.com/authorize?${new URLSearchParams({ client_id, response_type: 'code', ...

Typescript is failing to perform type checking

I'm encountering an issue while trying to utilize TypeScript type checking with the following code snippet: abstract class Mammal { abstract breed(other: Mammal); } class Dog extends Mammal { breed(other: Dog) {} } class Cat extends Mammal { ...