Android cannot find string if its null - java

I want to send Emails using android intent. Every thing is working well except when choosing email app to send email with, in the send to field getting null value, although I check for null values but seems I cannot detect when a string is null. Can anybody help me solve this.
if (emailAddress[0]!=null && !emailAddress[0].isEmpty()) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_EMAIL, emailAddress);
intent.putExtra(Intent.EXTRA_SUBJECT,
getResources().getString(R.string.email_sub));
// intent.putExtra(Intent.EXTRA_TEXT, "I'm email body.");
startActivity(Intent.createChooser(intent, "Send Email"));

try to use this syntax its detect null and empty string
if(!TextUtils.isEmpty(emailAddress[0]))

Check the String with equals() or equalsingorecase();
String[] emailAddress = new String[10];
emailAddress[0]="asdfasdfasdfasdf";
if (emailAddress[0]!=null && !emailAddress[0].isEmpty())
{
System.err.println("asddddddd " +emailAddress[0] );
}

You can use TextUtils.isEmpty(CharSequence str) method to detect if String is empty or null

TextUtils.isEmpty(charSequence char) is used for null String if it don't work then check if(emailAddress != null) because emailAddress[0] position value is null then your array is also null.

it might help you..
you can use any from below 2
if (emailAddress[0].toString().equals(""))
or
if (emailAddress[0].toString().length() > 0)

The string may not be null. AFAIK Intent.EXTRA_EMAIL takes String array as second argument.
Try this.
String[] addressArray = {"add1#mail.com", "a2#mail.com"};
//some lines...
intent.putExtra(Intent.EXTRA_EMAIL, addressArray);

Related

how to wait for startActivityForResult to continue next line in android java

my code is below,
whenever salesmanName value is empty i am not getting Login success Log.
how to get that. after getting result i want to execute next line.
if(salesmanName=="" ||salesmanName==null) {
Intent intent1=new Intent(MainActivity.this,
com.example.mysouq.LoginActivity.class);
startActivityForResult(intent1,LOGIN);
}
Log.e("Login success",salesmanName);
Do not use == for Strings
String var = new String("");
""==var => false
use equals:
"".equals(var)
also
salesmanName will be empty in you last line

Android ACTION_SEND with special unicode characters

I am trying to send text using an intent. I thought it was straight-forward:
public Intent getIntent() {
final Intent intent = new Intent();
intent.setComponent(new ComponentName(packageName, ri.activityInfo.name));
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, getText());
return intent;
}
private String getText(){
// the emoji can be one of many. I removed all that for brevity
final int unicode = 0x1F3C5;
final String emoji = String.valueOf(Character.toChars(unicode));
// final String emoji = "\n1F3C5"; //didn't work either
// I also tried using HTML here but I think I have some wires crossed, so I am not ruling that out yet
return textPartOne + " " + emoji + " " + textPartTwo;
}
As you can see, the EXTRA_TEXT has a special character in it (an emoji). When the text sends from device A the emoji appears like I expect in the message. But on device B (the receiver) the text shows some madness (usually in two different messages):
#.£¡ù¿ ¡ ¡ | | < | | | \ < | [ ¡ { ¡ [ ¡
#H£(ù#æ#a#¤¥¡
¡9#ü#Hù#Θ#=#ø¥p
¡6#Ö#Δì¿ ¡ |
It doesn't matter if I send the message from device A to device B or B to A. I get the same results either way, so I believe it isn't an issue with the emoji not being supported.
Now, if I remove all but the emoji code:
Xäx&
If I remove the emoji code altogether it works like a charm.
But the client has gotta have those emojis...
😤
Some other things that may be of note:
I am using this to manage what intents I am presenting to the user. They could pick MMS, email, Twitter, Facebook or whatever really. I need to support all of these
I am getting the special characters from Emojipedia
I am not displaying the emojis anywhere in the app. They will be shown in Text message, Email, or Facebook/Twitter feed.
There is already an iOS variant of this app who is successfully doing this.
I have tried nearly a dozen different ways with no avail.
Is there anyone that may have some insight on how to properly send special characters?
Edit:
As you can see, I am sending the emoji I desire. But the result is far from what I expect. This is a screenshot of an emulator sending a text to itself.
Here are some of the ways I have tried
String attempt1 = "--";
try {
attempt1 = Html.fromHtml(new String("&#x1F3C5".getBytes("UTF-8"))).toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
final int codePoint = 0x26F7;
final String attempt2 = new String(new int[]{codePoint}, 0, 1);
final String attempt3 = new String(Character.toChars(codePoint));
final String attempt4 = "\u26F7";
All result in:
&n
If I add text to these:
final String attempt4 = "COME ON: \u26F7";
I get this:
#Σ£(ù#æ#s##£ Å¡7#X£¿ù¿
Which makes total sense he said sarcastically
You can use intents, which are messages sent between activities. In a intent you can put all sort of data, String, int, etc.
In your case, in activity2, before going to activity1, you will store a String message this way :
Intent intent = new Intent(activity2.this, activity1.class);
intent.putExtra("message", getText());
startActivity(intent);
In activity1, in onCreate(), you can get the String message by retrieving a Bundle (which contains all the messages sent by the calling activity) and call getString() on it :
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
Then you can set the text in the TextView:
TextView txtView = (TextView) findViewById(R.id.your_resource_textview);
txtView.setText(message);
Hope this helps !

Intent.getStringExtra("key") returning null

I've looked at other people's issues on this same subject and haven't been able to solve the issue. The code on my main activity looks like this:
Intent i = new Intent(getApplicationContext(), ResultsActivity.class);
startActivity(i);
i.putExtra("dob", dobStr);
i.putExtra("gender", gender);
dobStr and gender are both strings (I have tested this by replacing dobStr with an actual string with quotes). My second activity is named ResultsActivity.
My second activity has this:
Intent i = getIntent();
String dob = i.getStringExtra("dob");
String gender = i.getStringExtra("gender");
but dob and gender are both null.
Can someone help me figure out the issue?
Try to invoke startActivity after the two putExtra calls.

How to open Google Maps using address?

How can I open Google Maps(using Intents or adding Google Maps into my application) with address? I have the address, but I don't have latitude/longitude. How can I do it? Thank you.
use below code,
String map = "http://maps.google.co.in/maps?q=" + str_location;
// where str_location is the address string
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(map));
startActivity(i);
From my personal Code Library. ;)
public static Intent viewOnMap(String address) {
return new Intent(Intent.ACTION_VIEW,
Uri.parse(String.format("geo:0,0?q=%s",
URLEncoder.encode(address))));
}
public static Intent viewOnMap(String lat, String lng) {
return new Intent(Intent.ACTION_VIEW,
Uri.parse(String.format("geo:%s,%s", lat, lng)));
}
String geoUri = "http://maps.google.com/maps?q=loc:" + addressName;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(geoUri));
context.startActivity(intent);
Change the bold part of this URL to your company address. It's best if you replace all spaces with a plus (+) character, but should work with spaces too:
http://maps.google.com/maps/geo?q=620+8th+Avenue,+New+York,+NY+10018,+USA&output=csv&oe=utf8&sensor=false
Raise a request to above URL. For more information refer http://androidadvice.blogspot.in/2010/09/asynchronous-web-request.html
This will generate a code that looks something like this:
200,8,40.7562008,-73.9903784
The first number, 200, says that the address is good. The second number, 8, indicates how accurate the address is. The last two numbers, 40.7562008 and -73.9903784, are the latitude and longitude of this address. Use these to get your google map working.
Note : The above steps have been copied from http://webdesign.about.com/od/javascript/ss/add-google-maps-to-a-web-page_2.htm
You can use Google Geocoding API, which converts your physical address into latitude and longitude. API returns it into XML or JSON format. You just need to parse the data to get latitude and longitude. After receiving latitude and longitude you can load it on mapview.
Geocoding api link :
https://developers.google.com/maps/documentation/geocoding/
Hope this helps.
As of 2017 the recommended by Google approach is using the Google Maps URLs API that provides universal cross-platform URLs. You can use these URLs in your intents.
Example of such URL from the documentation:
https://www.google.com/maps/search/?api=1&query=centurylink+field
Hope this helps!
Little late to the party. I prefer #st0le's answer but URLEncoder.encode(String s) is deprecated as of API 16. You need to pass a second argument as well. Check the answer below.
public static Intent viewOnMapA(String address) {
try {
return new Intent(Intent.ACTION_VIEW,
Uri.parse(String.format("geo:0,0?q=%s",
URLEncoder.encode(address, "UTF-8"))));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
From the current documentation
https://developers.google.com/maps/documentation/urls/get-started
It is better to use
https://www.google.com/maps/dir/?api=1&query=address
so:
val address = "some address"
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com/maps/dir/?api=1&query=$address"))
startActivity(intent)

Match number to contact in android app

Have an android app that prints with a toast pop up, and reads out a received message with tts. I use "String origin = smsMessage[0].getOriginatingAddress();" to get the phone number of the sender.
I want to query the contacts list on the phone, so if the received number matches any contacts, it will print & read out the name of the sender instead. Otherwise, if the number is not recognised, it will default back to just printing & reading the OriginatingAddress number.
Iv'e looked at How can I query Android contact based on a phone number? - but not quite sure howto go about it.
Uri phoneUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(origin));
Cursor phonesCursor = context.getContentResolver().query(phoneUri, new String[] {PhoneLookup.DISPLAY_NAME}, null, null, null);
if(phonesCursor != null && phonesCursor.moveToFirst()) {
displayName = phonesCursor.getString(0); // this is the contact name
}//end if
Go this eventually.
That question had the answer and posted the code.
Uri phoneUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(mNumber));
Cursor phonesCursor = managedQuery(phoneUri, new String[] {PhoneLookup.DISPLAY_NAME}, null, null, null);
if(phonesCursor != null && phonesCursor.moveToFirst()) {
String displayName = phonesCursor.getString(0); // this is the contact name

Categories

Resources