Im new to programming, so bear with me. After following a couple of tutorials i made an SMS application, i want to do an specific task when a specific text is received, i do this by comparing the text received to a value(code) that i already declared. The problem is that this condition never ocurrs.
public class SmsReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
String code = "blue";
String conf = "Ok";
String inv = "Invalid";
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();
//n = Integer.parseInt(str);
}
if (str == code)
Toast.makeText(context, conf, Toast.LENGTH_SHORT).show();
else
//str = Integer.toString(n);
//Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
Toast.makeText(context, inv, Toast.LENGTH_SHORT).show();
}
}
}
When I send the message it always displays the inv variable (Invalid). I tried to change the "code" variable to an integer, and then parse the string so I could compare it; in this scenario it did work, but whenever I received a string message the application crashes. I think it should be a simple thing, but since i don't fully understand java i can't figure it out.
I hope you could provide me with some guidelines or suggestions about what could i do.
Thanks in advance.
When comparing two strings, you should be using:
if (str.equals(code))
Java does not override the equals operator for string equality testing like it does for concatenation.
The test str == code only evaluates to true if the two String variables both refer to the EXACT same object in memory.
String str1 = "hello";
String str2 = "world";
if (str1 == str2) // not applicable for strings, can be use for integers
if (str1.equals(str2)) // applicable for strings
if (str1.compareTo(str2) > 0) // applicable for strings
Related
When exporting my array list item, Im getting this error. In the first place it works but when updating my code adding data on my array it crashed my app and this error appear, do you have any idea why this happening?
java.lang.ClassCastException: android.text.SpannableStringBuilder
cannot be cast to java.lang.String
I'm getting error in this line 312 after if statement -
mEdit1.putString("Status_" + i,list_items.get(i));
I've already tried put empty string on my list like this
""+list_items.get(i));
but it's not working :(
ArrayList<String> list_items = new ArrayList<String>(); //declared global
ArrayAdapter arrayAdapter; //declared global
public boolean export_data()
{
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor mEdit1 = sp.edit();
mEdit1.putString("Status_","");
mEdit1.apply();
mEdit1.putInt("Status_size", list_items.size());
for(int i=0;i<list_items.size();i++)
{
mEdit1.remove("Status_" + i);
if (list_items.get(i) !=null){
mEdit1.putString("Status_" + i,list_items.get(i));
String[] separated = list_items.get(i).split(":");
mEdit1.putString("Status_" + i, separated[0]);
}
else{
Toast.makeText(getApplicationContext(), "List is Empty", Toast.LENGTH_SHORT).show();
}
}
return mEdit1.commit();
}
Adding item on ArrayAdapter
public void refreshInbox(){
arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list_items);
ContentResolver cResolver = getContentResolver();
Cursor smsInboxCursor = cResolver.query(Uri.parse("content://sms/inbox"),null,null,null,"date desc");
int indexBody = smsInboxCursor.getColumnIndex("body");
if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return;
do{
String strbody = smsInboxCursor.getString( smsInboxCursor.getColumnIndex("body") );
if(strbody.contains("Notifier,") && strbody.contains(":")){
System.out.println ( strbody );
String str = strbody;
String[] separated = str.split(",");
String separate = separated[1];
String[] sep = separate.split(" : ");
String sep1 = sep[1];
String finals = separate.replace(sep1, "<u>"+"<b>" + sep1 +"<b>"+ "</u>");
arrayAdapter.add(Html.fromHtml(finals));
}
else if(strbody.contains("Notifier,") && !strbody.contains(":")){
System.out.println ( strbody );
String str = strbody;
String[] separated = str.split(",");
String separate = separated[1];
arrayAdapter.add(separate);
}
}while (smsInboxCursor.moveToNext());
}
Assuming you want to keep displaying HTML in your list view, the problem is that the objects that ArrayAdapter is adding list_items are not Strings. That means, you have to change how you define the list_items variable from String to a more generic character sequence type:
ArrayList<CharSequence> list_items = new ArrayList<>();
The CharSequence interface does not have a "split" method though. To be able to use "split", you'll need to call toString to get a regular string:
String[] separated = list_items.get(i).toString().split(":");
It would also help if you used the type parameter with your ArrayAdapter. Using the type parameter would have made it harder (if not impossible) to make this mistake.
ArrayAdapter<CharSequence> arrayAdapter;
... inside the method ...
arrayAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1, list_items);
list_items.get(i));
Looks like you might be attempting to put an unusual type of string into the list...
see: java.lang.ClassCastException: android.text.SpannableString cannot be cast to java.lang.String
I'm not an android dev but I suspect there are some "useful" shortcuts it provides in an attempt to make your life easier, that would probably trip you up.
Groovy's default string was a GString rather than a String. That tripped me up a number of times before I got used to it.
The error is with this line in refreshInbox()
arrayAdapter.add(Html.fromHtml(finals));
Html.fromHtml does't return String but instead it retuns Spanned
But you need to pass String to add() on adapter
To fix this convert it to String
adapter.add(Html.fromHtml(finals).toString()); // this will return plain text without html tags
or
adapter.add(finals); // this will be having HTML tags from this you can set text on views later
I have an activity 'B'. I have 2 more activities A and C. Both the activities lead to B. But i pass different Data from A and C. So while fetching
String dataFromA = getIntent.getStringExtra("SomethingA");
String dataFromC = getIntent.getStringExtra("SomethingC");
How to not get an error. I wont know from where the user is getting to activity B So how do i add an If statement or seomthing to not get an error while fetching as Either line A or C will get a NullPOinterException
You can use hasExtra method to check if that String exists.
if (getIntent().hasExtra("SomethingA")) {
String dataFromA = getIntent.getStringExtra("SomethingA");
} else if (getIntent().hasExtra("SomethingC")) {
String dataFromC = getIntent.getStringExtra("SomethingC");
}
You can try this code.
Bundle arguments = getArguments();
if (arguments != null){
if (arguments.containsKey("SomethingA")) {
String somethingA = arguments.getString("SomethingA");
if (TextUtils.isEmpty(somethingA)){
// Your codes comes here
}
}
}
Bundle (arguments) can be null if there is no data passed.
To check if string is empty or not use below code :
if(TextUtils.isEmpty(yourString))
{
// String empty
}
else
{
// string not empty
}
In your case you check it as :
if (getIntent()!=null && getIntent().getStringExtra!=null )
{
if (getIntent().hasExtra("SomethingA") && getIntent().hasExtra("SomethingB"))
String dataFromA = getIntent.getStringExtra("SomethingA");
String dataFromB = getIntent.getStringExtra("SomethingB");
}
I have three activities A,B and C
In my B activity I have one imageview, when I get a String from activity A to B, the imageview should be visible.
When I get a String from activity C to B then the imageview should not be visible.
//From activity A
Intent iin= getIntent();
Bundle b = iin.getExtras();
//From Activity C
Intent i2=getIntent();
Bundle abcd=i2.getExtras();
if(b!=null)
{
String j =(String) b.get("arrowvisi");
Toast.makeText(getApplicationContext(), j, Toast.LENGTH_LONG).show();
if(j==b.get("arrowvisi"))
{
img_back.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Operational arrow visible", Toast.LENGTH_LONG).show();
}
else
{
if(abcd!=null)
{
String jst =(String) abcd.get("arrow_val");
if(jst==abcd.get("arrow_val"))
{
img_back.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "scan dispatch visble", Toast.LENGTH_LONG).show();
}
else
{
//img_back.setVisibility(View.GONE);
System.out.println("from scan dispatch");
Toast.makeText(getApplicationContext(), "scan dispatch not visible", Toast.LENGTH_LONG).show();
}
}
Toast.makeText(getApplicationContext(), "Operational not visible", Toast.LENGTH_LONG).show();
}
}
Replace
String j = (String) b.get("arrowvisi");
with
String j = b.getString("arrowvisi");
and
String jst = (String) abcd.get("arrow_val");
with
String jst = abcd.getString("arrow_val");
also string comparison should be like
j.equals(b.getString("arrowvisi")) // change again
and
jst.equals(abcd.getString("arrow_val")) // change again
So, the final ans should be something like
//From activity A
Intent iin = getIntent();
Bundle b = iin.getExtras();
//From Activity C
Intent i2 = getIntent();
Bundle abcd = i2.getExtras();
if(b != null){
String j = "String to check"; // Replace content inside "" with your string
Toast.makeText(getApplicationContext(), j, Toast.LENGTH_LONG).show();
if(j.equals(b.getString("arrowvisi"))){
img_back.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Operational arrow visible", Toast.LENGTH_LONG).show();
}else{
if(abcd != null){
String jst = "String to check"; // Replace with string you want to check
if(jst.equals(abcd.getString("arrow_val"))){
img_back.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "scan dispatch visble", Toast.LENGTH_LONG).show();
}else{
//img_back.setVisibility(View.GONE);
System.out.println("from scan dispatch");
Toast.makeText(getApplicationContext(), "scan dispatch not visible", Toast.LENGTH_LONG).show();
}
}
Toast.makeText(getApplicationContext(), "Operational not visible", Toast.LENGTH_LONG).show();
}
}
Also note that, doing something like
String jst = abcd.getString("arrow_val"));
if(jst.equals(abcd.getString("arrow_val"))) // this will be always true
this, will result in if statement being always true.
2 options :
1) Remove if statement because always true.
2) change String jst = "Some string to compare" (change this) and now compare jst with getString("arrow_val") using jst.equals(abcd.getString("arrow_val")) in your if loop
change this
String j = (String) b.get("arrowvisi");
with
String j = b.getString("arrowvisi");
and
String jst = (String) abcd.get("arrow_val");
with
String jst = abcd.getString("arrow_val");
also put this in bracket()
b.get("arrowvisi")
abcd.get("arrow_val")
First of all,to compare strings in java,you need to use .equals
so change
if(j==b.get("arrowvisi"))
to
if(j.equals(b.getString("arrowvisi")))
and
if(jst==abcd.get("arrow_val"))
to
if(jst.equals(abcd.getString("arrow_val")))
And second,your condition always will be true,because you are comparing two equal values always,i.e. first getting value in jst and then comparing same value.
Edit : to resolve null pointer change
String j =(String) b.get("arrowvisi");
to
String j = b.getString("arrowvisi");
and
String jst =(String) abcd.get("arrow_val");
to
String jst =abcd.getString("arrow_val");
And post logcat exception.
I'm making a j2me Bluetooth application. I'm also new in java world. Where I have to display a Bluetooth service name to the user. So far it seems all is working correctly except service name. I verified my Bluetooth server is advertising service name correctly by other client (done by qt). I tried as follows:-
public void commandAction(Command command, Item item) {
if (item == deviceChoiceGroup) {
if (command == servicesDiscoverCommand) {
if(deviceList.size()==0) {
return;
}
UUID[] searchList = new UUID[1];
searchList[0] = new UUID("11111111111111111111111111111111",false);
int[] attrSet = new int[1];
attrSet[0] = 0x100;
RemoteDevice currentDevice =
(RemoteDevice) deviceList.elementAt(
getDeviceChoiceGroup().getSelectedIndex());
if(currentDevice == null) {
return;
}
try {
transactionID = bluetoothDiscoveryAgent.searchServices(
new int[] {0x100}, searchList, currentDevice, this);
printToForm("Start services under L2CAP searching...");
form.addCommand(cancelServicesDiscoverCommand);
} catch (BluetoothStateException e) {
//TODO: write handler code
}
}
}
}
public void servicesDiscovered(int transID, ServiceRecord[] serviceRecords){
if (serviceRecords.length>0 && serviceRecords!=null)
{
connectionURL=serviceRecords[0].getConnectionURL(0, false);
int[] ids=serviceRecords[0].getAttributeIDs();
DataElement ServiceName=serviceRecords[0].getAttributeValue(ids[1]);
// tried to convert objedct to string.
String str = (ServiceName.getValue()).toString();
// out is put is like java.util.vector$1#3c60cd14c
printToForm("#Service name: "+str);
printToForm("The Service name is: "+ServiceName.getValue());
}
}
"DataElement.getValue()" which returns object. Thus I can see service name as "java.util.vector$1#3c60cd14c". I tried to convert object to string as "String str = (ServiceName.getValue()).toString();" It doesn't convert correctly.
So how to convert object to string. So that I could see the service name in plain text. Thanks!
By seeing the result : java.util.vector$1#3c60cd14c i guess the returned object's type is Vector.
So try to cast to the Vector and iterate through it to get the values.
Iterator itr = serviceName.getValue().iterator();//do something here
System.out.println("Iterating through Vector elements...");
while(itr.hasNext())
System.out.println(itr.next());
i have a simple doubt in android programming. I am not familiar with java coding.so it might be a simple problem.
In the first two lines I am retrieving an array, which i passed from another activity to this activity...Then i am creating an array list . I am creating an object in the 4th line. Now comes the problem ...
I have to run a for loop to get the url value, which i have to pass it in the BaseFeedParser class. but i cant use the 4th line, i.e creating the object inside the loop because it will create a new object each time... which should not happen ... how can i fix this probelm?
Intent myintent = getIntent();
String[] ActiveURL = myintent.getStringArrayExtra("URL");
List<String> titles = new ArrayList<String>();
BaseFeedParser parser = new BaseFeedParser(url);
// fetching all active URLs
for (int i = 0; i < ActiveURL.length + 1; i++) {
url = ActiveURL[i];
messages.addAll(parser.parse());
}
// now getting the titles out of the messages for display
for (Message msg : messages) {
titles.add(msg.getTitle());
}
Thanks in advance ...
There are some problems in your java code :
Intent myintent = getIntent();
//variables are named in camel case, starting with a lower case letter
String[] activeURL = myintent.getStringArrayExtra("URL");
List<String> titles = new ArrayList<String>();
//we will use parser later, see below
//BaseFeedParser parser = new BaseFeedParser(url);
// fetching all active URLs
//it's very easy to loop through a table in java / C / C++
//learn the pattern, it's the simplest, you got confused with the final index
for (int i = 0; i < activeURL.length ; i++) {
//here you don't change the former object url was referencing,
//you are saying that you give the name url to another object in the array
//it doesn't create any new item, change giving them a name to use them
url = activeURL[i];
//create a new parser for each url, except if they can be recycled
//i.e they have a property setUrl
messages.addAll( new BaseFeedParser(url).parse());
}
// now getting the titles out of the messages for display
for (Message msg : messages) {
titles.add(msg.getTitle());
}
Indeed, you could even shorten the whole thing by
Intent myintent = getIntent();
String[] activeURL = myintent.getStringArrayExtra("URL");
List<String> titles = new ArrayList<String>();
// fetching all active URLs
//use a for each loop
for ( String url : activeURL ) {
//loop through messages parsed from feed to add titles
for (Message msg : new BaseFeedParser(url).parse() ) {
titles.add(msg.getTitle());
}
}
if you don't need the List of Message you called messages.