-1

While comparing the content of sms with text, it's not working. Can any one please help me solve this? Here I want the count of a and b based on sms content. If sms content is a, it will give count 1. If another sms also has content a, then count must be incremented to 1 i.e., 2. Below is my code:

    package com.example.sms;

    import java.util.ArrayList;

    import android.app.Activity;
    import android.database.Cursor;
    import android.net.Uri;
    import android.os.Bundle;
    import android.widget.TextView;

    public class Sms extends Activity {
    int count=0;
    int count1=0;

      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_sms);
          TextView view1 = (TextView)findViewById(R.id.textview1);
          TextView view2 = (TextView)findViewById(R.id.textView2);
          Uri uriSMSURI = Uri.parse("content://sms/inbox");
          Cursor cur = getContentResolver().query(uriSMSURI, null, null, null,null);
          String sms = "";
          String data = null;
          while (cur.moveToNext()) {
              sms =cur.getString(12);

                  if(sms=="a"){
                      count=count+1;
                      view1.setText("a"+count+")");
                  }

                  else if(sms=="b"){
                      count1=count1+1;
                      view2.setText("a("+count+")");
                  }
                  else{
                      //view1.setText("no data");
                  }
              //data.add(cur.getString(12));
             // view1.setText(cur.getString(12));
          }

          //view1.setText(sms);
          //setContentView(view);
      }
    }
Brian
  • 1,184
  • 2
  • 21
  • 38
Honey
  • 3
  • 2

3 Answers3

3

The String class in Java is not a primitive type. Because of this, the == operator will not give you the results you expect- it will compare memory addresses, not the contents of the Strings.

You should use the equals() method of the String class to compare strings.

In this case, you would use:

if (sms.equals("a") {
    // ...
}
Bryan Herbst
  • 66,602
  • 10
  • 133
  • 120
3

Your comparison isn't working because you need to use .equals() to compare strings.

if (sms.equals("a")){
    count = count + 1;
    view1.setText("a" + count + ")");
}
else if (sms.equals("b")){
    count1 = count1 + 1;
    view2.setText("a(" + count + ")");
}
jonhopkins
  • 3,844
  • 3
  • 27
  • 39
-1

use .equals() instead of == for strings

Ahmad Dwaik 'Warlock'
  • 5,953
  • 5
  • 34
  • 56