Question

I'm totaly new to Android app dev. I'm trying to make a button which on click would open phonebook (contacts); after that I should be able to select one or more contacts from the list. After that to get the number(s) stored in a variable as a string which contains one or more numbers (depending how much are selected) something like - ("+XX XXX XXX, +XX XXX xXX")

I saw a lot of code for it but I could not implement anything of that to work in the end.

Whole Code

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.telephony.SmsManager;

public class AndroidGPSTrackingActivity extends Activity {

    private static final int PICK_CONTACT = 0;

    protected static final int CHOOSE_CONTACTS = 0;

    Button btnShowLocation;

    // GPSTracker class
    GPSTracker gps;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btnShowLocation = (Button) findViewById(R.id.btnShowLocation);

        // show location button click event
        btnShowLocation.setOnClickListener(new View.OnClickListener() {



            @Override
            public void onClick(View arg0) {        
                // create class object
                gps = new GPSTracker(AndroidGPSTrackingActivity.this);

                // check if GPS enabled     
                if(gps.canGetLocation()){

                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();


                    String StringLong = decimalToDMS(longitude);
                    String StringLati = decimalToDMS(latitude);

                    // \n is for new line
                    Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + StringLati + "\nLong: " + StringLong, Toast.LENGTH_LONG).show();    

                    //SENDING SMS CODE START

                    String phoneNumber = "5556";
                    String message = "Moja GPS Lokacija je " + latitude + "   " + longitude;

                    SmsManager smsManager = SmsManager.getDefault();
                    smsManager.sendTextMessage(phoneNumber, null, message, null, null);


                      //SENDING SMS CODE END



                }else{
                    // can't get location
                    // GPS or Network is not enabled
                    // Ask user to enable GPS/network in settings
                    gps.showSettingsAlert();
                }





            }
        });

        // get contacts
      //Button Click
        View addNewContact;
        addNewContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
                startActivityForResult(intent, CHOOSE_CONTACTS);
            }
        });
        //Button click end



        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
        startActivityForResult(intent, PICK_CONTACT);

        public void onActivityResult(int reqCode, int resultCode, Intent data) {
            super.onActivityResult(reqCode, resultCode, data);

            switch (reqCode) {
              case (PICK_CONTACT) :
                if (resultCode == Activity.RESULT_OK) {
                    Uri contactData = data.getData();
                      Cursor c =  getContentResolver().query(contactData, null, null, null, null);
                       if (c.moveToFirst()) {
                        String name = c.getString(c.getColumnIndexOrThrow(People.NAME));  
                        String number = c.getString(c.getColumnIndexOrThrow(People.NUMBER));
                        TextView perrsonname;
                        perrsonname.setText(name);
                        Toast.makeText(this,  name + " has number " + number, Toast.LENGTH_LONG).show();
                       }
                 }
               break;
            }

        }



        //end contacts






    }

    String decimalToDMS(double coord) {
        String output, degrees, minutes, seconds;

        // gets the modulus the coordinate divided by one (MOD1).
        // in other words gets all the numbers after the decimal point.
        // e.g. mod := -79.982195 % 1 == 0.982195
        //
        // next get the integer part of the coord. On other words the whole
        // number part.
        // e.g. intPart := -79

        double mod = coord % 1;
        int intPart = (int) coord;

        // set degrees to the value of intPart
        // e.g. degrees := "-79"

        degrees = String.valueOf(intPart);

        // next times the MOD1 of degrees by 60 so we can find the integer part
        // for minutes.
        // get the MOD1 of the new coord to find the numbers after the decimal
        // point.
        // e.g. coord := 0.982195 * 60 == 58.9317
        // mod := 58.9317 % 1 == 0.9317
        //
        // next get the value of the integer part of the coord.
        // e.g. intPart := 58

        coord = mod * 60;
        mod = coord % 1;
        intPart = (int) coord;
        if (intPart < 0) {
            // Convert number to positive if it's negative.
            intPart *= -1;
        }

        // set minutes to the value of intPart.
        // e.g. minutes = "58"
        minutes = String.valueOf(intPart);

        // do the same again for minutes
        // e.g. coord := 0.9317 * 60 == 55.902
        // e.g. intPart := 55
        coord = mod * 60;
        intPart = (int) coord;
        if (intPart < 0) {
            // Convert number to positive if it's negative.
            intPart *= -1;
        }

        // set seconds to the value of intPart.
        // e.g. seconds = "55"
        seconds = String.valueOf(intPart);

        // I used this format for android but you can change it
        // to return in whatever format you like
        // e.g. output = "-79/1,58/1,56/1"
        output = degrees + "° " + minutes + "' " + seconds + " \" ";

        // Standard output of DMS
        // output = degrees + "°" + minutes + "'" + seconds + "\"";

        return output;
    }
}

XML FILE

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="80dp"
        android:src="@drawable/ic_launcher" 
        android:contentDescription="@string/plex_logo_description" />

    <Button
        android:id="@+id/btnShowLocation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="30dp"
        android:text="@string/sendLocation"
        android:background="#70bcba"
        android:padding="10dp"
        android:textColor="#fff"
        android:textStyle="bold"

        />


    <Button
        android:id="@+id/addNewContact"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btnShowLocation"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="60dp"
        android:text="@string/choose_contact"
        android:onClick="addNewContact"
         />


</RelativeLayout>
Was it helpful?

Solution

This will open contact to select a number

Intent intent = new Intent(Intent.ACTION_PICK);
   intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
  startActivityForResult(intent, PICK_CONTACT);

Now use onActivityResult to get the contact

public void onActivityResult(int reqCode, int resultCode, Intent data) {
      super.onActivityResult(reqCode, resultCode, data);

      switch (reqCode) {
        case (PICK_CONTACT) :
          if (resultCode == Activity.RESULT_OK) {
              Uri contactData = data.getData();
                Cursor c =  getContentResolver().query(contactData, null, null, null, null);
                 if (c.moveToFirst()) {
                  String name = c.getString(c.getColumnIndexOrThrow(People.NAME));  
                  String number = c.getString(c.getColumnIndexOrThrow(People.NUMBER));
                  perrsonname.setText(name);
                  Toast.makeText(this,  name + " has number " + number, Toast.LENGTH_LONG).show();
                 }
           }
         break;
      }

  }

Don't forget to add the Read Contacts permission.

update :-

inside your oncreate() add the following and remove the previous code from my answer.

Button addNewContact = (Button) findViewById(R.id.addNewContact);
addNewContact.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
                    startActivityForResult(intent, CHOOSE_CONTACTS);
                }
            });

remove code from comment get contacts to end contacts.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top