0

I have an android app which send multiple message and call on a click event.The problem is that

I have two click event.On second click event the code works perfect, but on first click event same code not works (i.e. it not sending any message).this may be seems very silly but I'm unable to find out the bug.Please tell me how to resolve this.

If any other info needed please inform me.

My code is :

     public class MainActivity extends AppCompatActivity {


            ArrayList<String> ar = new ArrayList<String>();


            public static final String MyPREFERENCES1 = "MyPrefs1" ;
            public static final String C11 = "contact11";
            public static final String C12 = "contact12";
            public static final String C13 = "contact13";
            public static final String C14 = "contact14";
            public static final String MSG11 = "msg11";
            public static final String MyPREFERENCES2 = "MyPrefs2" ;
            public static final String C21 = "contact21";
            public static final String C22 = "contact22";
            public static final String C23 = "contact23";
            public static final String C24 = "contact24";
            public static final String MSG22 = "msg22";


            RelativeLayout b1,b2,b3,b4,b5;
            Uri smsToUri;
        //    String c11,c12,c13,c14,msg11;
            String c21,c22,c23,c24,msg22;



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



                 b1 = (RelativeLayout) findViewById(R.id.LinearLayout1);
                 b2 = (RelativeLayout) findViewById(R.id.LinearLayout2);



                SharedPreferences prfs = getSharedPreferences(MyPREFERENCES1, Context.MODE_APPEND);
                 c11 = prfs.getString(C11, "");
                 c12 = prfs.getString(C12, "");
                 c13 = prfs.getString(C13, "");
                 c14 = prfs.getString(C14, "");
                 msg11 = prfs.getString(MSG11, "");

    First click event

                assert b1 != null;
                b1.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        File f = new File(
                                "/data/data/com.example.neo.dial_test/shared_prefs/MyPrefs1.xml");


                        if (f.exists()) {
                            if (c11.toString().equals(C11)||c11.toString().equals("")||c12.toString().equals(C11)||c12.toString().equals("")||c13.toString().equals(C11)||c13.toString().equals("")||c14.toString().equals(C11)||c14.toString().equals("")){

                                if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {

                                    return;
                                }
                                Intent intent3 = new Intent(Intent.ACTION_CALL);
                                intent3.setData(Uri.parse("tel:11223321"));
                                intent3.putExtra("com.android.phone.extra.slot", 0);
                                startActivity(intent3);
                                Log.d("TAG", "SharedPreferences Name_of_your_preference : exist");
                                for (int i = 0; i < ar.size(); i++)
                                {
                                    String message = msg11.toString();
                                    String tempMobileNumber = ar.get(i).toString();
                                    multipleSMS(tempMobileNumber, message);
                                }
                            }

                            else {
                                Intent intent3 = new Intent(Intent.ACTION_CALL);
                                intent3.setData(Uri.parse("tel:9506171242"));
                                intent3.putExtra("com.android.phone.extra.slot", 0);
                                startActivity(intent3);
                                Log.d("TAG", "SharedPreferences Name_of_your_preference : exist");
                                for (int i = 0; i < ar.size(); i++)
                                {
                                    String message = msg11.toString();
                                    String tempMobileNumber = ar.get(i).toString();
                                    multipleSMS(tempMobileNumber, message);
                                }
                            }


                        }
                        else{

                            if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {

                                return;
                            }
                            Intent intent3 = new Intent(Intent.ACTION_CALL);
                            intent3.setData(Uri.parse("tel:9506171243"));
                            intent3.putExtra("com.android.phone.extra.slot", 0);
                            startActivity(intent3);
                            Log.d("TAG", "SharedPreferences Name_of_your_preference : exist");
                        }
                    }
                });

                SharedPreferences prfs2 = getSharedPreferences(MyPREFERENCES2, Context.MODE_APPEND);
                c21 = prfs2.getString(C21, "");
                c22 = prfs2.getString(C22, "");
                c23 = prfs2.getString(C23, "");
                c24 = prfs2.getString(C24, "");
                msg22 = prfs2.getString(MSG22, "");


                ar.add(c21);
                ar.add(c22);
                ar.add(c23);
                ar.add(c24);
        //


Second click event       
                assert b2 != null;
                b2.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        File f = new File(
                                "/data/data/com.example.neo.dial_test/shared_prefs/MyPrefs2.xml");


                        if (f.exists()) {
                                if (c21.toString().equals(C11)||c21.toString().equals("")||c22.toString().equals(C11)||c22.toString().equals("")||c23.toString().equals(C11)||c23.toString().equals("")||c24.toString().equals(C11)||c24.toString().equals("")){

                                   if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {

                                       return;
                                  }
                                    Intent intent3 = new Intent(Intent.ACTION_CALL);
                                    intent3.setData(Uri.parse("tel:9506171244"));
                                    intent3.putExtra("com.android.phone.extra.slot", 0);
                                    startActivity(intent3);
                                    Log.d("TAG", "SharedPreferences Name_of_your_preference : exist");
                                    for (int i = 0; i < ar.size(); i++)
                                    {
                                        String message = msg22.toString();
                                        String tempMobileNumber = ar.get(i).toString();
                                        multipleSMS(tempMobileNumber, message);
                                    }
                                }

                            else {
                                    Intent intent3 = new Intent(Intent.ACTION_CALL);
                                    intent3.setData(Uri.parse("tel:9506171244"));
                                    intent3.putExtra("com.android.phone.extra.slot", 0);
                                    startActivity(intent3);
                                    Log.d("TAG", "SharedPreferences Name_of_your_preference : exist");
                                    for (int i = 0; i < ar.size(); i++)
                                    {
                                        String message = msg22.toString();
                                        String tempMobileNumber = ar.get(i).toString();
                                        multipleSMS(tempMobileNumber, message);
                                    }
                                }


                        }
                      else{

                            if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {

                                return;
                            }
                            Intent intent3 = new Intent(Intent.ACTION_CALL);
                            intent3.setData(Uri.parse("tel:9506171244"));
                            intent3.putExtra("com.android.phone.extra.slot", 0);
                            startActivity(intent3);
                            Log.d("TAG", "SharedPreferences Name_of_your_preference : exist");
                        }

                    } } );




            }


            private void multipleSMS(String phoneNumber, String message) {
                String SENT = "SMS_SENT";
                String DELIVERED = "SMS_DELIVERED";

                PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(
                        SENT), 0);

                PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
                        new Intent(DELIVERED), 0);

                // ---when the SMS has been sent---
                registerReceiver(new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context arg0, Intent arg1) {
                        switch (getResultCode()) {
                            case Activity.RESULT_OK:
                                ContentValues values = new ContentValues();
                                for (int i = 0; i < ar.size() - 1; i++) {
                                    values.put("address", ar.get(i).toString());
                                    // txtPhoneNo.getText().toString());
                                    values.put("body", ar.toString());
                                }
                                getContentResolver().insert(
                                        Uri.parse("content://sms/sent"), values);
                                Toast.makeText(getBaseContext(), "SMS sent",
                                        Toast.LENGTH_SHORT).show();
                                break;
                            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                                Toast.makeText(getBaseContext(), "Generic failure",
                                        Toast.LENGTH_SHORT).show();
                                break;
                            case SmsManager.RESULT_ERROR_NO_SERVICE:
                                Toast.makeText(getBaseContext(), "No service",
                                        Toast.LENGTH_SHORT).show();
                                break;
                            case SmsManager.RESULT_ERROR_NULL_PDU:
                                Toast.makeText(getBaseContext(), "Null PDU",
                                        Toast.LENGTH_SHORT).show();
                                break;
                            case SmsManager.RESULT_ERROR_RADIO_OFF:
                                Toast.makeText(getBaseContext(), "Radio off",
                                        Toast.LENGTH_SHORT).show();
                                break;
                        }
                    }
                }, new IntentFilter(SENT));

                // ---when the SMS has been delivered---
                registerReceiver(new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context arg0, Intent arg1) {
                        switch (getResultCode()) {
                            case Activity.RESULT_OK:
                                Toast.makeText(getBaseContext(), "SMS delivered",
                                        Toast.LENGTH_SHORT).show();
                                break;
                            case Activity.RESULT_CANCELED:
                                Toast.makeText(getBaseContext(), "SMS not delivered",
                                        Toast.LENGTH_SHORT).show();
                                break;
                        }
                    }
                }, new IntentFilter(DELIVERED));

                SmsManager sms = SmsManager.getDefault();
                try{
                sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
            }catch (IllegalArgumentException ex){
                    Toast.makeText(getBaseContext(), "exception",
                            Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onBackPressed() {
                // mIsBackButtonPressed = true;
                // super.onBackPressed();
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
                alertDialogBuilder.setTitle("Exit Application?");
                alertDialogBuilder
                        .setMessage("Click yes to exit!")
                        .setCancelable(true)
                        .setPositiveButton("Yes",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        // Write your code here to execute after dialog

                                        Intent startMain = new Intent(Intent.ACTION_MAIN);
                                        startMain.addCategory(Intent.CATEGORY_HOME);
                                        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        startMain.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                        startActivity(startMain);
                                        finish();
                                        MainActivity.isQuit = true;

        //                                Toast.makeText(getApplicationContext(), "ThanK You",
        //                                        Toast.LENGTH_LONG).show();
                                    }
                                })

                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {

                                dialog.cancel();

                            }
                        });

                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();
                return;
            }
            public static boolean isQuit = false;
        }

error log on second button click

E/ActivityThread: Activity com.example.neo.dial_test.MainActivity has leaked IntentReceiver com.example.neo.dial_test.MainActivity$7@798546 that was originally registered here. Are you missing a call to unregisterReceiver()?
                  android.app.IntentReceiverLeaked: Activity com.example.neo.dial_test.MainActivity has leaked IntentReceiver com.example.neo.dial_test.MainActivity$7@798546 that was originally registered here. Are you missing a call to unregisterReceiver()?
                      at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:898)
                      at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:699)
                      at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1653)
                      at android.app.ContextImpl.registerReceiver(ContextImpl.java:1633)
                      at android.app.ContextImpl.registerReceiver(ContextImpl.java:1627)
                      at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:488)
                      at com.example.neo.dial_test.MainActivity.multipleSMS(MainActivity.java:595)
                      at com.example.neo.dial_test.MainActivity.access$000(MainActivity.java:32)
                      at com.example.neo.dial_test.MainActivity$1.onClick(MainActivity.java:139)
                      at android.view.View.performClick(View.java:4757)
                      at android.view.View$PerformClick.run(View.java:19757)
                      at android.os.Handler.handleCallback(Handler.java:739)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:135)
                      at android.app.ActivityThread.main(ActivityThread.java:5233)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)

and when I m using this code to handle above error( Are you missing a call to unregisterReceiver()?) using this code :

private BroadcastReceiver sendBroadcastReceiver;
private BroadcastReceiver deliveryBroadcastReceiver;
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    sendBroadcastReceiver = new BroadcastReceiver()
    {

        public void onReceive(Context arg0, Intent arg1)
        {
            switch (getResultCode())
            {
            case Activity.RESULT_OK:
                Toast.makeText(getBaseContext(), "SMS Sent", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                Toast.makeText(getBaseContext(), "Generic failure", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_NO_SERVICE:
                Toast.makeText(getBaseContext(), "No service", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_NULL_PDU:
                Toast.makeText(getBaseContext(), "Null PDU", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_RADIO_OFF:
                Toast.makeText(getBaseContext(), "Radio off", Toast.LENGTH_SHORT).show();
                break;
            }
        }
    };

    deliveryBroadcastReceiver = new BroadcastReceiver()
    {
        public void onReceive(Context arg0, Intent arg1)
        {
            switch (getResultCode())
            {
            case Activity.RESULT_OK:
                Toast.makeText(getBaseContext(), "SMS Delivered", Toast.LENGTH_SHORT).show();
                break;
            case Activity.RESULT_CANCELED:
                Toast.makeText(getBaseContext(), "SMS not delivered", Toast.LENGTH_SHORT).show();
                break;
            }
        }
    };
registerReceiver(deliveryBroadcastReceiver, new IntentFilter(DELIVERED));
registerReceiver(sendBroadcastReceiver , new IntentFilter(SENT));

public void sendSMS(String phoneNumber, String message)
{
    String SENT = "SMS_SENT";
    String DELIVERED = "SMS_DELIVERED";
    PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
    PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0);
    SmsManager sms = SmsManager.getDefault();
    sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}

@Override
protected void onStop()
{
    unregisterReceiver(sendBroadcastReceiver);
    unregisterReceiver(deliveryBroadcastReceiver);
    super.onStop();
}
}

Error log After changing the the code replace the multipleSMS function with sendSMS function of new code.

FATAL EXCEPTION: main
                  Process: com.example.neo.dial_test, PID: 20531
                  java.lang.IllegalArgumentException: Invalid destinationAddress
                      at android.telephony.SmsManager.sendTextMessage(SmsManager.java:243)
                      at com.example.neo.dial_test.MainActivity.sendSMS(MainActivity.java:611)
                      at com.example.neo.dial_test.MainActivity$3.onClick(MainActivity.java:185)
                      at android.view.View.performClick(View.java:4757)
                      at android.view.View$PerformClick.run(View.java:19757)
                      at android.os.Handler.handleCallback(Handler.java:739)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:135)
                      at android.app.ActivityThread.main(ActivityThread.java:5233)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
Adi
  • 400
  • 8
  • 25
  • You have multiple ifs and elses in `onClick()`. So it is easy for you (and impossible for us) to determine (by logging or debugging) what happens if you click the button for the first time. Without this information, it's hard to tell what the problem may be. (With this information on the other hand, you may not need our help any more because you solved the issue on your own.) So please provide details on what happens if you really need help. – Bö macht Blau Oct 27 '16 at 06:24
  • if condition just for validation.I'm trying to send multiple message and call.I'm posted more code because same code works on one event and not works in other event. – Adi Oct 27 '16 at 06:29
  • Possible duplicate of [IntentRecieverLeakedException, Are you missing a call to unregisterReceiver() ? in android](http://stackoverflow.com/questions/9078390/intentrecieverleakedexception-are-you-missing-a-call-to-unregisterreceiver) – Bö macht Blau Oct 27 '16 at 06:38
  • That's the problem: " Are you missing a call to unregisterReceiver()?" You always have to unregister a BroadcastReceiver. BTW, you had me looking at your code for 10 minutes and you never said anything about an exception. That's not exactly nice. – Bö macht Blau Oct 27 '16 at 06:40
  • Sorry... I assume that people will know that.. – Adi Oct 27 '16 at 06:49
  • Well, "code not works" could mean there is an exception. It might also mean that it does not do what it's supposed to do. The "duplicate" link contains some info on how to handle your problem, so maybe you get it solved this time. But all in all you'll get more help if you provide all the relevant info (and preferably just the relevant info) from the beginning. – Bö macht Blau Oct 27 '16 at 07:01
  • All right, this is a new kind of problem. Maybe you'd best ask a new question: it will be shown in the queue whereas this one may already be too old, so it will not receive much attention. SO seems to encourage "one problem per question" anyway. And please remember: as little code as possible, but always enough so we can reproduce the error, and of course always the error log if there is one. Readability matters ;-) – Bö macht Blau Oct 27 '16 at 07:25

0 Answers0