Browse By

Read SMS Message from Inbox / Sent / Draft in Android

  • Hit Chikani

    can u try the backup of all messages in inbox.???

    • vimal rughani

      Its easy, I can do that, If you stuck with any issue, you can ask me your queries.

      • Hit Chikani

        i dont get any file in SD card. so plese give me a source of backu up

  • Hit Chikani

    backup is in TEXT file of XML file.

  • Robert Greso

    Hi at first thanks a lot for your tutorial! I need it for my app but I need also to get text from sms to editText when I click on one of those shown sms in list. Could you help me with this task or just give a hint ? Thanks for your time

    • vimal rughani

      Hi Robert, I am happy that you liked my tutorial. It will be my pleasure to help you in your task. If you want to extend this example to full fill your needs, you need to set setOnItemClickListener

      for your message listview (lvMsg). In that part you can set sms content into your desired edittextbox. Please let me know if you find any difficulty, you can send me your code for exact answer.

      • Robert Greso

        Hi, I have tried a different approach simmilar to contact picker. Here is my code :

        public class Decrypt extends Fragment {
        Button loadButton;
        EditText smsDisplay;

        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){

        View v = inflater.inflate(R.layout.decrypt, null);
        loadButton=(Button)v.findViewById(R.id.buttonLoad);
        smsDisplay=(EditText)v.findViewById(R.id.editTextLoad);
        loadButton.setOnClickListener(new OnClickListener() {

        @Override

        public void onClick(View v) {

        Intent sendIntent = new Intent(Intent.ACTION_VIEW);
        sendIntent.setData(Uri.parse(“sms:”));
        startActivityForResult(sendIntent,2);
        }
        });
        return v;
        }

        public void onActivityResult(int requestCode, int resultCode, Intent data) {

        try{

        Uri ur = data.getData();
        Cursor c = getActivity().getContentResolver().query(ur, null, null,null, null);
        if (c.moveToFirst()) {
        String s = c.getString(c.getColumnIndex(“body”));
        System.out.println(s);
        Toast.makeText(getActivity(), s, Toast.LENGTH_LONG).show();
        smsDisplay.setText(s);
        }
        }catch(Exception e){
        e.printStackTrace();
        }
        }

        It opens a Inbox like when I open original sms app in anroid, but when I click on one message it doesnt copy body of that sms in my edittext.
        Please couul you look at my code and find mistake?

        Thanks a lot for your time

        • eyesice

          Did you find a solution to this?

          • Robert Greso

            Do you mean that onItemClickListener?

          • eyesice

            OnActivityResult , are you able to get the body of the selected SMS ?

          • Robert Greso

            public void onItemClick(AdapterView parent, View view, int position, long id) {

            HashMap map = contactsList.get(position);

            String nameNumber = map.get(MESSAGE_SENDER_NUMBER);

            String body = map.get(MESSAGE_BODY);

            Intent intent = new Intent();

            intent.putExtra(“senderNumber”, nameNumber);

            intent.putExtra(“body”, body);

            setResult(RESULT_OK, intent);

            finish();

            }

            public void onActivityResult(int requestCode, int resultCode, Intent data) {

            try {

            if (requestCode == 22) {

            senderNumber = data.getStringExtra(“senderNumber”);

            body = data.getStringExtra(“body”);

            smsDisplay.setText(body);

            }

            } catch (Exception ex) {

            ex.printStackTrace();

            }

            }

            hope it helps

          • Beenee Bosh

            Can you post your .xml file please?

  • Massab Waqas Piracha

    Hi … I need to backup sms in a file to SD card and then have to restore them back …… Can u please help me how to do that ??????

  • Muhammad Faisal

    Hy bro i want ur help ..I want to get full conversation of specific number in list view.will u help me

  • Niyas Cofi

    Sir, thanks for ur tutorial, it helps me lot , How to read date and time of SMS in Inbox , Sent and Draft

    • http://virtualrealitysystems.net/ Vimal Rughani

      Niyas, I am happy that you like my tutorial. To read date of SMS , you need to put `date` column in reqCols array. String[] reqCols = new String[] { “_id”, “address”, “body”,”date” };
      This will fetch date from content provider and you can use it as per your need.
      Let me know if you have any other query.

  • Herry

    Thanks Vimal Rughani for this tutorial but i need little help how to get date in dd-mm-yyyy format

    • http://virtualrealitysystems.net/ Vimal Rughani

      Hi Herry, to display date into above application. you need to put `date` column in reqCols array. String[] reqCols = new String[] { “_id”, “address”, “body”,”date” };
      To represent date in dd-mm-yyyy format, use SimpleDateFormat class java, to manipulate date format.

      Let me know if you have any other query.

      • Beenee Bosh

        I added “date” into reqCols but didn’t displayed date. What was the problem?

  • deepak

    hello sir, I M a fresher, just know some old programming languages. I have very much interest in programming. I want to learn android programing from staring. what languages should I learn. or any thing else u want to suggest me.

    • http://virtualrealitysystems.net/ Vimal Rughani

      Hi Deepak,

      Android uses core JAVA and xml. I suggest you start learning core JAVA. Once you are familiar with that I will suggest you few books / sites which will help you in learning process.

  • Beenee Bosh

    Hi Vimal, this code is very useful to me, thanks a lot. But I need to encrypt this messages and don’t know how to do that please help me?

    • http://virtualrealitysystems.net/ Vimal Rughani

      Hi Beenee,

      Please check our one of the application which uses encrypted message, https://play.google.com/store/apps/details?id=com.vrs.securesms&hl=en

      Let me know if it fulfill your requirements.

      Regards,

      • Beenee Bosh

        Thaks for reply. This app is encrypt messages you sent. But i need to encrypt and decrypt inbox, sentbox messages and I don’t know how to do that on java code.

      • Beenee Bosh

        Will you help me about how to encrypt inbox and sentbox messages on java code?

        • http://virtualrealitysystems.net/ Vimal Rughani

          Beenee, encryption can be done through AES / DES. Inbox and sentbox message are nothing but string value only. so you can do that easily. Please check below link for AES / DES example
          http://examples.javacodegeeks.com/core-java/crypto/encrypt-decrypt-string-with-des/

          • Beenee Bosh

            I know these messages are string value. But how to get real SMS body and encrypt and decrypt by DES algorthims

          • Beenee Bosh

            Tnhx for reply :)

  • Beenee Bosh

    Hi Vimal I have one more question how to add into this source code get real message body and display it?

  • http://www.blurtit.com/?referred_by=Summerboy summer

    the mobile number 0919261611—sonly
    owner
    SUMMER S./

    since 2001

  • Khushi Kalaria

    hello sir, can u help me to get name of person along with this message. i have also added user permission to read contacts bt i am not able to do so.

    • http://virtualrealitysystems.net/ Vimal Rughani

      Khushi, you have to map mobile number with Contacts Content Provider, to get user name.
      In this article, `address` fields represent mobile number, to learn how to map that number with Contacts Content provider, please follow this article http://pulse7.net/android/contacts-content-provider-android/ You will get exact idea.
      Please feel free to ask your query.

  • maria

    hi sir thanks a lot for this tutorial
    i need to read(speakout) the clicked msgs
    i have tried this but its not working
    can you help me please?
    lvMsg.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override

    public void onItemClick(AdapterView av, View v, int pos,

    long id) {

    String msg = (String) getListAdapter().getItem(pos);

    speakOut(msg.toString());

    }

    });

    • http://virtualrealitysystems.net/ Vimal Rughani

      Maria, can you please tell me what kind of issue you are facing. If there is any crash in app. please send me log cat for that, so I can get exact idea.nn1

  • Safeer Qureshi

    Hi sir, I need to get the newly sent messages in my application while my application is running. I have set a content observer like this: “content://sms” it works fine. But I only need to get the changes in sent items. So, I used “content://sms/sent” but its not observing the changes in sent items. Please help…

  • hossein shooshtari

    Hi thanks a lot for your tutorial! I need something like ‘go sms’ source code, can you help me please, thanks a lot again. :))))

    • Ubuntu Frans

      dont know what you mean. I guess you mean tutorial Fedena?

      • hossein shooshtari

        exactly i need a sms manager with a database to save messages in database and read messages from database,

        i dont mean a big app like ‘go sms’ , just need a simple manager with database,

        thanks for replying Mr.Ubuntu

    • http://virtualrealitysystems.net/ Vimal Rughani

      Hi Hossein,
      Can you please tell me, in which way I can help you in ‘go sms’ app. It’s big application.

      • hossein shooshtari

        exactly i need a sms manager with a database to save messages in database and read messages from database,
        i dont mean a big app like ‘go sms’ , just need a simple manager with database,
        thanks for replying Mr.Vimal.

  • Sai Nalla

    hi nice tutorial but i want to read messages for particular sender from inbox how????
    help me…….

    • http://virtualrealitysystems.net/ Vimal Rughani

      Sai,
      to get messages for particular sender, you have to put filter on address field, while making query to content provider. I hope it will help you let me know if you have any difficulty.

      • Sai Nalla

        thanks for replay
        i changed above code to this::::

        if (v == btnInbox) {

        StringBuilder smsBuilder = new StringBuilder();

        final String SMS_URI_INBOX = “content://sms/inbox”;

        // final String SMS_URI_ALL = “content://sms/”;

        try {

        Uri uri = Uri.parse(SMS_URI_INBOX);

        String[] projection = new String[] { “_id”, “address”, “person”, “body”, “date”, “type” };

        Cursor cur = getContentResolver().query(uri, projection, “address=’xxx'”, null, null);

        if (cur.moveToFirst()) {

        int index_Address = cur.getColumnIndex(“address”);

        int index_Person = cur.getColumnIndex(“person”);

        int index_Body = cur.getColumnIndex(“body”);

        int index_Date = cur.getColumnIndex(“date”);

        int index_Type = cur.getColumnIndex(“type”);

        do {

        String strAddress = cur.getString(index_Address);

        int intPerson = cur.getInt(index_Person);

        String strbody = cur.getString(index_Body);

        long longDate = cur.getLong(index_Date);

        int int_Type = cur.getInt(index_Type);

        smsBuilder.append(“[ “);

        smsBuilder.append(strAddress + “, “);

        smsBuilder.append(intPerson + “, “);

        smsBuilder.append(strbody + “, “);

        smsBuilder.append(longDate + “, “);

        smsBuilder.append(int_Type);

        smsBuilder.append(” ]nn”);

        } while (cur.moveToNext());

        if (!cur.isClosed()) {

        cur.close();

        cur = null;

        }

        } else {

        smsBuilder.append(“no result!”);

        } // end if

        }

        catch (SQLiteException ex) {

        Log.d(“SQLiteException”, ex.getMessage());

        }

        but i didn’t get my requirement…………
        help me if you have any suggestions

        • http://virtualrealitysystems.net/ Vimal Rughani

          Hi Sai, filter should be like this.

          Cursor cur = getContentResolver().query(uri, projection, “address LIKE ? “, new String[]{Number + “%” }, null);

          where Number is string value which contains number to be search.

          I hope this will help you.

          • Sai Nalla

            sir thank you very much for helping me
            i am changed the filter to this
            but it shows an sqlite exception…..
            can u plz help mee…
            i am new to android.

            public void onClick(View v) {

            if (v == btnInbox) {

            StringBuilder smsBuilder = new StringBuilder();

            final String SMS_URI_INBOX = “content://sms/inbox”;

            // final String SMS_URI_ALL = “content://sms/”;

            try {

            Uri uri = Uri.parse(SMS_URI_INBOX);

            String[] projection = new String[] { “_id”, “address”, “person”, “body”, “date”, “type” };

            Cursor cur = getContentResolver().query(uri, projection, “address LIKE ?”,new String[]{OTA + “%” } , null);

            if (cur.moveToFirst()) {

            // int index_id=cur.getColumnIndex(“_id”);

            int index_Address = cur.getColumnIndex(“address OTA ?”);

            int index_Person = cur.getColumnIndex(“person”);

            int index_Body = cur.getColumnIndex(“body”);

            int index_Date = cur.getColumnIndex(“date”);

            int index_Type = cur.getColumnIndex(“type”);

            do {

            String strAddress = cur.getString(index_Address);

            int intPerson = cur.getInt(index_Person);

            String strbody = cur.getString(index_Body);

            long longDate = cur.getLong(index_Date);

            int int_Type = cur.getInt(index_Type);

            // String id = cur.getString(index_id);

            smsBuilder.append(“[ “);

            smsBuilder.append(strAddress + “, “);

            smsBuilder.append(intPerson + “, “);

            smsBuilder.append(strbody + “, “);

            smsBuilder.append(longDate + “, “);

            smsBuilder.append(int_Type);

            // smsBuilder.append(id);

            smsBuilder.append(” ]nn”);

            } while (cur.moveToNext());

            if (!cur.isClosed()) {

            cur.close();

            cur = null;

            }

            } else {

            smsBuilder.append(“no result!”);

            } // end if

            }

            catch (SQLiteException ex) {

            Log.d(“SQLiteException”, ex.getMessage());

            }

          • Sai Nalla

            hiiiii
            i want date of message also in listview
            can you plz help mee????????

          • http://virtualrealitysystems.net/ Vimal Rughani

            Sai,

            Use date field of SMS Content provide, it will give you date of that sms.

          • Sai Nalla

            Cursor c = cr.query(inboxURI, reqCols, “address LIKE ?, date LIKE ? “,

            new String[] { Number + “%”,Date + “%” },null);

            i changed query to this but i getting error……

  • hossein shooshtari

    exactly i need a sms manager with a database to save messages in database and read messages from database,
    i dont mean a big app like ‘go sms’ , just need a simple manager with database,
    thanks for replying Mr.Vimal.

    • http://virtualrealitysystems.net/ Vimal Rughani

      Hossein, it will not be good idea to save sms in database, as they are already exist in Content Provide, we can access from that. Still if you want to store that data in db, its quite easy. Please follow my this article, it will help you. http://pulse7.net/android/sqlite-database-android/
      Once you have cursor of SMS content provider, you can iterate through each record and save that record in any table of sqlite. Hope this will help you.

  • eshal

    hai sir!
    will you help me please .. your tutorial is best but i am not gettig how to set the listView inside item which you have given ids { ibimsg nd ibinumber}.
    i am new to android and working on messages field in android
    thanks

    • http://virtualrealitysystems.net/ Vimal Rughani

      Hi Eshal,

      You have to use custom row for your listview. You can download full source code from download link. in that code you will find row.xml file which is used for custom row. You can put any details which you want to put.

      Let me know if you have any query.

  • http://twitter.com/hitohendrix Kevin Marroquín

    How to print at the log? man thank for example :)

  • Chirag Patel

    what attribute should i use to get sender/recepient name ? “Person” is giving me null.

    • http://virtualrealitysystems.net/ Vimal Rughani

      Hi Chirag,

      You have to query contacts content provider with sms adress value. Directly person will not give name for that contact number.

  • Chirag Mangal

    Hey , Will you please tell me how to delete all messages ?

    • http://virtualrealitysystems.net/ Vimal Rughani

      Hi Chirag, Follow this steps

      1. Fetch all message from content provider.

      2. Loop through that

      3. fire this line.

      context.getContentResolver().delete(
      Uri.parse(“content://sms/” + id), null, null);

      where id is row id of specific message. ( _id )

      I hope this will help you. Let me know if you have any query.

  • Pingback: Android : Delete Message from Inbox programmatically in Android - Pulse7()

  • shariq mnm

    how Can I Fetch a Specific Number Msgs From inbox ????

    • http://virtualrealitysystems.net/ Vimal Rughani

      Hi Shariq, You have to put filter like this.

      Cursor cur = getContentResolver().query(uri, projection, “address LIKE ? “, new String[]{Number + “%” }, null);

      where Number is string value which contains number to be search.

      I hope this will help you.

      • shariq mnm

        this code is not ruining Vimal Rughani kindly
        please my code and if is possible to talk on whatsapp i want to share my idea with you kindly please help me ?

        public void onClick(View v) {
        // TODO Auto-generated method stub
        if(v == btninbox){
        Uri inboxURI = Uri.parse(“content://sms/inbox”);
        String[] reCols = new String[]{“_id”,”address”,”body”}; ContentResolver cr = getContentResolver();
        String Number = “+923132795055”;
        //Cursor c = cr.query(inboxURI, reCols, null, null, null);
        Cursor cur = getContentResolver().query(inboxURI, reCols, “address LIKE +923132795055 “, new String[]{Number + “%” }, null);
        Adapter adapter = new SimpleCursorAdapter(this, R.layout.row, cur,
        new String[]{“body”,”address”},new int[]{ R.id.lblMsg , R.id.lblNo} ); IvMsg.setAdapter((ListAdapter) adapter);
        }

        }

      • http://shariqshek.com/ Shariq Sheki

        Not working Vimal kindly please check my code

        public void onClick(View v) {

        // TODO Auto-generated method stub

        if(v == btninbox){

        Uri inboxURI = Uri.parse(“content://sms/inbox”);

        String[] reCols = new String[]{“_id”,”address”,”body”};

        ContentResolver cr = getContentResolver();

        String Number = “+9231327950”;

        Cursor cur = getContentResolver().query(inboxURI, reCols, “address LIKE +9231327950 “, new String[]{“address” + “%” }, null);

        Adapter adapter = new SimpleCursorAdapter(this, R.layout.row, cur,

        new String[]{“body”,”address”},new int[]{ R.id.lblMsg , R.id.lblNo} );

        IvMsg.setAdapter((ListAdapter) adapter);

        }

        • http://virtualrealitysystems.net/ Vimal Rughani

          Shariq, you are making mistake in query string. either you directly put whole query in 3rd col, or field name in 3rd column and compare value in 4th column, currently you are setting data for both way .. ! Use below query.
          Cursor cur = getContentResolver().query(inboxURI, reCols, “address LIKE +9231327950 “, null, null);

          Let me know still if you have any difficulty.

          • http://shariqshek.com/ Shariq Sheki

            you are genious bro its working thank u soo much ……i

          • Marija Beatriz Tuble

            Hi i followed what you said but i still cant make it work. Here are my codes. I would really appreciate it if you could tell me where i went wrong. Thank you!

            @Override
            public void onClick(View v) {

            if (v == btnInbox) {

            // Create Inbox box URI
            Uri inboxURI = Uri.parse(“content://sms/inbox”);

            // List required columns
            String[] reqCols = new String[] { “_id”, “address”, “body” };

            // Get Content Resolver object, which will deal with Content Provider
            ContentResolver cr = getContentResolver();

            // Fetch Inbox SMS Message from Built-in Content Provider
            Cursor c = cr.query(inboxURI, reqCols, “address LIKE +6587210384”, null, null);

            // Attached Cursor with adapter and display in listview
            adapter = new SimpleCursorAdapter(this, R.layout.row, c,
            new String[] { “body”, “address” }, new int[] {
            R.id.lblMsg, R.id.lblNumber });
            lvMsg.setAdapter(adapter);

            }

  • shrikant konded

    where row layout in this code im not getting

  • shrikant konded

    can u pl help me out in developing an application which will collect sms details like time,date,number and body which has to print in my app by creating local db and accessing from it

  • Paolo Tatel

    Hi, thanks for this tutorial but I’m a bit of a newbie in android so i don’t understand some of the code given. It seems that there is a problem where it cannot resolve the value of lblMsg and lblNumber and I don’t know what to do. Please help!

    • Yasir Ahmed

      here he didn’t mention about the row.xml file just download his project and copy the row.xml file in the layout folder of your project and issue will be solved.

      • Paolo Tatel

        Finally got it to work. Thank you for answering my question.

  • Prathik Ram

    can anyone help me in How to display all the SMS Content Providers of each sms

  • Yashaswi Bhardwaj

    hello sir i want to make an app that reads the user sms and categorises it ..eg: i t should store the sms sent by bank in different folders

  • Eaby Babu

    Hi Vimal, I am so thankful to you for your tutorials, It was a great help for me. I am developing an app for Railway PNR status inquiry. Would you please tell me how to get the PNR no from the user SMS inbox to my Application Text field automatically. Your help would be greatly appreciated. Thanks.

  • Atif Qamar

    Hello Vimal Sir, this was awesome tutorial. I need a small help
    1. I want to generator .vcf file for the contact in my app .
    2. To store all SMS in sd card .
    both 1 and 2 data i want syn to mysql .

    would you please help me sir ?

  • Rigel Cabantac

    Hi I have a question how can I open the source file can I open it using android studio? I am a beginner on creating android apps Thanks

  • Marija Beatriz Tuble

    hi is there any way for me to extract the message itself and store it as a string to be passed as an intent for future use?

  • bardia saboori

    Hi,
    Thanks for your useful tutorial. I’m a newbie and I am trying to get to know how tos in android. I just copied your code into an empty activity and tried to run it on an emulator, but every time the app crashes and shows a message that reads”theApp has stopped”.
    I just sent an sms in the emulator for the sake of the app. I used content Uris for sentbox and inbox. I really donno why the app doesnt work but I’m pretty sure the problem lies in this line:
    Cursor temp = cResolver.query(sentUri, reqCols, null, null, null);
    Can you tell me why it doesnt work!?

  • yu main

    Savvy discussion , I was fascinated by the facts ! Does anyone know where my assistant might be able to get a fillable DEQ 606-002A form to edit ?

  • Ginger Talavera

    https://goo.gl/FbhchD