Read sms from Inbox and display in RecyclerView

0
132

Hello, Developers!! This tutorial will tell you how to retrieve messages from a particular sender from inbox and display on a RecyclerView.

Output:-

Download source code: [media-downloader media_id=”1272″ texts=”Search-SMS.zip”]

Download APK: [media-downloader media_id=”1276″ texts=”Search sms”]

Wants to Learn Advanced Android Application development from scratch- Beyond Basics

Creating New Project

Open your Android Studio & create a new Project, have taken Empty Activity for this project. We kept all the things by default and clicked finish.

Manifest Declarations

To read the messages we need to add following permission in the AndroidManifest.xml

<uses-permission android:name="android.permission.READ_SMS"/>

Add RecyclerView dependency in-app level build.gradle file.

compile 'com.android.support:recyclerview-v7:25.1.1'

Creating Layout

activity_main.xml

This file contains RecyclerView.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.mytrendin.searchsms.MainActivity">
    <TextView
        android:text="Enter search number"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        android:textSize="15sp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginRight="20dp"
        android:layout_marginEnd="20dp" />

    <EditText
        android:id="@+id/number"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:layout_below="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/textView"
        android:layout_alignEnd="@+id/textView"
        android:layout_marginTop="16dp" />

    <Button
        android:text="ADD"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn_add"

        android:elevation="8dp"
        android:layout_below="@+id/number"
        android:layout_centerHorizontal="true" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rvList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="23dp"
        android:layout_below="@+id/btn_add"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentBottom="true">
    </android.support.v7.widget.RecyclerView>
</RelativeLayout>

activity_recview.xml

This file is used to render inside RecyclerView.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:gravity="center_vertical|left"
    android:layout_height="match_parent"
    android:paddingTop="5dp"
    android:paddingLeft="5dp"
    android:paddingRight="5dp"
    android:paddingBottom="5dp"
    android:background="#ffffff">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:paddingBottom="10dp"
        android:orientation="vertical"
        android:background="@drawable/cardview">

    <TextView
        android:text="TextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@android:color/primary_text_light"

        android:layout_marginLeft="10dp"
        android:layout_marginStart="10dp"
        android:id="@+id/ph_no" />

    <TextView
        android:text="TextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:textColor="@android:color/primary_text_light"
        android:layout_marginStart="10dp"
        android:id="@+id/msg" /></LinearLayout>
</RelativeLayout>

MainActivity.java

package com.mytrendin.searchsms;

import android.Manifest;
import android.app.LauncherActivity;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.BoolRes;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    EditText number;
    Button add_btn;
    RecyclerView rvList;
    Boolean permission = false;
    public static final int MY_PERMISSIONS_REQUEST_READ_SMS = 99;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rvList = (RecyclerView) findViewById(R.id.rvList);
        number = (EditText)findViewById(R.id.number);
        add_btn = (Button)findViewById(R.id.btn_add);

        add_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    permission = checkSmsPermission();
                    if (permission) {
                        List<ListItem> list= new ArrayList();
                        ListItem listItem;
                        final String num = number.getText().toString();
                        Uri uriSms = Uri.parse("content://sms/inbox");
                        final Cursor cursor = getContentResolver().query(uriSms, 
               new String[]{"_id", "address", "date", "body"}, null, null, null);

                        while (cursor.moveToNext()) {
                            String address = cursor.getString(1);
                            if (address.equals(num)) {
                                String msg = cursor.getString(3);
                                listItem = new ListItem();
                                listItem.setNumber(address);
                                listItem.setMessage(msg);
                                list.add(listItem);
                            }
                        }
                        ListAdapter listAdapter = new ListAdapter(list, 
                                       getBaseContext());
                        rvList.setLayoutManager(new LinearLayoutManager(
                                       getBaseContext()));
                        rvList.setAdapter(listAdapter);
                    }
                }
            }
        });
    }
    public boolean checkSmsPermission() {

                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.READ_SMS)
                        != PackageManager.PERMISSION_GRANTED) {
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                            android.Manifest.permission.READ_SMS)) {
                        ActivityCompat.requestPermissions(this,
                                new String[]{android.Manifest.permission.READ_SMS},
                                MY_PERMISSIONS_REQUEST_READ_SMS);
                    } else {
                        ActivityCompat.requestPermissions(this,
                                new String[]{android.Manifest.permission.READ_SMS},
                                MY_PERMISSIONS_REQUEST_READ_SMS);
                    }
                    return false;
                } else {
                    return true;
                }
            }
            @Override
            public void onRequestPermissionsResult(int requestCode,
                                  String permissions[], int[] grantResults) {
                switch (requestCode) {
                    case MY_PERMISSIONS_REQUEST_READ_SMS: {
                        if (grantResults.length > 0
                                && grantResults[0] == PackageManager.
                                                       PERMISSION_GRANTED) {
                            if (ContextCompat.checkSelfPermission(this,
                                    android.Manifest.permission.READ_SMS)
                                    == PackageManager.PERMISSION_GRANTED) {
                                return;
                            }
                        } else {
                            Toast.makeText(getApplicationContext(),
                                       "permission denied",
                                    Toast.LENGTH_LONG).show();
                        }
                        return;
                    }
                }
            }
}

Whenever the button to add number is clicked we will apply a Version check before executing our code. If the Android Version is equal or above the Marshmallow version then permission has to be granted first, by the user.

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
     permission = checkSmsPermission();

If the permission is given we will create the List of type ListItem and then object to ListItem.

List<ListItem> list= new ArrayList();
ListItem listItem;

Now we will get the number to be searched from the EditText

final String num = number.getText().toString();

Uniform Resource Identifier(URI) is a string of characters used to identify a resource. The method createsUri.parse a new Uriobject from a properly formatted String which we can use to refer to resources. Here the string would point to the inbox as we want to read the messages from there. Then we will pass this URI object to the getContentResolver method’s query. The second parameter to this query would be names of columns.

Related:

Receive SMS in Application and Search for keywords

Connecting To Phone Book, Phone Call, And Default SMS Service using Android

Send SMS using Intent

Drag and Swipe with RecyclerView

ItemDecoration in RecyclerView in Android

Uri uriSms = Uri.parse("content://sms/inbox");
final Cursor cursor = getContentResolver().query(uriSms, 
           new String[]{"_id", "address", "date", "body"}, 
           null, null, null);

Next, we will parse through this cursor to get our messages

while (cursor.moveToNext()) {
   String address = cursor.getString(1);
   if (address.equals(num)) {
       String msg = cursor.getString(3);
       listItem = new ListItem();
       listItem.setNumber(address);
       listItem.setMessage(msg);
       list.add(listItem);
   }
}

So as we need to display only those messages which are sent from a particular number. So we will first get the number of messages where the cursor is currently pointing, then we’ll check if that number matches with the number entered by the user and if it does only then we will retrieve the message’s body and then add it to the ListItem’s object. This object is then added to the List.

If you want to display all the messages from the inbox then simply remove this if condition.

Then the Layout would be set for RecyclerView using

 rvList.setLayoutManager(new LinearLayoutManager(getBaseContext()));

ListItem.java

package com.mytrendin.searchsms;

public class ListItem {

    private String Number;
    private String Message;

    public String getNumber() {
        return Number;
    }

    public void setNumber(String number) {
        Number = number;
    }

    public String getMessage() {
        return Message;
    }

    public void setMessage(String message) {
        Message = message;
    }
}

Here the file will hold the values in the form getter and setter methods for the Number and Message.

ListAdapter.java

package com.mytrendin.searchsms;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;

public class ListAdapter extends RecyclerView.Adapter<ListAdapter.myHolder>{

    private List<ListItem> list;
    private Context mContext;
    public ListAdapter(List<ListItem> list, Context mContext){
        this.list = list;
        this.mContext = mContext;
    }

    @Override
    public myHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.activity_recview, null);
        myHolder holder = new myHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(myHolder holder, int position) {
        ListItem listItem = list.get(position);
        holder.ph_no.setText(listItem.getNumber());
        holder.msg.setText(listItem.getMessage());
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public static class myHolder extends RecyclerView.ViewHolder{

        TextView ph_no;
        TextView msg;

        public myHolder(View itemView) {
            super(itemView);
            ph_no = (TextView) itemView.findViewById(R.id.ph_no);
            msg = (TextView) itemView.findViewById(R.id.msg);
        }
    }
}

update colors.xml file

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="colorBackroundWhite">#f0f2ea</color>
</resources>

create one XML file inside a drawable folder named cardview.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
    <solid android:color="#ffffff" />
    <stroke android:width="2dp" android:color="@color/colorBackroundWhite"/>
    <corners android:radius="2dp"/>
</shape>

This file will create the card view look. If You are Beginner Learn Android application development from the scratch


If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

LEAVE A REPLY

Please enter your comment!
Please enter your name here