Search code examples
javaandroidlistviewphone-number

Call phone numbers from list view array


I am trying to create something like a phone directory or hardcoded contact list. I have already created the ListView with contact name and number but I need assistance in calling the phone numbers when pressed. Sample coding would be perfect. Thanks

  ListView listView;

    String [ ]stations = {"911", "999","Jack", "James", "Terror"};

    String pNumbers [] = {"911", "999", "444", "554", "664"
            "};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_police_numbers);

        ListView listView = (ListView) findViewById(R.id.numbersP);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,stations);
        listView.setAdapter(adapter);

        listView= (ListView)findViewById(R.id.numbersP);

    }

Solution

  • Here is a sample code that might get you started:

       private void makeTelCall(String telNumber){
            try{
                Intent intent = new Intent(Intent.ACTION_CALL);
                intent.setData(Uri.parse("tel:"+telNumber));
                startActivity(intent);
            }
            catch(SecurityException se){
                openAppDetailSettings();
                String mess = "Permission for telephone calls has not been granted!";
                Toast.makeText(this, mess, Toast.LENGTH_LONG).show();
                Log.e(TAG, se.getMessage());
            }
            catch (Exception ex){
                Log.e(TAG, ex.getMessage());
            }
        }
    

    The user must grant permission to make calls in the settings. And you must make the appropriate changes to the Manifest file.

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

    In order to get directly to the setting page from your code you can add this:

    private void openAppDetailSettings(){
        String s =  Settings.ACTION_APPLICATION_DETAILS_SETTINGS;
        Intent intent = new Intent();
        intent.setAction(s);
        Uri uri = Uri.fromParts("package", BuildConfig.APPLICATION_ID, null);
        intent.setData(uri);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
    

    Notice that I add the method call from the Exception.

    Please be aware that Android will not allow you to make the call 'silently' (without clicking the 'call button'). This is a security measure to prevent calls being made without the user knowing that a call is being made from their device.