Sort list items based on gps distance - flutter

Hello the dart code below contains a series of locations with the gps position, at the time of starting the app I have to retrieve the long and lat that I have saved in two variables, what I have to do next is to sort the list of locations based on the gps distance from where to find me this is based on lat and long how can I do?
Dart Code:
double longitudine=0,latitudine=0;
Future<bool> caricamentoSedi() async {
await _getGpsValue();
listaSedi = await Sede.caricamento();
//This point write function order listaSedi
return true;
}
Sede class:
class Sede {
//Costruttore di una sede
Sede(this.info_id, this.app_id, this.info_title, this.descrizione, this.email,
this.telefono, this.lat, this.long, this.note,this.rgbcolor);
final int info_id, app_id;
double lat = 0, long = 0;
final String info_title, descrizione, email, telefono, note,rgbcolor;
//Descrizione: Funzione che effettua il caricamento delle sedi
static Future<List<Sede>> caricamento() async {
return await SedeController.caricamento();
}
//Descrizione: funzione che recupero l'email
String getEmail() {
return email;
}
//Descrizione: funzione che recupera la descrizione
String getDescrizione() {
return descrizione;
}
//Descrizione: funzione che recupera il numero di telefono rimuovendo li spazi vuoti presenti nel valore
String getTelefono() {
return telefono.replaceAll(new RegExp(r"\s+"), "");
}
//Recupero latitudine
double getLatitudine() {
return lat;
}
//Recupero longitudine
double getLongitudine() {
return long;
}
//Recupero note
String getNote() {
return this.note;
}
}

You can implement your own method to calculate distance between 2 points, then use it to sort the list :
https://stackoverflow.com/a/64966888/14394936
Or you can use a lib like geolocator :
https://stackoverflow.com/a/64890616/14394936
Sort the list :
https://stackoverflow.com/a/12889025/14394936
https://api.dart.dev/stable/2.10.5/dart-core/List/sort.html

Related

Huffman code for image compression - Java

Since I started my Codification Theory course, I've started to feel curious about practical implementations of information theory algorithms. I've researched about Huffman code and how this is used for data compress. I am specially curious about building an image (JPG, JPEG) compressor using Huffman codes but I'm struggling in the implementation.
My idea for this program goes like this:
1. Implement a HuffmanCode class, which is used to encode and decode a string input (Find the char frequency for all characters in string, build Huffman tree, generate Huffman code, etc.). I found this implementation "here".
2. Having the Huffman code implementation, I read an image input and convert it to a byte array. Then, I use this byte array to build a string having all of these bytes. Now, I apply the Huffman code for the previous string.
3. The result of the previous step is a binary string, then I convert this binary string to a byte array.
4. Finally, write the corresponding image to the previous byte array and output.
Following this reasoning, I got a RasterFormatException : Data array too small (should be > 749999 ). I've tried others implementations for writing the image but I am still getting some other Exceptions such as image == null exception.
I was wondering if someone has a better approach for building this program, or if I am missing something related to writing/reading images in Java (I'm new with this tools), or if I am misunderstanding something related to Huffman codes.
The HuffmanCode class is the following (I made some changes):
public class HuffmanCode {
public static void main(String[] args){
String test = "AndersonAndresLlanosQuintero";
System.out.println(countFrequency(test));
}
// Clase nodo para las construcción del árbol.
class HuffmanNode{
public int frecuencia;
public char caracter;
public HuffmanNode leftNode;
public HuffmanNode rightNode;
public HuffmanNode(){}
public int getFrecuencia() {
return frecuencia;
}
public void setFrecuencia(int frecuencia) {
this.frecuencia = frecuencia;
}
public char getCaracter() {
return caracter;
}
public void setCaracter(char caracter) {
this.caracter = caracter;
}
public HuffmanNode getLeftNode() {
return leftNode;
}
public void setLeftNode(HuffmanNode leftNode) {
this.leftNode = leftNode;
}
public HuffmanNode getRightNode() {
return rightNode;
}
public void setRightNode(HuffmanNode rightNode) {
this.rightNode = rightNode;
}
}
// Clase comparadora para saber cuando un nodo está por encima de otro.
class HuffmanComparator implements Comparator<HuffmanNode> {
public int compare(HuffmanNode x, HuffmanNode y) {
return x.frecuencia - y.frecuencia;
}
}
/* Procedemos a implementar el algoritmo : */
/* Necesitaremos la raíz del árbol de Huffman y un Map para
hacer match entre un símbol y su frecuencia de aparición.
*/
private Map<Character,String> charToBinaryMap;
private HuffmanNode root;
private String nuevaSalida;
public HuffmanNode getRoot(){
return this.root;
}
public String getNuevaSalida(){
return this.nuevaSalida;
}
public HuffmanCode(){
this.root = null;
this.charToBinaryMap = new HashMap<Character, String>();
}
public HuffmanNode getTree(){
return this.root;
}
/* Teniendo el código de Huffman, decodificar simplemente asigna a cada arista
* del árbol el símbolo de 0 o 1. Para esta implementación, las aristas a la izq.
* tendrán el símbolo "0" y para la derecha el símbolo "1". */
public String Decodificar(String binaryString, HuffmanNode root){
HuffmanNode current = root;
StringBuilder build = new StringBuilder();
for(int i = 0; i < binaryString.length(); i++){
if(current != null){
if((current.rightNode == null && binaryString.charAt(i) == '1') || (current.leftNode == null && binaryString.charAt(i) == '0')){
i--;
build.append(current.caracter);
current = root;
continue;
}
if(binaryString.charAt(i) == '1'){
current = current.rightNode;
}else {
current = current.leftNode;
}
}
}
if(current != null){
build.append(current.caracter);
}
return build.toString();
}
/*Codificar : Crear el árbol más óptimo para nuestra cadena de bits. */
public String Codificar(String strToCode){
Map<Character, Integer> charOcurrence = countFrequency(strToCode);
int n = charOcurrence.size();
/* Creamos una cola de prioridad con el mapeo de la ocurrencia de símbolos
que organice los símbolos de acuerdo al comparador de Huffman. */
PriorityQueue<HuffmanNode> huffmanHeap = new PriorityQueue<>(n, new HuffmanComparator());
// Recorremos el HashMap y creamos la cola de prioridad de acuerdo a la frecuencia del símbolo:
charOcurrence.forEach((key, value) -> {
HuffmanNode node = new HuffmanNode();
node.caracter = key;
node.frecuencia = value;
node.leftNode = null;
node.rightNode = null;
huffmanHeap.add(node);
});
/* Transformamos la cola prioritaria (minHeap) en un árbol de Huffman mediante
el algoritmo visto en clase. */
while(huffmanHeap.size() > 1){
HuffmanNode leaf1 = huffmanHeap.peek();
huffmanHeap.poll();
HuffmanNode leaf2 = huffmanHeap.peek();
huffmanHeap.poll();
HuffmanNode ptr = new HuffmanNode();
ptr.frecuencia = leaf1.frecuencia + leaf2.frecuencia;
ptr.caracter = '-';
ptr.leftNode = leaf1;
ptr.rightNode = leaf2;
huffmanHeap.add(ptr);
}
this.root = huffmanHeap.peek();
/* Teniendo el árbol de Huffman, buscamos las palabras código
y mostramos al usuario como se han codificado los símbolos : */
System.out.println(" Caracter | Palabra Código | Frecuencia");
System.out.println("----------------------------------");
codeWords(root, "");
/* Codificamos el input con las nuevas palabras código obtenidas : */
StringBuilder build = new StringBuilder();
for(Character ch : strToCode.toCharArray()){
build.append(this.charToBinaryMap.get(ch));
}
this.nuevaSalida = build.toString();
int pesoOriginal = strToCode.getBytes().length*8;
int pesoComprimido = nuevaSalida.length();
System.out.println("Peso original (bits) :" + pesoOriginal);
/*System.out.println("Codificación de Huffman: " + nuevaSalida);
*/
System.out.println("Longitud de la codificación de Huffman: " + nuevaSalida.length());
System.out.println("Peso post-codificación: " + pesoComprimido);
return nuevaSalida;
}
/* countFrequency : Cuenta número de ocurrencias de un caracter. */
public static Map<Character, Integer> countFrequency(String input){
HashMap<Character, Integer> mapFrequency = new HashMap<>();
for(int i = 0; i < input.length(); i++){
if(!mapFrequency.containsKey(input.toCharArray()[i])){
mapFrequency.put(input.toCharArray()[i], 1);
}else{
mapFrequency.put(input.toCharArray()[i], mapFrequency.get(input.toCharArray()[i])+1);
}
}
return mapFrequency;
}
/* Como queremos las hojas del árbol de Huffman, hacemos un simple
* recorrido in-order sobre el árbol, imprimiendo únicamente las hojas. */
public void codeWords(HuffmanNode root, String str){
if(root.leftNode != null){
codeWords(root.leftNode, str + 0);
}
if(root.leftNode == null && root.rightNode == null){
this.charToBinaryMap.put(root.caracter, str);
System.out.println(root.caracter + " | " + str + " | " + root.frecuencia);
return;
}
if(root.rightNode != null){
codeWords(root.rightNode, str + 1);
}
}
public String charList(HuffmanNode root, String str){
if(root.leftNode != null){
charList(root.leftNode, str);
}
if(root.leftNode == null && root.rightNode == null){
str = str + root.caracter;
}
if(root.rightNode != null){
charList(root.rightNode, str);
}
return str;
}
}
The ImageProcessing class, where the whole reasoning is developed, is the following:
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.image.*;
import java.io.*;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import javax.imageio.ImageIO;
public class ImageProcessing {
public static void main(String args[]) throws Exception{
/* Convert image to byte array and then, to a string */
StringBuilder build = new StringBuilder();
BufferedImage bImage = ImageIO.read(new File("/WorkSpace/HuffmanCompression/src/draken.jpg"));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(bImage, "jpg", bos );
byte [] data = bos.toByteArray();
for(int i = 0; i < data.length; i++){
build.append(data[i]);
}
/* Use Huffman code to the previous string.*/
HuffmanCode huffman = new HuffmanCode();
String prueba = huffman.Codificar(build.toString());
String pruebaDecodificada = huffman.Decodificar(prueba, huffman.getTree());
String strToByte = huffman.getNuevaSalida();
/*
String inputString = strToByte;
Charset dictionaryMap = StandardCharsets.UTF_16;
byte[] newImage = inputString.getBytes(dictionaryMap);
*/
/*Convert the binary string to a byte array and then, output the corresponding image. I copied and paste this part of the code from this blog. */
byte[] bval = new BigInteger(strToByte, 2).toByteArray();
OutputStream stream = new FileOutputStream("output.jpg");
BufferedImage image = createRGBImage(bval, bImage.getWidth(), bImage.getHeight());
try {
ImageIO.write(image, "jpg", stream);
}
finally {
stream.close();
}
}
public static BufferedImage createRGBImage(byte[] bytes, int width, int height) {
DataBufferByte buffer = new DataBufferByte(bytes, bytes.length);
ColorModel cm = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), new int[]{8, 8, 8}, false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
return new BufferedImage(cm, Raster.createInterleavedRaster(buffer, width, height, width * 3, 3, new int[]{0, 1, 2}, null), false, null);
}
}
I will be grateful if someone can help me, Thanks in advance!

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)

How do i setup BroadcastReceiver to only display sms received from specific numbers?

I need help modifying a broadcastReceiver I wrote so that it only displays incoming sms message from numbers that I can specify. right now the following code displays ALL received sms, it would be nice if the app only displayed sms from 1 specific number. can anyone provide any specifics on how I could accomplish this?
code is as follows:
public class IncomingSms extends BroadcastReceiver {
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);
// Show Alert
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context,
"senderNum: "+ senderNum + ", message: " + message, duration);
toast.show();
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
}
thanks a bunch for any help guys.
Just put one if there :)
public class IncomingSms extends BroadcastReceiver {
private static final String MY_PHONE_NUMBER = "your number here";
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
if(!MY_PHONE_NUMBER.equals(phoneNumber)) {
return;
}
...

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!

Can't place Marker in GWT Maps with Lat & Lng - Null Pointer Exception in map.addOverlay(Marker)

I'm trying to add multiple markers to my GWT-Map. If I do it with the geocoder, it works just fine... But I also get the values from a database, so I can place them via Lat Lng.
That's the code:
public static void markerSetzen(final double lat, final double lon) {
/* Markeroptionen setzen */
MarkerOptions markeroptions = MarkerOptions.newInstance();
markeroptions.setBouncy(true);
markeroptions.setBounceGravity(0.3);
final Marker marker = new Marker(LatLng.newInstance(lat, lon),
markeroptions);
map.addOverlay(marker);
marker.addMarkerClickHandler(new MarkerClickHandler() {
#Override
public void onClick(MarkerClickEvent event) {
// popup- Fenster erstellen
map.getInfoWindow().open(
LatLng.newInstance(lat, lon),
new InfoWindowContent(image + name + "<br>" + ort
+ "<br>" + kategorie + "<br><br>"
+ beschreibung + "<br>" + web));
}
});
}
The exception is always thrown at map.addOverlay(). I check the returned doubles from the db
via syso and they're just fine...
I hope someone can help,
thanks in advance
EDIT: that is the code of the geocoder method, which does what I want:
public static void koordSuchen(final double lat, final double lon,
final String ort, final String image, final String name,
final String kategorie, final String beschreibung,
final String web, final int zoomlevel) {
// Geokodierung von Adressen herausbekommen
Geocoder geocoder = new Geocoder();
geocoder.getLatLng(ort, new LatLngCallback() {
#Override
public void onSuccess(LatLng point) {
final LatLng ortKoord = LatLng.newInstance(lat, lon);
// neuen Marker erstellen
Marker marker = new Marker(ortKoord);
// neues Marker- Overlay erstellen
map.addOverlay(marker);
// Marker Klickhandler erstellen (Bei klick auf Marker oeffnet
// sich ein Popup)
marker.addMarkerClickHandler(new MarkerClickHandler() {
#Override
public void onClick(MarkerClickEvent event) {
// popup- Fenster erstellen
map.getInfoWindow().open(
ortKoord,
new InfoWindowContent(image + name + "<br>"
+ ort + "<br>" + kategorie + "<br><br>"
+ beschreibung + "<br>" + web));
}
});
}
#Override
public void onFailure() {
}
});
}
map.addOverlay() is the first instance of the variable map in your sample code. Are you sure map is initialized?