How to pass GPS (lat,lon etc) to Android services - service

I'm trying to build a background service which is able to log the data and save it into a SQLite database at a specific time interval without user consent.
So far:
I was able to start the services and toast current LastKnownLocation. This just to see if the variable is okay before I insert it to SQLite table.
However, if the GPS is not active the application will crash.
What's wrong with my code, and how to make it auto change when location changes?
public class SpycareServices extends Service {
/*Location Listener Declaration*/
PhoneInfo myPhone;
Util myFunction;
private LocationListener listener;
private LocationManager locationManager;
boolean gps_enabled = false;
boolean network_enabled = false;
Location net_loc = null, gps_loc = null, finalLoc = null;
public double longitude,latitude;
/*Declare SharedPref StartService*/
public SpycareServices(){
}
/*Declare constructor for location listener*/
public SpycareServices(Context context){
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate(){
/*Instantiate listener*/
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
//Check which provider active
gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(gps_enabled)
{
gps_loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if(network_enabled)
{
net_loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//net_loc = locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,3000,0,listener);
}
/*If both gps and network has value, choose the better one*/
if (gps_loc != null && net_loc != null) {
//smaller the number more accurate result will
if (gps_loc.getAccuracy() > net_loc.getAccuracy()){
finalLoc = net_loc;
//
}
else{
finalLoc = gps_loc;
//locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,listener);
}
} else {
if (gps_loc != null) {
finalLoc = gps_loc;
} else if (net_loc != null) {
finalLoc = net_loc;
}
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
Toast.makeText(getApplicationContext(),"Services Has Been Started!",Toast.LENGTH_SHORT).show();
//Instance util to get timestamp
myFunction = new Util(this);
Toast.makeText(getApplicationContext(),"My time "+ myFunction.getTimestamp(this),Toast.LENGTH_SHORT).show();
//Instance Imei
myPhone = new PhoneInfo(this);
Toast.makeText(getApplicationContext(),"My Imei "+ myPhone.betaGetImei(this),Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"My Location Provider is "+ finalLoc.getProvider(),Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"My Longitude is "+ finalLoc.getLongitude(),Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"My Latitude is "+ finalLoc.getLatitude(),Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public void onDestroy(){
Toast.makeText(getApplicationContext(),"Services Has Been Destroyed!",Toast.LENGTH_SHORT).show();
//super.onDestroy();
//Prevent memory leaks by deregister listener when destroyed
if(locationManager!=null){
locationManager.removeUpdates(listener);
}
}

Related

How to access SharedPreference within Service in Android

I am working on a service that will capture longitude and latitude implementing LocationListener.
Also I am trying to update the longitude and latitude values in sharedpreference as they get captured.
However I am getting runtime error while using sharedpreference within service. I think the problem is with context. I have tried, getApplicationContext(), getBaseContext() but not working.
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// private GPSTrackerImplementation mCallback;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
//public SharedPrefference shareObj;
String address;
String city;
String state;
String country;
String postalCode;
String knownName;
Geocoder geocoder;
List<Address> addresses;
public SharedPrefference shareObj;
public GPSTracker(Context context) {
this.mContext = context;
// PreferenceManager.getDefaultSharedPreferences(context);
// SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
//PreferenceManager.getDefaultSharedPreferences(context).edit().putString("GPS_ENABLED", "Y").commit();
// if (!isGPSEnabled) {
// no network provider is enabled
} else this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
getLocation();
}
if (isGPSEnabled) {
if (location == null) {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS", "GPS");
getLocation();
}
}
}catch (SecurityException e) {
e.printStackTrace();
}
getLocation();
}
public Location getLocation() {
try {
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.d("On constructor-GPS", "latitude"+latitude);
Log.d("On constructor-GPS", "longitude"+longitude);
return location;
}
else {
return locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
}catch (SecurityException e) {
e.printStackTrace();
}
return location;
}
/**
* Function to get latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
*
* #return boolean
*/
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
*/
#Override
public void onLocationChanged(Location location) {
this.location = location;
latitude = location.getLatitude();
longitude = location.getLongitude();
// Toast.makeText(this, "location changed", Toast.LENGTH_LONG).show();
Log.d("n location changed", "latitude"+latitude);
Log.d("On location changed", "longitude"+longitude);
String m_latStr = Double.toString(latitude);
String m_longStr = Double.toString(longitude);
PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit().putString("LATITUDE", m_latStr).commit();
PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit().putString("LONGITUDE", m_longStr).commit();
}
LOGCAT
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:375)
at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:370)
at com.teamlease.gps.services.GPSTracker.onLocationChanged(GPSTracker.java:195)
at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:285)
at android.location.LocationManager$ListenerTransport.-wrap0(LocationManager.java)
at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:230)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

Refresh suggestion list on change - cn1 autocomplete

I've implemented a custom autocomplete text field in a cn1 app, but I've noticed it only loads the suggestions list once, after that any change in the text doesn't trigger a change in the list, and the getSuggestionModel() is never called again. How can I achieve this (in my mind, basic) functionality?
This is my autocomplete class:
public class ForumNamesAutocomplete extends AutoCompleteTextField {
List<String>suggestions = new LinkedList<String>();
List<Map<String,Object>> fData;
StateMachine mac;
int currentIndex;
String prevText;
public static final String KEY_FORUM_NAME = "name";
public static final String KEY_FORUM_ID = "id";
public static final String KEY_FORUM_DESC = "desc";
public ForumNamesAutocomplete(StateMachine sm){
super();
mac = sm;
if(sm.forumData != null){
fData = mac.forumData;
}
}
#Override
protected boolean filter(String text) {
if(text.equals(prevText)){
return false;
}
setSuggestionList(text);
fireDataChanged(DataChangedListener.CHANGED, text.length());
prevText = text;
return true;
}
#Override
public void fireDataChanged(int type, int index) {
super.fireDataChanged(type, index);
}
public void setSuggestionList(String s){
if(suggestions == null){
suggestions = new LinkedList<String>();
}else{
suggestions.clear();
}
LinkedList<String> descList = new LinkedList<String>();
for(int i = 0;i<fData.size();i++){
boolean used = false;
Map<String,Object> forumMap = fData.get(i);
if(((String)forumMap.get(KEY_FORUM_NAME)).indexOf(s) != -1){
suggestions.add((String)forumMap.get(KEY_FORUM_NAME));
used = true;
}
if(!used && ((String)forumMap.get(KEY_FORUM_DESC)).indexOf(s) != -1){
descList.add((String)forumMap.get(KEY_FORUM_NAME));
}
}
suggestions.addAll(descList);
}
#Override
protected ListModel<String> getSuggestionModel() {
return new DefaultListModel<String>(suggestions);
}
}
This used to be simpler and seems to be a bit problematic now as explained in this issues.
Technically what you need to do is return one model and then mutate said model/fire modified events so everything will refresh. This is non-trivial and might not work correctly for all use cases so ideally we should have a simpler API to do this as we move forward.
After additional debugging, I saw that the getSuggestionModel() method was being called only during initialization, and whatever the suggestion list (in suggestion object) was at that point, it remained so. Instead I needed to manipulate the underlying ListModel object:
public class ForumNamesAutocomplete extends AutoCompleteTextField {
ListModel<String>myModel = new ListModel<String>();
...
#Override
protected boolean filter(String text) {
if(text.length() > 1){
return false;
}
setSuggestionList(text);
return true;
}
private void setSuggestionList(String s){
if(myModel == null){
myModel = new ListModel<String>();
}else{
while(myModel.getSize() > 0)
myModel.removeItem(0);
}
for(int i = 0;i<fData.size();i++){
boolean used = false;
Map<String,Object> forumMap = fData.get(i);
if(((String)forumMap.get(KEY_FORUM_NAME)).indexOf(s) != -1){
myModel.addItem((String)forumMap.get(KEY_FORUM_NAME));
used = true;
}
if(!used && ((String)forumMap.get(KEY_FORUM_DESC)).indexOf(s) != -1){
myModel.addItem((String)forumMap.get(KEY_FORUM_NAME));
}
}
}
...
}

current location not display accurately by google location API

When I am running this code it gives current location after I clicked the button_currentlocation. But when I checked the accuracy it is very low accuracy (sometime 5000m). But I need to get current location for one time with high accuracy (around 10m).
If someone can help me to correct my coding,it will be great help for my research.
My cordings are as follow
in my manifest
uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
LocationProvider Class
public class LocationProvider implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
public abstract interface LocationCallback {
public void handleNewLocation(Location location);
}
public static final String TAG = LocationProvider.class.getSimpleName();
/*
* Define a request code to send to Google Play services
* This code is returned in Activity.onActivityResult
*/
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private LocationCallback mLocationCallback;
private Context mContext;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
public LocationProvider(Context context, LocationCallback callback) {
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationCallback = callback;
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
mContext = context;
}
public void connect() {
mGoogleApiClient.connect();
}
public void disconnect() {
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Location services connected.");
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
mLocationCallback.handleNewLocation(location);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution() && mContext instanceof Activity) {
try {
Activity activity = (Activity)mContext;
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(activity, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
mLocationCallback.handleNewLocation(location);
}
}
In HomePage Class
package com.ksfr.finaltest01;
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.android.gms.maps.model.LatLng;
public class HomePage extends Activity implements AdapterView.OnItemSelectedListener,LocationProvider.LocationCallback {
public static final String TAG = HomePage.class.getSimpleName();
Button button_disFinder;
private LocationProvider locationProvider;
String Provider,Str_endLocation;
double cur_latitude, cur_longitude,cur_accuracy, end_latitude, end_longitude;
float distance_cur_to_end;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
locationProvider = new LocationProvider(this,this);
Spinner spinner = (Spinner) findViewById(R.id.spinner_schools);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.school_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public void CurrentLocationClicked(View view) {
if (cur_latitude!=0&&cur_longitude != 0 ){
Spinner spinner = (Spinner) findViewById(R.id.spinner_schools);
spinner.setClickable(true);
String message= String.format("Current Location\n" + "Latitude :" + cur_latitude + "\nLongitude :" + cur_longitude+"\nAccuracy :"+cur_accuracy+"\nProvider :"+Provider);
Toast.makeText(HomePage.this, message, Toast.LENGTH_LONG).show();
}
else{
String message= String.format("Location services disconnected.\nSwich ON Location Service to work App.");
Toast.makeText(HomePage.this, message, Toast.LENGTH_LONG).show();
//System.exit(0);
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position!= 0) {
Str_endLocation=String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(getApplicationContext(), Str_endLocation + " Selected", Toast.LENGTH_SHORT).show();
switch (Str_endLocation){
//end location latitude and logitude will be taken from here.
case "Kahagolla National School":
end_latitude = 6.816703;end_longitude = 80.9637076;
break;
}
String message3= String.format("End Location\n"+"Latitude :"+end_latitude+"\nLongitude :"+end_longitude);//For Testing
Toast.makeText(HomePage.this, message3, Toast.LENGTH_LONG).show();//For Testing
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void FindDistanceClicked (View view){
Location curlocation = new Location("");
curlocation.setLatitude(cur_latitude);
curlocation.setLongitude(cur_longitude);
Location endlocation = new Location("");
endlocation.setLatitude(end_latitude);
endlocation.setLongitude(end_longitude);
distance_cur_to_end = curlocation.distanceTo(endlocation)/1000;
String message5= String.format("Distance from current location to\n" + Str_endLocation + " :" + String.format("%.3g%n", distance_cur_to_end)+"km");//For testing
Toast.makeText(HomePage.this, message5, Toast.LENGTH_LONG).show();//For testing
}
public void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
cur_latitude = location.getLatitude();
cur_longitude = location.getLongitude();
cur_accuracy = location.getAccuracy();
Provider = location.getProvider();
LatLng cur_latLng = new LatLng(cur_latitude, cur_longitude);
}
#Override
protected void onResume() {
super.onResume();
locationProvider.connect();
}
#Override
protected void onPause() {
super.onPause();
locationProvider.disconnect();
}
public void ClearClicked (View view){
}
}
Try reversing your onConnected method location code.
First try to get current location and if that is not available then try getting lastKnown location.
Some thing like this
if(location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
I corrected my issue finally,
From this method i got locations in 3m accuracy,which I want.
Here's code
DistanceFinderActivity.java
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 5*1000; // in Milliseconds
protected LocationManager locationManager;
double cur_latitude, cur_longitude,cur_accuracy, end_latitude, end_longitude;
float distance_cur_to_end;
public LatLng cur_latLng,end_latLng;
MyLocationListener myLocationListener =new MyLocationListener();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_distance_finder);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
myLocationListener
);
//......
}
protected void showCurrentLocation() {
Location location = locationManager.getLastKnownLocation(GPS_PROVIDER);
if (location != null) {
cur_latitude = location.getLatitude();
cur_longitude = location.getLongitude();
cur_accuracy = location.getAccuracy();
Provider = location.getProvider();
DecimalFormat df = new DecimalFormat("#.###");
df.setMinimumFractionDigits(2);
String message = String.format(
"Current Location \nLatitude: %1$s\nLongitude: %2$s\nAccuracy: %3$s\n" +
" Provider: %4$s\nWait until new location capture",
cur_latitude, cur_longitude,String.valueOf(df.format(cur_accuracy)),Provider.toUpperCase()
);
Toast.makeText(MainDistanceFinderActivity.this, message,
Toast.LENGTH_LONG).show();
}
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
cur_latitude = location.getLatitude();
cur_longitude = location.getLongitude();
cur_accuracy = location.getAccuracy();
Provider = location.getProvider();
DecimalFormat df = new DecimalFormat("#.###");
df.setMinimumFractionDigits(2);
String message = String.format(
"New Location Captured. \nLatitude: %1$s\nLongitude: %2$s\nAccuracy: %3$s\n" +
" Provider: %4$s",
cur_latitude, cur_longitude,String.valueOf(df.format(cur_accuracy)), Provider.toUpperCase()
);
Toast.makeText(MainDistanceFinderActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(MainDistanceFinderActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(MainDistanceFinderActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(MainDistanceFinderActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}

Add Cluster Items onClick over Expandable List View

First of all I'm sorry for my bad English :X
Iam quite a newbie in Android App development and Iam about to develope an app which gives the user informations like free park-places in town.
The app is based on Google Maps.
My Problem:
My app starts and shows a Google Maps Layout. Over an ExpandableListView the User can open a overview about the Parking-Locations.
If the user click on a Child Item in the ExpListView a new Cluster item should be generated at the MapsLayout.
How can I give the OnClick data to the MainActivity? I want that the MainActivity 'knew' which Item is clicked by the User!
Im glad about every answer :)
public class MyExpandableAdapter extends BaseExpandableListAdapter{
private Activity activity;
private ArrayList<Object> childtems;
private LayoutInflater inflater;
private ArrayList<String> parentItems, child;
// constructor
public MyExpandableAdapter(ArrayList<String> parents, ArrayList<Object> childern)
{
this.parentItems = parents;
this.childtems = childern;
}
public void setInflater(LayoutInflater inflater, Activity activity)
{
this.inflater = inflater;
this.activity = activity;
}
// method getChildView is called automatically for each child view.
// Implement this method as per your requirement
#Override
public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
{
child = (ArrayList<String>) childtems.get(groupPosition);
TextView textView = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.child_view, null);
}
// get the textView reference and set the value
textView = (TextView) convertView.findViewById(R.id.textViewChild);
textView.setText(child.get(childPosition));
// set the ClickListener to handle the click event on child item
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(activity, child.get(childPosition),
Toast.LENGTH_SHORT).show();
//Tried to insert connection to MapsActivity but doesnt work!
}
});
return convertView;
}
// method getGroupView is called automatically for each parent item
// Implement this method as per your requirement
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
{
if (convertView == null) {
convertView = inflater.inflate(R.layout.parent_view, null);
}
((CheckedTextView) convertView).setText(parentItems.get(groupPosition));
((CheckedTextView) convertView).setChecked(isExpanded);
return convertView;
}
#Override
public Object getChild(int groupPosition, int childPosition)
{
return null;
}
#Override
public long getChildId(int groupPosition, int childPosition)
{
return 0;
}
#Override
public int getChildrenCount(int groupPosition)
{
return ((ArrayList<String>) childtems.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition)
{
return null;
}
#Override
public int getGroupCount()
{
return parentItems.size();
}
#Override
public void onGroupCollapsed(int groupPosition)
{
super.onGroupCollapsed(groupPosition);
}
#Override
public void onGroupExpanded(int groupPosition)
{
super.onGroupExpanded(groupPosition);
}
#Override
public long getGroupId(int groupPosition)
{
return 0;
}
#Override
public boolean hasStableIds()
{
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition)
{
return false;
}
}
MapsActivity (Main)
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private ClusterManager<MyItem> mClustermanager ;
private ArrayList<String> parentItems = new ArrayList<String>();
private ArrayList<Object> childItems = new ArrayList<Object>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpClusterer();
// Create Expandable List and set it's properties
ExpandableListView expandableList = (ExpandableListView) findViewById(R.id.expandableListView);
expandableList.setDividerHeight(2);
expandableList.setGroupIndicator(null);
expandableList.setClickable(true);
// Set the Items of Parent
setGroupParents();
// Set The Child Data
setChildData();
// Create the Adapter
MyExpandableAdapter adapter = new MyExpandableAdapter(parentItems, childItems);
adapter.setInflater((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE), this);
// Set the Adapter to expandableList
expandableList.setAdapter(adapter);
// expandableList.setOnChildClickListener();
}
// method to add parent Items
public void setGroupParents()
{
parentItems.add("Parkhäuser");
}
public void setChildData()
{
ArrayList<String> child = new ArrayList<String>();
child = new ArrayList<String>();
child.add("Park1");
child.add("Park2");
child.add("Park3");
child.add("Park4");
childItems.add(child);
}
private void setUpClusterer()
{
((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(47.99481, 7.84856), 10 )) ;
//Initialisierung des Managers mit dem Context (this) und der Map
//Activity erbt von Context deswegen können wir dem Konstruktor 'this' mitgeben
mClustermanager = new ClusterManager<MyItem>(this, ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap() );
//Zeigt der Map die Listener des ClusterManagers
((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap().setOnCameraChangeListener((mClustermanager));
((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap().setOnMarkerClickListener(mClustermanager);
//Hinzufügen der Markierungen zum Cluster Manager
addItems() ;
}
private void addItems(){
//Startkoordinaten des ersten Markers --> Bahnhofsgarage
double lat = 47.99673 ;
double lng = 7.84152 ;
//Hinzufügen von 10 weiteren Punkten
for(int i = 1; i <14; i++){
if(i==1)
{ //Konzerthaus
lat = 47.99602 ;
lng = 7.84220;
}
if(i==2){
//Volksbank
lat = 47.99783 ;
lng = 7.84322;
}
if(i==3){
//am Bahnhof
lat = 47.99892 ;
lng = 7.84310;
}
if(i==4){
//Uni-FMF/Vf
lat = 48.00135 ;
lng = 7.84481;
}
if(i==5){
//unterlinden
lat = 47.99811 ;
lng = 7.84876;
}
if(i==6){
//schwarzwaldcity
lat = 47.99760 ;
lng = 7.85090;
}
if(i==7){
//Rotteckring
lat = 47.99618 ;
lng = 7.84732;
}
if(i==8){
//Am Zähringer Tor
lat = 47.99921 ;
lng = 7.85350;
}if(i==9){
//Karlsbau
lat = 47.99757 ;
lng = 7.85366;
}if(i==10){
//Landratsamt
lat = 47.99969 ;
lng = 7.85758;
}if(i==11){
//Schlossberg
lat = 47.99654 ;
lng = 7.85758;
}if(i==12){
//Schwabentor
lat = 47.99054 ;
lng = 7.85833;
}if(i==13){
//Am Martinstor
lat = 47.99281 ;
lng = 7.84715;
}if(i==14){
//Uni Kolleg Gebäude
lat = 47.98797 ;
lng = 7.87129;
}
MyItem offsetItem = new MyItem(lat,lng) ;
mClustermanager.addItem(offsetItem);
}
}
}
Solved! After research I make ExpandableAdpater an inner class of MapsActivity! Now i can put data between both classes and use Methods also!

Getting location with Android Google Map v2

I can't get my locayion. It always crashes. I checked everything. Can anyone please help me find my location?
private GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
if(isGooglePlay()){
setContentView(R.layout.map);
setupmapifneeded();
}
}
private void setupmapifneeded() {
if(map==null){
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
}if(map!=null){
map.setMyLocationEnabled(true);
LocationManager mlm = (LocationManager)getSystemService(LOCATION_SERVICE);
Criteria c = new Criteria();
String provider = mlm.getBestProvider(new Criteria(), false);
if(provider == null){
onProviderDisabled(provider);
}
Location mylocation = mlm.getLastKnownLocation(provider);
if(mylocation != null){
onLocationChanged(mylocation);
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
private boolean isGooglePlay(){
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(status == ConnectionResult.SUCCESS){
return true;
}else{
((Dialog)GooglePlayServicesUtil.getErrorDialog(status, this, 10)).show();
//Toast.makeText(this, "nai", Toast.LENGTH_LONG).show();
}
return false;
}
#Override
public void onLocationChanged(Location mylocation) {
double lat = mylocation.getLatitude();
double longi = mylocation.getLongitude();
LatLng latlng = new LatLng(lat,longi);
map.moveCamera(CameraUpdateFactory.newLatLng(latlng));
map.animateCamera(CameraUpdateFactory.zoomTo(10));
}
you can simply use
map.setMyLocationEnabled(true)
this will get your location on the map automatically.
Location location = map.getMyLocation();