I am trying to use Geocoder class in my App and found that Geocoder.getFromLocationName returns null if the address is intersection of two streets. Ex. "Quail Ave and Dunford Way, Sunnyvale, CA 94087" . However, the method works perfect for any other type address.
During Debug session, I could see the address parameter passed and reflects correctly, but "geocodeMatches" returns size(0) zero.
Appreciate any Help!!
public static List<Address> getGeoCode(#NonNull Context context, #NonNull String address){
try {
geocodeMatches = new Geocoder(context).getFromLocationName(address, 1);
if (!geocodeMatches.isEmpty())
{
return geocodeMatches;
}
} catch (IOException e) {
Log.e("ERROR", "Error to retrieve geocode" + e);
e.printStackTrace();
}
return geocodeMatches;
}
GeoCoder is working on NetworkLocationService. In some cases, NetworkLocationService is stopped working due to some reason. I don't know exact reason. But you can get address from google api in that case.
Hope below code will help you!
public static String GetLocationAddressFromLatLong(Context context, double latitude, double longitude) {
String finalAddress = "";
Geocoder geocoder;
List<Address> addresses = null;
geocoder = new Geocoder(context.getApplicationContext(), Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
finalAddress = addresses.get(0).getAddressLine(0) + ", " + addresses.get(0).getAddressLine(1);
} else {
//Get address from Google api
try {
JSONObject jsonObj = getJSONfromURL("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + ","
+ longitude + "&sensor=true");
String Status = jsonObj.getString("status");
if (Status.equalsIgnoreCase("OK")) {
JSONArray Results = jsonObj.getJSONArray("results");
JSONObject location = Results.getJSONObject(0);
finalAddress = location.getString("formatted_address");
}
} catch (Exception e) {
e.printStackTrace();
}
}
return finalAddress;
}
Related
String targetRptFile = System.getenv("LOCAL_BIRT_INPUT") + "/"+report.getMergeRptTemplates().getTargetTemplate()+".rptdesign";
String attachRptFile = System.getenv("LOCAL_BIRT_INPUT") + "/"+report.getMergeRptTemplates()
.getAttachTemplate()+".rptdesign";
DesignConfig dConfig = new DesignConfig();
IDesignEngineFactory factory = (IDesignEngineFactory) Platform.createFactoryObject(IDesignEngineFactory.EXTENSION_DESIGN_ENGINE_FACTORY);
IDesignEngine dEngine = factory.createDesignEngine(dConfig);
SessionHandle session = dEngine.newSessionHandle(null);
ReportDesignHandle targetRptDesignHandle = null;
ReportDesignHandle attachRptDesignHandle = null;
try {
targetRptDesignHandle = session.openDesign(targetRptFile);
attachRptDesignHandle = session.openDesign(attachRptFile);
} catch (DesignFileException e) {
e.printStackTrace();
}
OdaDataSourceHandle attachOdaDataSourceHandle = (OdaDataSourceHandle)attachRptDesignHandle.getAllDataSources()
.get(0);
targetRptDesignHandle.getAllDataSources().add(attachOdaDataSourceHandle);
String newTargetRptFile = System.getenv("LOCAL_BIRT_INPUT") + "/"+report
.getMergeRptTemplates().getTargetTemplate()+"-merge"+".rptdesign";
try {
targetRptDesignHandle.saveAs(newTargetRptFile);
targetRptDesignHandle.close();
attachRptDesignHandle.close();
session.closeAll(true);
} catch (IOException e) {
e.printStackTrace();
}
}
Never did this, but I remember a similar problem when I wanted to copy a JDBCDataSource. I worked around this by setting all the properties manually instead of trying to copy the whole DS.
I am working on location coordinates marking feature in the App.
I am using following dll's and google map.
Xamarin.Forms.Maps
Xam.Plugin.Geolocator
Xam.Plugin.ExternalMaps
In my iphone simulator, If the Location is NONE.It pulls default location some where in Rome, Italy
Following is the code written to pull the Map ..
public async Task<Xamarin.Forms.Maps.Position> GetPosition()
{
IsBusy = true;
Xamarin.Forms.Maps.Position p;
try
{
if (!locator.IsGeolocationAvailable)
{
p = new Xamarin.Forms.Maps.Position();
}
if (!locator.IsGeolocationEnabled)
{
p = new Xamarin.Forms.Maps.Position();
}
var position = await locator.GetPositionAsync(timeoutMilliseconds: 10000);
p = new Xamarin.Forms.Maps.Position(position.Latitude,position.Longitude);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
p = new Xamarin.Forms.Maps.Position();
}
IsBusy = false;
return p;
}
public async Task<object> GetCityName(double latitude, double longitude) {
HttpClient client;
client = new HttpClient();
client.MaxResponseContentBufferSize = 256000;
try
{
var response = await client.GetAsync("https://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
var json = Newtonsoft.Json.Linq.JObject.Parse(result);
var reValue = "" + json["results"][0]["formatted_address"];
var strArr = reValue.Split(',');
if (strArr.Length > 2)
return strArr[strArr.Length - 2] + ", " +strArr[strArr.Length - 1];
else
return "";
}
else {
Debug.WriteLine(#"Failed.");
return "Failed";
}
}
catch (Exception ex)
{
Debug.WriteLine(#"ERROR {0}", ex.Message);
return ex.Message;
}
}
Image :
elaborate your problem please, and change your conditions as follows:
if (CrossGeolocator.Current.IsGeolocationAvailable)
{
if (CrossGeolocator.Current.IsGeolocationEnabled)
{
var position = await locator.GetPositionAsync(timeoutMilliseconds: 10000);
p = new Xamarin.Forms.Maps.Position(position.Latitude,position.Longitude);
}
else
{
throw new Exception("Geolocation is turned off");
// Geolocation is turned off for the device.
}
}
else
{
throw new Exception("Geolocation is turned off");
// Geolocation not available for device
}
Here now Handle the catches from GetPosition() Method to make sure you don't get the default location.
How do I validate an email address?
An address should have a "# " and end ".com "
Here's the code I used:
public void email(){
String a = "qwertyuiopasdfghjklzxcqwertyuiopasdfghjklzxcvbnmvbnmqwertyuiopasdfghjklzxcvbnm#qwertyuiopasdfghjklzxcvbnmqwertyuiopaqwertyuiopasdfghjklzxcvbnmsdfghjklzxcvbnm.com";
String b = JOptionPane.showInputDialog("Enter email");
try{
if(!b.contains(a)){
throw new Error("Incorrect");
}else{
System.out.println("Correct");
}
} catch (Error e){
System.out.println(""+e);
}
}
I think this might help you. From: What is the best Java email address validation method?
public static boolean isValidEmailAddress(String email) {
boolean result = true;
try {
InternetAddress emailAddr = new InternetAddress(email);
emailAddr.validate();
} catch (AddressException ex) {
result = false;
}
return result;
}
In my app I need to download several images from a server. I use this code to get a byte array :
HttpConnection connection = null;
InputStream inputStream = null;
byte[] data = null;
try
{
//connection = (HttpConnection)Connector.open(url);
connection = (HttpConnection)Connector.open(url, Connector.READ_WRITE, true);
int responseCode = connection.getResponseCode();
if(responseCode == HttpConnection.HTTP_OK)
{
inputStream = connection.openInputStream();
data = IOUtilities.streamToBytes(inputStream);
inputStream.close();
}
connection.close();
return data;
}
catch(IOException e)
{
return null;
}
The url are formed with the suffix ";deviceSide=false;ConnectionType=MDS - public" (without spaces) and it is working perfectly well.
The problem is that with phones that do not have a sim card, we can't connect to the internet via the MDS server. So we changed to use the connection factory and let BB choose whatever he wants :
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(url);
if (connDesc != null)
{
final HttpConnection httpConn;
httpConn = (HttpConnection)connDesc.getConnection();
try
{
httpConn.setRequestMethod(HttpConnection.GET);
final int iResponseCode = httpConn.getResponseCode();
if(iResponseCode == HttpConnection.HTTP_OK)
{
InputStream inputStream = null;
try{
inputStream = httpConn.openInputStream();
byte[] data = IOUtilities.streamToBytes(inputStream);
return data;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
finally{
try
{
inputStream.close();
} catch (IOException e)
{
e.printStackTrace();
return null;
}
}
}
}
catch (IOException e)
{
System.err.println("Caught IOException: " + e.getMessage());
}
}
return null;
The connection works because it select the good prefix (interface=wifi in our case), but this create another problem.
Some images are not well downloaded, some of them (not the sames at each try) are corrupted, but only when the phone use a wifi connection to get these images.
How can I avoid this problem ? What method to get a connection do I have to use ? Is it possible to check if the user have a sim card in orderto use MDS - public ?
Here is an example of a corrupted image :
error image http://nsa30.casimages.com/img/2012/06/28/120628033716123822.png
try this:
public static String buildURL(String url) {
String connParams = "";
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
connParams = ";interface=wifi"; //Connected to a WiFi access point.
} else {
int coverageStatus = CoverageInfo.getCoverageStatus();
//
if ((coverageStatus & CoverageInfo.COVERAGE_BIS_B) == CoverageInfo.COVERAGE_BIS_B) {
connParams = ";deviceside=false;ConnectionType=mds-public";
} else if ((coverageStatus & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
// Have network coverage and a WAP 2.0 service book record
ServiceRecord record = getWAP2ServiceRecord();
//
if (record != null) {
connParams = ";deviceside=true;ConnectionUID=" + record.getUid();
} else {
connParams = ";deviceside=true";
}
} else if ((coverageStatus & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
// Have an MDS service book and network coverage
connParams = ";deviceside=false";
}
}
Log.d("connection param"+url+connParams);
//
return url+connParams;
}
private static ServiceRecord getWAP2ServiceRecord() {
String cid;
String uid;
ServiceBook sb = ServiceBook.getSB();
ServiceRecord[] records = sb.getRecords();
//
for (int i = records.length -1; i >= 0; i--) {
cid = records[i].getCid().toLowerCase();
uid = records[i].getUid().toLowerCase();
//
if (cid.indexOf("wptcp") != -1
&& records[i].getUid().toLowerCase().indexOf("wap2") !=-1
&& uid.indexOf("wifi") == -1
&& uid.indexOf("mms") == -1) {
return records[i];
}
}
//
return null;
}
What happens when you append interface=wifi? Can you run the network diagnostic tool attached to below kb article and run all tests with SIM removed
http://supportforums.blackberry.com/t5/Java-Development/What-Is-Network-API-alternative-for-legacy-OS/ta-p/614822
Please also note that when download large files over BES/MDS there are limits imposed by MDS. Please ensure you review the below kb article
http://supportforums.blackberry.com/t5/Java-Development/Download-large-files-using-the-BlackBerry-Mobile-Data-System/ta-p/44585
You can check to see if coverage is sufficient for BIS_B (MDS public) but that won't help you if you are trying to support SIM-less users. I wonder if the problem is in an incomparability between the connection on Wi-Fi and IOUtilities.streamToBytes(). Try coding as recommended in the API documents.
I have two classes. MetaDataExtractor(GUI) and MetaData.
MetaData has the method which extracts the metadata from an image. MetaDataExtractor is designed to display the data in a JTextPane. (Please excuse the class names. I know it's a little confusing. I'm fairly new to Java).
MetaDataExtractor:
LongitudeField.setText("" + MetaDataTags.getLongitude());
MetaData:
public String getLongitude() {
try {
Metadata metadata = ImageMetadataReader.readMetadata(jpegFile);
if (metadata.containsDirectory(GpsDirectory.class)) {
GpsDirectory gpsDir = (GpsDirectory) metadata.getDirectory(GpsDirectory.class);
GpsDescriptor gpsDesc = new GpsDescriptor(gpsDir);
String Longitude = "" + gpsDesc.getGpsLongitudeDescription();
}
} catch (ImageProcessingException ex) {
Logger.getLogger(MetaData.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error 1");
} catch (IOException ex) {
Logger.getLogger(MetaData.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error 2");
}
return longitude;
}
If I set the longitude to be displayed in the JTextPane, it returns "null". If however, I set it to print out on the command line, it prints the longitude fine?
Please excuse me if its a simple solution. I'm still getting to grips with Java.
Java is case sensitive and declare firstly your variable outside of try & catch statement.
Use a IDE like Eclipse to reduce syntax errors like these.
so you should have :
public String getLongitude() {
String longitudeDesc ="";
try {
Metadata metadata = ImageMetadataReader.readMetadata(jpegFile);
if (metadata.containsDirectory(GpsDirectory.class)) {
GpsDirectory gpsDir = (GpsDirectory) metadata.getDirectory(GpsDirectory.class);
GpsDescriptor gpsDesc = new GpsDescriptor(gpsDir);
longitudeDesc = "" + gpsDesc.getGpsLongitudeDescription();
}
} catch (ImageProcessingException ex) {
Logger.getLogger(MetaData.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error 1");
} catch (IOException ex) {
Logger.getLogger(MetaData.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error 2");
}
return longitudeDesc ;
}