How to use a constructer of java class into fragment? - android

[![enter image description here][1]][1]HI all I am having a problem can anyone tell me how do I resolve this , I want to use a constructer in fragment class:
here is my both classes
AppLocationService:
public class AppLocationService extends Service implements LocationListener {
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
public AppLocationService(Context context) {
locationManager = (LocationManager) context
.getSystemService(LOCATION_SERVICE);
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
here is fragment:
public class AddressFragment extends Fragment {
Button ShowAddress;
TextView tvAddress;
AppLocationService appLocationService;
public AddressFragment(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_address, container, false);
tvAddress = (TextView) rootView.findViewById(R.id.input_location);
appLocationService = new AppLocationService(
AddressFragment.this);
ShowAddress = (Button) rootView.findViewById(R.id.btn_location);
ShowAddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Location location = appLocationService
.getLocation(LocationManager.GPS_PROVIDER);
//you can hard-code the lat & long if you have issues with getting it
//remove the below if-condition and use the following couple of lines
//double latitude = 37.422005;
//double longitude = -122.084095
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LocationAddress locationAddress = new LocationAddress();
locationAddress.getAddressFromLocation(latitude, longitude,
getApplicationContext(), new GeocoderHandler());
} else {
showSettingsAlert();
}
}
});
return rootView;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
AddressFragment.this);
alertDialog.setTitle("SETTINGS");
alertDialog.setMessage("Enable Location Provider! Go to settings menu?");
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
AddressFragment.this.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
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;
}
tvAddress.setText(locationAddress);
}
}
// Inflate the layout for this fragment
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}

To answer your question; A Fragment does not derive from Context. To let your code compile, you should change this
appLocationService = new AppLocationService(
AddressFragment.this);
To this
appLocationService = new AppLocationService(getActivity());
However, you should never call a constructor of a Service yourself. You should start it with Context#startService(Intent) (in your case getActivity().startService(new Intent(getActivity(), AppLocationService.class)). To supply any parameters for your service, take a look at Intent#putExtra(String, String)

Related

Null pointer errors when using fragments

The GPS class and MainActivity both worked fine until we tried to add a second page. We've tried using intents and fragments and have spent way too many hours/days on trying to figure this out.
We keep getting NullPointerExceptions for either the onClickListener() in MainActivity and when updating any textviews from the GPS class. We know it has something to do with how the fragments work but we're not sure how to fix this.
This is our MainActivity class
public class MainActivity extends ActionBarActivity {
// Get buttons and text fields
public Button showLocation;
// TextViews
public static TextView showLatitude;
public static TextView showLongitude;
public static TextView showDistance;
// GPS class
GPS gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
showLocation = (Button) findViewById(R.id.btnShowLocation);
showLatitude = (TextView) findViewById(R.id.txtLatitude);
showLongitude = (TextView) findViewById(R.id.txtLongitude);
showDistance = (TextView) findViewById(R.id.txtDisplayDistance);
// Create gps
gps = new GPS(MainActivity.this);
// show location button click event
showLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
gps.setTotalDistance(0.0);
}
});//END LISTENER
}// END ONCREATE
public void nextPage(View view) {
// In response to button
Intent intent = new Intent(this, ResourcePage.class);
// Set activity intent
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
And this is the GPS class
public class GPS extends Service implements LocationListener {
private final Context mContext;
// Flag for GPS/Network/Location status
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
// Location Class
Location location;
// Latitude and longitude save points
private double startLatitude = 0;
private double endLatitude = 1.0;
private double startLongitude = 0;
private double endLongitude = 1.0;
private double totalDistance = 0;
// Results Array
private float[] results = new float[1];
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_FOR_UPDATES = 10; // meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BETWEEN_UPDATES = 1000; // 1 second
// Location Manager
protected LocationManager locationManager;
// Interface
public GPS(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// Getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// Checking Flags
if (!isGPSEnabled && !isNetworkEnabled) {
// ^no network provider is enabled do nothing/go on^
}
else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BETWEEN_UPDATES, MIN_DISTANCE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
startLatitude = location.getLatitude();
startLongitude = location.getLongitude();
} //END OF LAST IF BLOCK
} //END OF SECOND IF BLOCK
} //END OF "FIRST" IF BLOCK
// if GPS Enabled get latitude/longitude using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BETWEEN_UPDATES, MIN_DISTANCE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
startLatitude = location.getLatitude();
startLongitude = location.getLongitude();
}
}
}
}
}//END OF ELSE BLOCK
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
// Call to remove updates from listener
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPS.this);
}
}
public double getLatitude(){
if(location != null){
startLatitude = location.getLatitude();
}
// Return latitude
return startLatitude;
}
public double getLongitude(){
if(location != null){
startLongitude = location.getLongitude();
}
// Return longitude
return startLongitude;
}
//Function to check GPS/wifi are enabled
public boolean canGetLocation() {
//return boolean
return this.canGetLocation;
}
// Function to show settings alert dialog if gps is off
public void showSettingsAlert(){
// On pressing Settings button will launch Settings Options
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// Settings button listener/press
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
// Called from listener on gps change of X
#Override
public void onLocationChanged(Location location) {
//Display Latitude and Longitude
if(location != null){
startLatitude = location.getLatitude();
startLongitude = location.getLongitude();
MainActivity.showLatitude.setText(String.valueOf(startLatitude));
MainActivity.showLongitude.setText(String.valueOf(startLongitude));
}
// Get distance between
Location.distanceBetween(startLatitude, startLongitude, endLatitude,endLongitude, results);
// Convert to miles Add distance to total
totalDistance = totalDistance + results[0] * 0.000621371192;
// Display the total
MainActivity.showDistance.setText(String.format("%.2f", totalDistance));
// Move old values to End locations
endLatitude = startLatitude;
endLongitude = startLongitude;
}
// Function to clear total distance (Testing)
public void setTotalDistance(Double savedData){
totalDistance = savedData;
MainActivity.showDistance.setText(String.valueOf(totalDistance));
}
public double getTotalDistance(){
return totalDistance;
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
For the layout files we have activity_main.xml which is empty, fragment_main.xml which has all our text fields and buttons and then fragment_resource.xml which has nothing but a textview so we knew things would appear on it.
If you say all your views belong to the fragment then initialize views in fragment not in Activity.
The Activity layout does not have the views and findViewById looks for a view in the current inflated layout. So the initialization fails leading to NullPointerException when you use the view objects.
TextView showLatitude;
TextView showLongitude;
TextView showDistance;
GPS gps;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
showLocation = (Button)rootView.findViewById(R.id.btnShowLocation);
showLatitude = (TextView) rootView.findViewById(R.id.txtLatitude);
showLongitude = (TextView) rootView.findViewById(R.id.txtLongitude);
showDistance = (TextView) rootView.findViewById(R.id.txtDisplayDistance);
gps = new GPS(getActivity()); // wrong bind the service to the activtiy
showLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
gps.setTotalDistance(0.0); // remove this
}
});
return rootView;
}
Also you have
public class GPS extends Service
Its a Service class. You need to bind the service to Activity. But you dogps = new GPS(getActivity());
Replace this:
setContentView(R.layout.activity_main);
By:
setContentView(R.layout.fragment_main);
You have the problem in this method
public void setTotalDistance(Double savedData){
totalDistance = savedData;
MainActivity.showDistance.setText(String.valueOf(totalDistance));
}
You can't just call the MainActivity that way it will return NULL
Pointer exception for showDistance Variable.Because its not a static
class.So you want to do like this.
public void setTotalDistance(Double savedData){
totalDistance = savedData;
((this.mContext)MainActivity).showDistance.setText(String.valueOf(totalDistance));
}
Surely this will make some sense.

turn on gps and using it

I have a class for get the user location.
If the GPS is off I turned it on and show the location, but it doesnt work.
this is the class:
public class UseGPS implements Runnable{
Activity activity;
Context context;
private ProgressDialog pd;
LocationManager mLocationManager;
Location mLocation;
MyLocationListener mLocationListener;
Location currentLocation = null;
public UseGPS(Activity Activity, Context Context){
this.activity = Activity;
this.context = Context;
}
public void getMyPos(){
DialogInterface.OnCancelListener dialogCancel = new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
Toast.makeText(activity,"no gps signal",Toast.LENGTH_LONG).show();
handler.sendEmptyMessage(0);
}
};
pd = ProgressDialog.show(activity,context.getString(R.string.looking_for), context.getString(R.string.gps_signal), true, true, dialogCancel);
writeSignalGPS();
}
private void setCurrentLocation(Location loc) {
currentLocation = loc;
}
private void writeSignalGPS() {
Thread thread = new Thread(this);
thread.start();
}
public void run() {
mLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
Looper.prepare();
mLocationListener = new MyLocationListener();
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
Looper.loop();
Looper.myLooper().quit();
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
pd.dismiss();
mLocationManager.removeUpdates(mLocationListener);
if (currentLocation!=null) {
Toast.makeText(activity,currentLocation.getLatitude(),Toast.LENGTH_LONG).show();
Toast.makeText(activity,currentLocation.getLongitude(),Toast.LENGTH_LONG).show();
}
}
};
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
if (loc != null) {
setCurrentLocation(loc);
handler.sendEmptyMessage(0);
}
}
#Override
public void onProviderDisabled(String provider) {
/*turn on GPS*/
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
context.sendBroadcast(intent);
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
The code works when the GPS is turned on, but it doesnt turn the gps on.
What can I do?
While launching time of your app, give one pop-up message with option to turn on the GPS by the user.
This pop-up button navigates to GPS setting in Setting for their user can turn on the GPS.
Here is the code snippet:
AlertDialog gpsonBuilder = new AlertDialog.Builder(Home_Activity.this);
gpsonBuilder.setTitle("Your Gps Provider is disabled please Enable it");
gpsonBuilder.setPositiveButton("ON",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
});
gpsonBuilder.show();

Setting GPS and waiting for enable

I have a problem with setting GPS service . I want to check if GPS is enable . If it is disable , it will display a dialog to user turn it on . The problem is it not wait for user enable GPS and get location .
I have a class
public class GPSTracker extends Service implements LocationListener{
private final Context mContext;
boolean isGPSEnable = false;
boolean isNetworkEnable = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_FOR_UPDATE = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATE = 1000 * 60 * 1; // 1 minute
protected LocationManager locationManager;
public GPSTracker(Context ctx) {
this.mContext = ctx;
getLocation();
}
public Location getLocation()
{
try {
locationManager = (LocationManager)mContext.getSystemService(LOCATION_SERVICE);
isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnable)
{
showSettingsGPSAlert();
}
else if(!isNetworkEnable)
{
showSettingsNetWorkAlert();
}
else
{
this.canGetLocation = true;
if(isNetworkEnable)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATE,
MIN_DISTANCE_FOR_UPDATE, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnable) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATE,
MIN_DISTANCE_FOR_UPDATE, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
}catch (Exception ex)
{
Log.e("<<Location Error>>",ex.getMessage());
}
return location;
}
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public boolean canGetGPS() {
return this.isGPSEnable;
}
public boolean canGetNetwork() {
return this.isNetworkEnable;
}
public void showSettingsGPSAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startService(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
public void showSettingsNetWorkAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("NetWork is settings");
// Setting Dialog Message
alertDialog.setMessage("NetWork is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
And I have class to use it
public class RestaurantListFragment extends ListFragment {
private ArrayList<Restaurant> restaurants;
private SQLDataHelper dataHelper;
private GPSTracker gps;
private double UserLatitude;
private double UserLongitude;
private ProgressDialog progressBar;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.restaurant_list, null);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
gps = new GPSTracker(getActivity());
UserLatitude = gps.getLatitude();
UserLongitude = gps.getLongitude();
Toast.makeText(getActivity(),UserLatitude + "|" + UserLongitude,Toast.LENGTH_SHORT).show();
dataHelper = new SQLDataHelper(getActivity(), "restaurantDB");
restaurants = new ArrayList<Restaurant>();
dataHelper.openDB();
Cursor cursor = dataHelper.query("Restaurant", new String[]{"Id", "ResName", "Logo", "Address", "Latitude", "Longitude"}, null
, null, null, null, null);
if (cursor.moveToFirst()) {
do {
Restaurant restaurant = new Restaurant();
restaurant.setId(cursor.getInt(0));
restaurant.setResName(cursor.getString(1));
restaurant.setLogo(cursor.getString(2));
restaurant.setAddress(cursor.getString(3));
restaurants.add(restaurant);
} while (cursor.moveToNext());
}
//Collections.sort(restaurants);
RestaurantAdapter restaurantAdapter = new RestaurantAdapter(getActivity(),restaurants);
setListAdapter(restaurantAdapter);
}
}
It works fine when GPS is enable . I want the user can turn it on first . After that it show user location . Then it can query database and setListAdapter . Thanks for any suggestion .

Multiple onResume() when coming back to my activity from Home

When I am navigating out from my (main) activity and then coming back by clicking the icon on the Home screen - the activity is automatically Resumed->Paused->Resumed.
I am expecting for only one onResume().
My activity creates an AsyncTask in the onResume() function (the activity is not calling to other activities at all) and currently two additional AsyncTasks are created instead of one.
I did some tests and noticed that it happens when this activity is declared as "SingleTask" in the Mainfest. With 'SingleTop" it goes fine and onResume() is called only once.
HELP!
This is my code of the main activity:
public class HomeFinderActivity extends ListActivity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
private Location location;
private static final String LOG_TAG = "::HomeFinderActivity->Asynctask";
private ArrayList<Home> home_parts = new ArrayList<Home>();
private ListViewAdapter m_adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
// instantiate ListViewAdapter class
m_adapter = new ListViewAdapter(this, R.layout.row, home_parts);
setListAdapter(m_adapter);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
location = locationManager.getLastKnownLocation(provider);
}
//Asynctask to retrieve cursor from database and sort list by distance
private class SortList extends AsyncTask<Location, Void, ArrayList<Home>> {
#Override
protected ArrayList<Home> doInBackground(Location... location) {
try {
if (home_parts.isEmpty()){
home_parts=Home.getHomeParts(location[0], getApplicationContext());
}
else{
for (Home d : home_parts){
if (location != null){
d.setmDistance((int) (d.getmLatitude()), d.getmLongitude(),(double) (location[0].getLatitude())
, (double) (location[0].getLongitude()));
}
}
}
} finally {
}
Collections.sort(home_parts, new Comparator(){
public int compare(Object o1, Object o2) {
Home p1 = (Home) o1;
Home p2 = (Home) o2;
return (int) p1.getmDistance()- (int) p2.getmDistance();
}
});
return home_parts;
}
protected void onPostExecute(ArrayList<Home> address) {
m_adapter = new ListViewAdapter(HomeFinderActivity.this, R.layout.row, address);
// display the list.
setListAdapter(m_adapter);
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
//starting handling location
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
Log.e(LOG_TAG, "onResume() started");
if (location != null) {
onLocationChanged(location);
}
else
{
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
Log.e(LOG_TAG, "onPause() started");
locationManager.removeUpdates(this);
}
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
SortList showList = new SortList();
showList.execute(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
/** Called when the user clicks the Add Entry button */
public void goAddEntry(View view) {
Intent intent = new Intent(this, AddEntry.class);
startActivity(intent);
}
}

Loading Map crashes on few devices

I have a listview and onItemSelected, will call an Activity to get user location (his current lat and lng), this activity has no layout, then this activity automatically calls another activity which gets lat and lng of the item selected from the listview and marks both the user location and item location on the map.
This worked fine when I was testing on Emulator and Samsung Galaxy Ace, But it crashes when I'm testing on Micromax A50 and Sony Xperia.
Sad thing is that I can't install drivers of the later 2 devices, so I cant get logcat.
Can any 1 guess what might have gone wrong??
My code for finding user location is:
public class MyLocationActivity extends Activity implements LocationListener {
private LocationManager mgr;
private String best;
public static double myLocationLatitude;
public static double myLocationLongitude;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mgr = (LocationManager) getSystemService(LOCATION_SERVICE);
dumpProviders();
Criteria criteria = new Criteria();
best = mgr.getBestProvider(criteria, true);
Log.d("best provider", best);
Location location = mgr.getLastKnownLocation(best);
dumpLocation(location);
/*Intent intent = new Intent(MyLocationActivity.this, ShowMapActivity.class);
startActivity(intent);*/
Intent intent = new Intent(MyLocationActivity.this, MapMarkerActivity.class);
startActivity(intent);
finish();
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
dumpLocation(location);
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
protected void onPause() {
super.onPause();
mgr.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
mgr.requestLocationUpdates(best, 15000, 1, this);
}
private void dumpLocation(Location l) {
if (l == null) {
myLocationLatitude = 0.0;
myLocationLongitude = 0.0;
} else {
myLocationLatitude = l.getLatitude();
myLocationLongitude = l.getLongitude();
}
}
private void dumpProviders() {
List<String> providers = mgr.getAllProviders();
for (String p : providers) {
dumpProviders(p);
}
}
private void dumpProviders(String s) {
LocationProvider info = mgr.getProvider(s);
StringBuilder builder = new StringBuilder();
builder.append("name: ").append(info.getName());
}
}
and item location is:
public class MapMarkerActivity extends MapActivity {
private MapView map = null;
private MyLocationOverlay me = null;
private Drawable marker1;
private Drawable marker2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.particular_entry);
Button feedButton = (Button) findViewById(R.id.feedButton_particularEntry);
feedButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(MapMarkerActivity.this,
FeedListViewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
});
Button iWantButton = (Button) findViewById(R.id.iWantButton_particularEntry);
iWantButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MapMarkerActivity.this,
IWantActivity.class);
startActivity(intent);
}
});
Button shareButton = (Button) findViewById(R.id.shareButton_particularEntry);
shareButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MapMarkerActivity.this,
ShareActivity.class);
startActivity(intent);
}
});
Button profileButton = (Button) findViewById(R.id.profileButton_particularEntry);
profileButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MapMarkerActivity.this,
ProfileActivity.class);
startActivity(intent);
}
});
map = (MapView) findViewById(R.id.map);
map.getController().setCenter(
getPoint(FeedListViewActivity.lat, FeedListViewActivity.lng));
map.getController().setZoom(13);
map.setBuiltInZoomControls(true);
marker1 = getResources().getDrawable(R.drawable.marker2);
marker2 = getResources().getDrawable(R.drawable.marker1);
marker1.setBounds(0, 0, marker1.getIntrinsicWidth(),
marker1.getIntrinsicHeight());
marker2.setBounds(0, 0, marker1.getIntrinsicWidth(),
marker1.getIntrinsicHeight());
map.getOverlays().add(new SitesOverlay(marker1));
me = new MyLocationOverlay(this, map);
map.getOverlays().add(me);
}
#Override
public void onResume() {
super.onResume();
me.enableCompass();
}
#Override
public void onPause() {
super.onPause();
me.disableCompass();
}
#Override
protected boolean isRouteDisplayed() {
return (false);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_S) {
map.setSatellite(!map.isSatellite());
return (true);
} else if (keyCode == KeyEvent.KEYCODE_Z) {
map.displayZoomControls(true);
return (true);
}
return (super.onKeyDown(keyCode, event));
}
private GeoPoint getPoint(double lat, double lon) {
return (new GeoPoint((int) (lat * 1000000.0), (int) (lon * 1000000.0)));
}
public class SitesOverlay extends ItemizedOverlay<OverlayItem> {
private List<OverlayItem> items = new ArrayList<OverlayItem>();
public SitesOverlay(Drawable marker) {
super(marker);
boundCenterBottom(marker);
OverlayItem oli1 = new OverlayItem(getPoint(
MyLocationActivity.myLocationLatitude,
MyLocationActivity.myLocationLongitude), "YL",
"Your Location");
oli1.setMarker(marker2);
items.add(oli1);
OverlayItem oli2 = new OverlayItem(getPoint(
FeedListViewActivity.lat, FeedListViewActivity.lng), "SL",
"Store Location");
oli2.setMarker(marker1);
items.add(oli2);
populate();
}
#Override
protected OverlayItem createItem(int i) {
return (items.get(i));
}
#Override
protected boolean onTap(int i) {
Toast.makeText(MapMarkerActivity.this, items.get(i).getSnippet(),
Toast.LENGTH_SHORT).show();
return (true);
}
#Override
public int size() {
return (items.size());
}
}
}
Maybe this can help you:
Location Method Calls Crashes On Some Devices

Categories

Resources