List isn't populating - java

I'm making an app that will list addresses nearby in a listview, but for some reason the addresses aren't going into the list. Am I missing something with the address collection or?...
It happens within the for loop. I want it to read the list of addresses I get and trim the information I want to only necessary bits, like street numbers and zip codes instead of the big mess of numbers.
Every time I run the app however, the list remains blank.
package com.atonea.ps;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class PSActivity extends Activity {
protected static final Location Location = null;
/** Called when the activity is first created. */
String location_text="";
String here="";
final ArrayList<String> addressbook = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button goButton = (Button) findViewById(R.id.beginButton);
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
Criteria crta = new Criteria();
crta.setAccuracy(Criteria.ACCURACY_FINE);
crta.setAltitudeRequired(false);
crta.setBearingRequired(false);
crta.setCostAllowed(true);
crta.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(crta, true);
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
goButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void updateWithNewLocation(Location location) {
String latLong;
TextView uhoh = (TextView) findViewById(R.id.texty);
ListView listview = (ListView) findViewById(R.id.listview1);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, addressbook);
listview.setAdapter(arrayAdapter);
String addressString = "no address found";
Address fulladdress;
String street;
String zip;
String addresstogether;
if(location!=null) {
double lat = location.getLatitude();
double lon = location.getLongitude();
latLong = "Lat:" + lat + "\nLong:" + lon;
double lattitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder gc = new Geocoder(this,Locale.getDefault());
try {
List addresses= gc.getFromLocation(lattitude, longitude, 1);
if(addresses.size()>0) {
for (int a = 0; a > 6; a++) {
fulladdress = ((Address) addresses.get(a));
street = fulladdress.getAddressLine(a);
zip = fulladdress.getPostalCode();
addresstogether = street+" "+zip;
addressbook.add(a, addresstogether);
arrayAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(),addresstogether, Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
}
} else {
latLong = " NO Location Found ";
}
uhoh.setText("your Current Position is :\n" +latLong + "\n " + addressString );
}
}

for (int a = 0; a > 6; a++) {
You are never going to enter this loop. You start with 0 which is always smaller than 6.

This condition for (int a = 0; a > 6; a++) is not correct.
As you have initialized a with 0 and then checking a > 6 it will always be false and your program will never get in the loop.
It must be for (int a = 0; a < 6; a++).

Related

How to get latitude and longitude separately in 2 textviews in android studio JAVA?

from this i'm getting latitude and longitude in a single textview. But I want the latitude to be in 1 textview and longitude in another text view. Please help me on this.
My main activity
package com.shopping.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Button addressButton;
TextView addressTV;
TextView latLongTV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addressTV = (TextView) findViewById(R.id.addressTV);
addressButton = (Button) findViewById(R.id.addressButton);
addressButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditText editText = (EditText) findViewById(R.id.addressET);
String address = editText.getText().toString();
GeocodingLocation locationAddress = new GeocodingLocation();
locationAddress.getAddressFromLocation(address,
getApplicationContext(), new GeocoderHandler());
}
});
}
private class GeocoderHandler extends Handler {
#Override
public void handleMessage(Message message) {
String locationAddress;
switch (message.what) {
case 1:
Bundle bundle = message.getData();
locationAddress = bundle.getString("address");
break;
default:
locationAddress = null;
}
latLongTV.setText(locationAddress);
}
}
}
my geocodinglocation class.java
package com.shopping.myapplication;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class GeocodingLocation {
private static final String TAG = "GeocodingLocation";
public static void getAddressFromLocation(final String locationAddress,
final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override
public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List
addressList = geocoder.getFromLocationName(locationAddress, 1);
if (addressList != null && addressList.size() > 0) {
Address address = (Address) addressList.get(0);
StringBuilder sb = new StringBuilder();
sb.append(address.getLatitude()).append("\n");
sb.append(address.getLongitude()).append("\n");
result = sb.toString();
}
} catch (IOException e) {
Log.e(TAG, "Unable to connect to Geocoder", e);
} finally {
Message message = Message.obtain();
message.setTarget(handler);
if (result != null) {
message.what = 1;
Bundle bundle = new Bundle();
result = "Address: " + locationAddress +
"\n\nLatitude and Longitude :\n" + result;
bundle.putString("address", result);
message.setData(bundle);
} else {
message.what = 1;
Bundle bundle = new Bundle();
result = "Address: " + locationAddress +
"\n Unable to get Latitude and Longitude for this address location.";
bundle.putString("address", result);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
}
from this i'm getting latitude and longitude in a single textview. But I want the latitude to be in 1 textview and longitude in another text view. Please help me on this.
Please correct me if I'm wrong, but it appears that you are getting lat long as a single string for the address. Inside run() method for the thread, there are these lines:
sb.append(address.getLatitude()).append("\n");
sb.append(address.getLongitude()).append("\n");
result = sb.toString();
As you can see, you can get latitued and longitude from the address object here directly! There are many ways you can go about this. You can stick the lat and long values into the bundle if you wish. According to documentation, getLatitude() and getLongitude() return double:
public double getLatitude()
You could try putting the values independantly into the bundle, and give them appropriate keys. Or, if you don't want to mess with the geo code, you could in onCreate() method simply do:
String address = editText.getText().toString();
String[] values = address.split("\\n"); //we know that we need to split by \\n because we did sb.append(address.getLatitude()).append("\n")
//N.b: make sure to include \\n double backslash!
String lat = values[0];
String long = values[1];
Hope this helps! Please let me know if this works :D
EDIT: I have tried implementing it myself and it seems to work no problem! Here is a screenshot:
Here is main activity:
import androidx.appcompat.app.AppCompatActivity;
import android.location.Address;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Button addressButton;
TextView addressTV;
TextView latTV;
TextView longTV;
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addressTV = findViewById(R.id.addressTV);
latTV = findViewById(R.id.latTV);
longTV = findViewById(R.id.longTV);
addressButton = findViewById(R.id.addressButton);
editText = (EditText) findViewById(R.id.addressET);
addressButton.setOnClickListener(arg0 -> {
String address = editText.getText().toString();
GeocodingLocation locationAddress = new GeocodingLocation();
locationAddress.getAddressFromLocation(address,
getApplicationContext(), new GeocoderHandler());
});
}
private class GeocoderHandler extends Handler {
#Override
public void handleMessage(Message message) {
switch (message.what) {
case 1:
Bundle bundle = message.getData();
Address address = bundle.getParcelable("address");
latTV.setText(address.getLatitude()+"");
longTV.setText(address.getLongitude()+"");
break;
case 2:
addressTV.setText("unable to get address");
}
}
}
}
Notes: I simplified some things here for you, but its essentially the same. Important point however is that you can stick Parcable objects directly into the bundle, and since Address objects are Parcable, you can put the Address object directly into the bundle!
Here is the geo coding location class:
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class GeocodingLocation {
private static final String TAG = "GeocodingLocation";
public static void getAddressFromLocation(final String locationAddress,
final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override
public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
Message message = Message.obtain();
message.setTarget(handler);
try {
List addressList = geocoder.getFromLocationName(locationAddress, 1);
if (addressList != null && addressList.size() > 0) {
Address address = (Address) addressList.get(0);
message.what = 1;
Bundle bundle = new Bundle();
bundle.putParcelable("address", address);
message.setData(bundle);
}
} catch (IOException e) {
Log.e(TAG, "IOException", e);
message.what = 2;
}
message.sendToTarget();
}
};
thread.start();
}
}
Note: here I simplified your code a little bit also. Personally (and I think most people will agree), I like to code in a way that uses least indentations, but is still interpretable. Instead of doing try catch finally I just placed the correct pieces of code in try and catch separately, so there is no longer the need for finally clause at all.
Before you had a message with address string, and in the catch clause you would put the string "unable to get address for location" into bundle with key "address":
Bundle bundle = new Bundle();
result = "Address: " + locationAddress +
"\n\nLatitude and Longitude :\n" + result;
bundle.putString("address", result);
The result string doesn't contain an address, but rather an error message, so its probably not a good idea to put it in bundle with "address" key (because its an error message). I did it slightly differently, I set message.what property to message.what = 2;, and made that a case in the switch inside the main activity.
I hope this helps you further! :D

Adding array-lists content to a Text View giving empty text

I am trying to display the phone numbers of each card inserted in a phone via an app that I am creating as follows
mSubscriptionManager = SubscriptionManager.from(context);
GetCarriorsInformation();
number = findViewById(R.id.phone_numbers);
for (int i=0; i < Numbers.size(); i++){
number.append(number.getText() + Numbers.get(i) + " , ");
}
This is after getting the phone numbers and adding each to the arraylist as shown bellow
private void GetCarriorsInformation() {
Numbers = new ArrayList<>();
subInfoList = mSubscriptionManager.getActiveSubscriptionInfoList();
if (subInfoList.size() > 1) {
isMultiSimEnabled = true;
}
for (SubscriptionInfo subscriptionInfo : subInfoList) {
Numbers.add(subscriptionInfo.getNumber());
}
}
This runs without errors but and the textView only shows ''
What could I be doing wrong?
Here is the enttire MainActivity.java code
package com.otemainc.securesoccialmedia;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Context context;
private SubscriptionManager mSubscriptionManager;
public static boolean isMultiSimEnabled = false;
public static String defaultSimName;
public static List<SubscriptionInfo> subInfoList;
public static ArrayList<String> Numbers;
TextView number;
#TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
mSubscriptionManager = SubscriptionManager.from(context);
GetCarriorsInformation();
number = findViewById(R.id.phone_numbers);
for(int i=0; i < Numbers.size(); i++) {
number.append(number.getText() + Numbers.get(i) + " , ");
}
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
private void GetCarriorsInformation() {
Numbers = new ArrayList<>();
subInfoList = mSubscriptionManager.getActiveSubscriptionInfoList();
if (subInfoList.size() > 1) {
isMultiSimEnabled = true;
}
for (SubscriptionInfo subscriptionInfo : subInfoList) {
Numbers.add(subscriptionInfo.getNumber());
}
}
}
I have also added this line to the manifest file
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Try putting a breakpoint there to check if there are any values in subscriptionInfo. Otherwise try using:
Numbers.add(String.valueOf(subscriptionInfo.getNumber()));

How to save my ListView when app closes

I've tried using both SharedPrefrences and also saving to internal storage but I cannot get the results I want. The only results I have achieved are crashes.
I have an app that generates a custom password based on user options, it then enters those password into an Arraylist if the user clicks a button to save the password. However, when the app closes all data is lost.
How do I save the populated ArrayList or ListView so when the user clicks views passwords they can see their previously saved passwords?
* MAIN ACTIVITY JAVA *
package com.jrfapplications.passgen;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import static com.jrfapplications.passgen.SettingsPage.CustPass;
import static com.jrfapplications.passgen.SettingsPage.FBPass;
import static com.jrfapplications.passgen.SettingsPage.custword;
import static com.jrfapplications.passgen.SettingsPage.custwordend;
import static com.jrfapplications.passgen.SettingsPage.isEndWordChecked;
import static com.jrfapplications.passgen.SettingsPage.isHighCaseChecked;
import static com.jrfapplications.passgen.SettingsPage.isNumbChecked;
import static com.jrfapplications.passgen.SettingsPage.isSpecChecked;
import static com.jrfapplications.passgen.SettingsPage.isStartCustWordChecked;
import static com.jrfapplications.passgen.SettingsPage.passLength;
public class MainActivity extends AppCompatActivity implements Serializable {
//Buttons
Button btnGoToSet;
Button btnGenPass;
Button btnViewPass;
Button btnSavePass;
//TextView
TextView passView;
//Saved Pass Array
static ArrayList<String> SavedCustomPasswords = new ArrayList<>();
static ArrayList<String> SavedFacebookPasswords = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Find Buttons
btnGoToSet = (Button) findViewById(R.id.settingsbtn);
btnGenPass = (Button) findViewById(R.id.genpass);
btnViewPass = (Button) findViewById(R.id.viewpassbtn);
btnSavePass = (Button) findViewById(R.id.SavePassBtn);
//Find TextView
passView = (TextView) findViewById(R.id.pwEditTxt);
//Button Functions
btnGoToSet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, SettingsPage.class));
}
});
btnGenPass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
generatePassword(generateCharSet());
}
});
btnSavePass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (CustPass == 1){
if (SavedCustomPasswords.contains(passView.getText().toString())){
Toast.makeText(getApplicationContext(), "Password Already Saved", Toast.LENGTH_SHORT).show();
}else{
SavedCustomPasswords.add(passView.getText().toString());
Toast.makeText(getApplicationContext(), "Password Saved", Toast.LENGTH_SHORT).show();
}
}
if (FBPass == 1){
if (SavedFacebookPasswords.contains(passView.getText().toString())){
Toast.makeText(getApplicationContext(), "Password Already Saved", Toast.LENGTH_SHORT).show();
}else{
SavedFacebookPasswords.add(passView.getText().toString());
Toast.makeText(getApplicationContext(), "Password Saved", Toast.LENGTH_SHORT).show();
}
}
}
});
btnViewPass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, view_pass.class));
}
});
}
public char[] generateCharSet() {
String numbers = "0123456789";
String special = "!£$%^&*()";
String alphabetsLower = "abcdefghijklmnopqrstuvwxyz";
String alphabetsUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// Add lower alphabets by default
StringBuilder finalCharset = new StringBuilder(alphabetsLower);
// Add special chars if option is selected
if (isSpecChecked == 1) {
finalCharset.append(special);
}
// Add upper case chars if option is selected
if (isHighCaseChecked == 1) {
finalCharset.append(alphabetsUpper);
}
// Add numbers if option is selected
if (isNumbChecked == 1) {
finalCharset.append(numbers);
}
// build the final character set
return finalCharset.toString().toCharArray();
}
public void generatePassword(char[] charset) {
final StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < passLength; i++) {
char c = charset[random.nextInt(charset.length)];
sb.append(c);
}
if (isStartCustWordChecked == 1 && isEndWordChecked == 1){
final String output = custword + sb.toString() + custwordend;
passView.setText(output);
}else if (isStartCustWordChecked == 1){
final String output = custword + sb.toString();
passView.setText(output);
}else if (isEndWordChecked == 1){
final String output = sb.toString() + custwordend;
passView.setText(output);
}else
{
final String output = sb.toString();
passView.setText(output);
}
}
}
* VIEW PASS JAVA *
package com.jrfapplications.passgen;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class view_pass extends AppCompatActivity {
private ListView mListView1, mListView2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_pass);
mListView1 = (ListView)findViewById(R.id.listView1);
mListView2 = (ListView)findViewById(R.id.listView2);
mListView1.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, MainActivity.SavedCustomPasswords));
mListView2.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, MainActivity.SavedFacebookPasswords));
ListUtils.setDynamicHeight(mListView1);
ListUtils.setDynamicHeight(mListView2);
}
public static class ListUtils {
public static void setDynamicHeight(ListView mListView) {
ListAdapter mListAdapter = mListView.getAdapter();
if (mListAdapter == null) {
// when adapter is null
return;
}
int height = 0;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(mListView.getWidth(), View.MeasureSpec.UNSPECIFIED);
for (int i = 0; i < mListAdapter.getCount(); i++) {
View listItem = mListAdapter.getView(i, null, mListView);
listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
height += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = mListView.getLayoutParams();
params.height = height + (mListView.getDividerHeight() * (mListAdapter.getCount() - 1));
mListView.setLayoutParams(params);
mListView.requestLayout();
}
}
}
This can be done by simply storing the generated password into sqlite database. https://developer.android.com/training/basics/data-storage/databases.html
You can also use cursor loaders for a better performance.
https://developer.android.com/guide/components/loaders.html
Try using a DBMS, if you want it stored locally, I would recommend SQL, or cloud-based system like Firebase
Shared preferences and Gson, much simple.
I used shared preferences to to save my ArrayLists on close thanks for the direction guys!
Using this for my answer:
Android: keep values in list after app shutdown
static ArrayList<String> SavedCustomPasswords = new ArrayList<>();
SavedCustomPasswords = getArray();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, SavedCustomPasswords);
adapter.notifyDataSetChanged();
public boolean saveArray() {
SharedPreferences sp = this.getSharedPreferences(SHARED_PREFS_NAME, Activity.MODE_PRIVATE);
SharedPreferences.Editor mEdit1 = sp.edit();
Set<String> set = new HashSet<String>();
set.addAll(SavedCustomPasswords);
mEdit1.putStringSet("list", set);
return mEdit1.commit();
}
public void onStop() {
saveArray();
super.onStop();
}
public ArrayList<String> getArray() {
SharedPreferences sp = this.getSharedPreferences(SHARED_PREFS_NAME, Activity.MODE_PRIVATE);
//NOTE: if shared preference is null, the method return empty Hashset and not null
Set<String> set = sp.getStringSet("list", new HashSet<String>());
return new ArrayList<String>(set);
}

Android App Crash with NullPointerException

I am getting weather info in my app and had it working. Now I am getting a null pointer exception and I'm not sure why, especially since it was working and I haven't changed any of this code.
package com.kentuckyfarmbureau.kyfb;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class WeatherLocation extends Activity
{
EditText locationText;
TextView label;
Button getWeather;
String enteredText;
String url = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=%s&format=json&num_of_days=5&key=37a5fj42xpyptvjgkhrx5rwu";
String newURL;
String currentLocationText;
LocationManager lm;
Location location;
double longitude;
double latitude;
String longString;
String latString;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.weatherlocation);
locationText = (EditText) findViewById(R.id.locationTextView);
label = (TextView) findViewById(R.id.label);
getWeather = (Button) findViewById(R.id.showWeather);
locationText.setText("Current Location");
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
longString = String.valueOf(longitude);
latString = String.valueOf(latitude);
currentLocationText = (latString + "+" + longString);
enteredText = currentLocationText;
newURL = String.format(url, enteredText);
locationText.setOnEditorActionListener(new OnEditorActionListener()
{
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
{
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_DONE)
{
if(locationText.getText().toString().equals("Current Location"))
{
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
longString = String.valueOf(longitude);
latString = String.valueOf(latitude);
currentLocationText = (latString + "+" + longString);
enteredText = currentLocationText;
}
else
{
enteredText = locationText.getText().toString();
enteredText = enteredText.replaceAll(" ", "+");
}
System.out.println(enteredText);
// hide the virtual keyboard
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.RESULT_UNCHANGED_SHOWN);
newURL = String.format(url, enteredText);
System.out.println("Formatted URL: " + newURL);
handled = true;
}
return handled;
}
});
// Get Weather button
getWeather.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent weather = new Intent(WeatherLocation.this, Weather.class);
weather.putExtra("INTENT_KEY_URL", newURL);
weather.putExtra("CURRENT_LOCATION", locationText.getText().toString());
startActivity(weather);
}
});
}
}
The problem seems to be line 48, longitude = location.getLongitude();
If line 48 is causing the issues, then most likely your
location is null. This can be null if you call getLastKnownLocation() while the provider is disabled as noted in the android documentation.
I fixed this by adding a location listener.
final LocationListener locationListener = new LocationListener()
{
#Override
public void onLocationChanged(Location currentLocation)
{
latitude = currentLocation.getLatitude();
longitude = currentLocation.getLongitude();
}
public void onProviderDisabled(String provider)
{
}
public void onProviderEnabled(String provider)
{
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
};
And adding:
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 1, locationListener);

Implement geocoding in android 2.2

Friends...
i'm woking on a project on geocoding.I tried to implement it several times.But i'm not able to retrieve the latitude and longitude values corresponding to a location.Please help me out to complete my project..
try this code hope this will help you:
package com.example.map;
import java.util.List;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import android.app.AlertDialog;
import android.app.Dialog;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class mapView extends MapActivity{
MapView myMap;
Button btnSearch;
EditText adress;
Geocoder gc;
double lat;
double lon;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myMap = (MapView) findViewById(R.id.simpleGM_map); // Get map from XML
btnSearch = (Button) findViewById(R.id.simpleGM_btn_search); // Get button from xml
adress = (EditText) findViewById(R.id.simpleGM_adress); // Get address from XML
gc = new Geocoder(this); // create new geocoder instance
btnSearch.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
String addressInput = adress.getText().toString(); // Get input text
try
{
List<Address> foundAdresses = gc.getFromLocationName(
addressInput, 5); // Search addresses
if (foundAdresses.size() == 0)
{ // if no address found,
// display an error
Dialog locationError = new AlertDialog.Builder(
mapView.this).setIcon(0).setTitle(
"Error").setPositiveButton(R.string.ok, null)
.setMessage(
"Sorry, your address doesn't exist.")
.create();
locationError.show();
}
else
{ // else display address on map
for (int i = 0; i < foundAdresses.size(); ++i)
{
// Save results as Longitude and Latitude
// #todo: if more than one result, then show a
// select-list
Address x = foundAdresses.get(i);
lat = x.getLatitude();
lon = x.getLongitude();
}
navigateToLocation((lat * 1000000), (lon * 1000000),
myMap); // display the found address
}
}
catch (Exception e)
{
// #todo: Show error message
}
}
});
}
#Override
protected boolean isRouteDisplayed()
{
// TODO Auto-generated method stub
return false;
}
/
* Navigates a given MapView to the specified Longitude and Latitude
* #param latitude
* #param longitude
* #param mv
*/
public static void navigateToLocation(double latitude, double longitude,
MapView mv)
{
GeoPoint p = new GeoPoint((int) latitude, (int) longitude); // new
// GeoPoint
mv.displayZoomControls(true); // display Zoom (seems that it doesn't
// work yet)
MapController mc = mv.getController();
mc.animateTo(p); // move map to the given point
int zoomlevel = mv.getMaxZoomLevel(); // detect maximum zoom level
mc.setZoom(zoomlevel - 1); // zoom
mv.setSatellite(false); // display only "normal" mapview
}
}

Categories

Resources