0

Hello I would like to ask for help on how to get the if else statements found below inside a onreceive from a broadcastreceiver . Im trying to change the button background depending on the value received. like when I receive the value 1 the button image will change to onn . Because it does not work when I place if else statements, but if I place the btn.setBackgroundResource(R.drawable.onn); before the if else statements it works fine however it defeats the purpose of having the app show which button is at on state. I'm trying to create an app that will update 6 switches depending on the text message. Like if I receive 111000 the first three switches will change image to on. TIA Main activity package com.example.asd;

import java.lang.reflect.Array;
import java.text.BreakIterator;

import android.R.array;
import android.R.layout;
import android.R.string;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.widget.TextView;

public class MainActivity extends Activity {
    String[] bin={"0","0","0","0","0","0"};
    String[] bin1={"0","0","0","0","0","0"};
    Button zero,one,two,three,four,five,update,refresh;
    IntentFilter intentFilter; 
    TextView tv1;
    private final BroadcastReceiver intentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //---display the SMS received in the TextView---
            init();
            zero=(Button)findViewById(R.id.one);
            bin[0]=intent.getStringExtra("zero");
            if (bin[0]!=null && bin[0].equalsIgnoreCase("1")) {
                zero.setBackgroundResource(R.drawable.onn);
            }
            else {
                zero.setBackgroundResource(R.drawable.off);
            }
            one=(Button)findViewById(R.id.two);
            bin[1]=intent.getStringExtra("one");
            if (bin[1]!=null && bin[1].equalsIgnoreCase("1")) {
                one.setBackgroundResource(R.drawable.onn);
            }
            else {
                one.setBackgroundResource(R.drawable.off);
            }
            two=(Button)findViewById(R.id.three);
            bin[2]=intent.getStringExtra("two");
            if (bin[2]!=null && bin[2].equalsIgnoreCase("1")) {
                two.setBackgroundResource(R.drawable.onn);
            }
            else {
                two.setBackgroundResource(R.drawable.off);
            }
            three=(Button)findViewById(R.id.four);
            bin[3]=intent.getStringExtra("three");
            if (bin[3]!=null && bin[3].equalsIgnoreCase("1")) {
                three.setBackgroundResource(R.drawable.onn);
            }
            else {
                three.setBackgroundResource(R.drawable.off);
            }
            four=(Button)findViewById(R.id.five);
            bin[4]=intent.getStringExtra("four");
            if (bin[4]!=null && bin[4].equalsIgnoreCase("1")) {
                four.setBackgroundResource(R.drawable.onn);
            }
            else {
                four.setBackgroundResource(R.drawable.off);
            }
            five=(Button)findViewById(R.id.six);
            bin[5]=intent.getStringExtra("five");
            if (bin[5]!=null && bin[5].equalsIgnoreCase("1")) {
                five.setBackgroundResource(R.drawable.onn);
            }
            else {
                five.setBackgroundResource(R.drawable.off);
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //---intent to filter for SMS messages received---
        intentFilter = new IntentFilter();
        zero=(Button)findViewById(R.id.one);
        one=(Button)findViewById(R.id.two);
        two=(Button)findViewById(R.id.three);
        three=(Button)findViewById(R.id.four);
        four=(Button)findViewById(R.id.five);
        five=(Button)findViewById(R.id.six);
        refresh=(Button)findViewById(R.id.refresh);
        update=(Button)findViewById(R.id.update);
        intentFilter.addAction("SMS_RECEIVED_ACTION");

        zero.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bin[0]=="1") {
                    bin[0]="0";     
                    updateBtn();
                }
                else {
                    bin[0]="1";
                    updateBtn();
                }
            }
        });
        one.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bin[1].equals("1")) {
                    bin[1]="0";     
                    updateBtn();
                }
                else {
                    bin[1]="1"; 
                    updateBtn();
                }
            }
        });
        two.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bin[2].equals("1")) {
                    bin[2]="0";             
                    updateBtn();
                }
                else {
                    bin[2]="1";             
                    updateBtn();
                }
            }
        });
        three.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bin[3].equals("1")) {
                    bin[3]="0";         
                    updateBtn();
                }
                else {
                    bin[3]="1";                 
                    updateBtn();
                }
            }
        });
        four.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bin[4].equals("1")) {
                    bin[4]="0";                 
                    updateBtn();
                }
                else {
                    bin[4]="1";                 
                    updateBtn();
                }
            }
        });
        five.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (bin[5].equals("1")) {
                    bin[5]="0";                 
                    updateBtn();
                }
                else {
                    bin[5]="1";
                    updateBtn();
                }
            }
        });
        refresh.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                updateBtn();
                String s="";
                for (int i = 0; i < 6; i++) {
                    s+= bin[i];
                }
                String upToNCharacters = s.substring(0, Math.min(s.length(), 6));
                Toast.makeText(getBaseContext(),upToNCharacters+"00", Toast.LENGTH_LONG).show();
                s="";
            }
        });
        update.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                updateBtn();
                //Toast.makeText(getBaseContext(),s0+s1+s2+s3+s4+s5+"00", Toast.LENGTH_LONG).show();
                Toast.makeText(getBaseContext(),bin[0]+bin[1]+bin[2]+bin[3]+bin[4]+bin[5]+"00", Toast.LENGTH_LONG).show();

            }
        });
    }


    private void updateBtn() {
        for (int i = 0; i < 6; i++) {
            if (bin[i]==null) {
                bin[i]="0";
            }
            else
            {
                bin[i]=bin[i];
            }
        }
        if (bin[0]=="1") {
            zero.setBackgroundResource(R.drawable.onn);
        }
        else if(bin[0]=="0"){
            zero.setBackgroundResource(R.drawable.off);
        }
        if (bin[1]=="1") {
            one.setBackgroundResource(R.drawable.onn);
        }
        else if(bin[1]=="0"){
            one.setBackgroundResource(R.drawable.off);
        }
        if (bin[2]=="1") {
            two.setBackgroundResource(R.drawable.onn);
        }
        else if(bin[2]=="0"){
            two.setBackgroundResource(R.drawable.off);
        }
        if (bin[3]=="1") {
            three.setBackgroundResource(R.drawable.onn);
        }
        else if(bin[3]=="0"){
            three.setBackgroundResource(R.drawable.off);
        }
        if (bin[4]=="1") {
            four.setBackgroundResource(R.drawable.onn);
        }
        else if(bin[4]=="0"){
            four.setBackgroundResource(R.drawable.off);
        }
        if (bin[5]=="1") {
            five.setBackgroundResource(R.drawable.onn);
        }
        else if(bin[5]=="0"){
            five.setBackgroundResource(R.drawable.off);
        }   
    }
    private void init() {
        // TODO Auto-generated method stub
        for (int i = 0; i < 6; i++) {
            bin[i]="0";
        }
    }

    @Override
    protected void onResume() {
        //---register the receiver---
        registerReceiver(intentReceiver, intentFilter);
        super.onResume();
    }

    @Override
    protected void onPause() {
        //---unregister the receiver---
        unregisterReceiver(intentReceiver);
        super.onPause();
    }
}  

activity xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/back"
    tools:context="${relativePackage}.${activityClass}" >

    <Button
        android:id="@+id/one"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:background="@drawable/off"
        android:rotation="90" />

    <Button
        android:id="@+id/two"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_below="@+id/one"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:background="@drawable/off"
        android:rotation="90" />

    <Button
        android:id="@+id/three"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_below="@+id/two"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:background="@drawable/off"
        android:rotation="90" />

    <Button
        android:id="@+id/four"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_below="@+id/three"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:background="@drawable/off"
        android:rotation="90" />

    <Button
        android:id="@+id/five"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_below="@+id/four"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:background="@drawable/off"
        android:rotation="90" />

    <Button
        android:id="@+id/six"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_below="@+id/five"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:background="@drawable/off"
        android:rotation="90" />

    <Button
        android:id="@+id/refresh"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_marginBottom="19dp"
        android:layout_marginLeft="31dp"
        android:background="@drawable/button" />

    <Button
        android:id="@+id/update"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_marginBottom="69dp"
        android:layout_marginLeft="31dp"
        android:background="@drawable/button" />

</RelativeLayout>

Smsreceiver

package com.example.asd;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class SMSReceiver extends BroadcastReceiver
{
    @SuppressWarnings("deprecation")
    @Override
    public void onReceive(Context context, Intent intent)
    {
        //---get the SMS message passed in---
        Bundle bundle = intent.getExtras();
        SmsMessage[] msgs = null;
        String str = "";
        String[] bin=new String[6];
        if (bundle != null)
        {
            //---retrieve the SMS message received---
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];
            for (int i=0; i<msgs.length; i++){
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                str += msgs[i].getMessageBody().toString();
                bin[i]=msgs[i].getMessageBody().toString();

            }
            //---send a broadcast intent to update the SMS received in the activity---
            Intent broadcastIntent = new Intent();
            broadcastIntent.setAction("SMS_RECEIVED_ACTION");
            broadcastIntent.putExtra("zero", bin[0]);
            broadcastIntent.putExtra("one", bin[1]);
            broadcastIntent.putExtra("two", bin[2]);
            broadcastIntent.putExtra("three", bin[3]);
            broadcastIntent.putExtra("four", bin[4]);
            broadcastIntent.putExtra("five", bin[5]);
            broadcastIntent.putExtra("sms", str);

            context.sendBroadcast(broadcastIntent);
        }
    }
}

2 Answers2

1

You have to use

 if (bin[0].equals("1")) {
                zero.setBackgroundResource(R.drawable.onn);
            }
            else {
                zero.setBackgroundResource(R.drawable.off);
            }

because Strings will be compared with equals() method, not with ==

Also, You have to be sure that this String is not null if You get it from an intent. Like:

 bin[0]=intent.getStringExtra("zero");
 if(bin[0]!=null){


   //Your if/else statements

 }
Opiatefuchs
  • 9,800
  • 2
  • 36
  • 49
  • tried the .equals before it produced an error thats why i changed it to == however it does not produce an error with bin[0]!=null && bin[0].equalsIgnoreCase("1")) but the button image still doesnt change. – Incog Nito Mar 03 '16 at 08:57
  • are You sure the bin[0] is not null? Make some logs to be sure it is not null, it can also be an issue by passing the string via intent. – Opiatefuchs Mar 03 '16 at 08:59
  • nope im using a toast to see if theres value. And im sending it from ddms – Incog Nito Mar 03 '16 at 09:01
  • I do not see any toast in Your code, so You are 100% sure that the intent is not null? – Opiatefuchs Mar 03 '16 at 09:29
  • and have You registered Your receiver? Sorry, but there is so much what could going wring. Compairing with == was just one of it.... – Opiatefuchs Mar 03 '16 at 09:29
  • please post more code. Where is that receiver (in which class, activity etc.), where do You have registered the receiver, how do You get sure that the intent is not null. It´s important to see all the relevant code... – Opiatefuchs Mar 03 '16 at 09:31
  • posted it sorry for the incomplete info just thought ive narrowed the problem to that portion not only that my code is messy lol – Incog Nito Mar 03 '16 at 15:41
  • ok, I see You have a second BroadcastReceiver class. Is the SMS Receiver working? And if yes, until which point? Have You registered the sms receiver inside Your manifest? – Opiatefuchs Mar 04 '16 at 07:51
  • and what You are doing in Your init() method? – Opiatefuchs Mar 04 '16 at 07:54
  • ive registered the receiver on my manifest. Hmm i think its working since when i toast the received sms from the on receive it shows the right value. The init method is useless lol I'll be removing I placed it to see it would fix a toast that shows more than the specified amount , like it should only output 6 digits from bin[6] it would sometimes output more than that when i pressed one of the buttons after receiving an sms. Hence i just made use of the String upToNCharacters = s.substring(0, Math.min(s.length(), 6)); to check. – Incog Nito Mar 04 '16 at 08:58
  • a substring with 3 parameters? – Opiatefuchs Mar 04 '16 at 09:42
  • sorry dont understand what you mean – Incog Nito Mar 04 '16 at 10:01
  • sorry, I read that in the wrong way: String upToNCharacters = s.substring(0, Math.min(s.length(), 6)).....I had interpreted the second parameter of Math as the third one of substring...forget it, need some glasses :) – Opiatefuchs Mar 04 '16 at 10:17
  • so this discussion is too weird at this moment. Please let us focus on the real problem: You are not receiving Your broadcast at the intentReceiver in Your Mainactivity, right? Please do following: put Log.d("TEST","RECEIVED"); directly after onReceive and switch the filter in Your Logcat to "TEST". Then tell us if You receive this output in Your Logcat window..... – Opiatefuchs Mar 04 '16 at 10:26
  • 03-04 10:02:55.353: D/TEST(1176): RECEIVED. got this. Well the only issue I have is the if else statement anything that i place inside the if else statement dont work like the changing of the button background. But if i place zero.setBackgroundResource(R.drawable.onn); before the if else statement then it changes as soon as it receives an sms. thanks for taking the time to help appreciate it. – Incog Nito Mar 04 '16 at 15:05
  • OK, sorry for so much steps here, but we must get sure everything other works fine. The next thing is, are You sure You get Your string out of the intent? You should check via a Log if you get Your correct string out of the intent. Second: I have seen that inside Your click method for zero button, You have still used == instead of equals, you should change it, this could also be the cause.. – Opiatefuchs Mar 07 '16 at 06:46
  • also in Your updateBtn() method, You are using ==. Please go through Your code and change all compares of strings to equals()... – Opiatefuchs Mar 07 '16 at 06:50
  • Hi Ive solved the issue. The issue was in the smsreceiver.jave where I would send the intent bin[0]...bin[5] . The way I understood the for loop there was it was going to place a letter to bin[i] each time it loops when in fact it puts the whole message in bin[0] and skips the rest. Found this out when I just toasted bin[0] and was confused why it still toasted the whole text when it should have just outputed the first value. So what i did was just to extract each index of the string and put it to its respective variable and the if else statement worked. Anyhow thanks for helping – Incog Nito Mar 08 '16 at 02:01
  • glad it is resolved :).... – Opiatefuchs Mar 08 '16 at 06:46
0

Don't use == to compare String. You have to use equals or equalsIgnoreCase for compare String see developer doc for String and code looks like

       if (bin[0]!=null && bin[0].equalsIgnoreCase("1")) {
            zero.setBackgroundResource(R.drawable.onn);
        }
        else {
            zero.setBackgroundResource(R.drawable.off);
        }
Nils
  • 647
  • 6
  • 16
  • equalsIgnoreCase() usually correct, but it´s not important for compairing a number String – Opiatefuchs Mar 03 '16 at 08:29
  • tried the .equals before it produced an error thats why i changed it to == however it does not produce an error with bin[0]!=null && bin[0].equalsIgnoreCase("1")) but the button image still doesnt change. – Incog Nito Mar 03 '16 at 08:52
  • well first put log in if else block and check its print or not if yes then problem in your action in block..!!! – Nils Mar 03 '16 at 09:09
  • sorry not really familiar on how to use log in program – Incog Nito Mar 03 '16 at 15:54