From csv to ArrayList - java

Ive been having trouble getting the data from a csv file into an arrayList so i can use it to make Polylines later. Whatever i try i can't get it to work properly. Does anyone have a pointer to what im doing wrong.
Im using a Toast to temporarly see the result.
Im expecting the code to give me an ArrayList, but it just returns me a empty list
Im adding the maps activity where this should happen and the function that writes the file in the mainActivity
MapsActivity;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
FileInputStream fileInputStream = openFileInput("trip_file");
InputStreamReader inputReader = new InputStreamReader(fileInputStream);
BufferedReader BufferedReader = new BufferedReader(inputReader);
List<LatLng> latLngList = new ArrayList<LatLng>();
String line = "";
try {
while( (line = BufferedReader.readLine()) != null) // Read until end of file
{
double lat = Double.parseDouble(line.split(", ")[0]);
double lon = Double.parseDouble(line.split(", ")[1]);
latLngList.add(new LatLng(lat, lon));
}
} catch (IOException e) {
e.printStackTrace();
}
String teest = String.valueOf(latLngList);
Toast.makeText(getBaseContext(), teest,
Toast.LENGTH_SHORT).show();
}
}
This code in MainActivity writes the file;
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lon = location.getLongitude();
myList.add(lat);
myList.add(lon);
String file_name = "trip_file";
try {
String skrive = String.valueOf(myList);
FileOutputStream fileOutputStream = openFileOutput(file_name, MODE_PRIVATE);
fileOutputStream.write(skrive.getBytes());
fileOutputStream.close();
Toast.makeText(getApplicationContext(), "Location saved",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

I suggest you use CSVParser (Apache 2.0 licence) which is nice and simple:
https://github.com/OpenBD/openbd-core/tree/master/src/au/com/bytecode/opencsv

Related

I want to get marker from json

the error is "Error connecting to service"
public class MarkerTask extends AsyncTask<Void, Void, String>
{
private static final String LOG_TAG = "ExampleApp";
private static final String SERVICE_URL = "https://192.168.8.103/map1.php";
private GoogleMap mMap;
// Invoked by execute() method of this object
#Override
protected String doInBackground(Void... args) {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
// Connect to the web service
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Read the JSON data into the StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to service", e);
//throw new IOException("Error connecting to service", e); //uncaught
} finally {
if (conn != null) {
conn.disconnect();
}
}
return json.toString();
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String json) {
try {
// De-serialize the JSON string into an array of city objects
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
LatLng latLng = new LatLng(jsonObj.getJSONArray("marker").getDouble(0),
jsonObj.getJSONArray("marker").getDouble(1));
//move CameraPosition on first result
if (i == 0) {
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng).zoom(13).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
// Create a marker for each city in the JSON data.
mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
.title(jsonObj.getString("name"))
.snippet(Integer.toString(jsonObj.getInt("population")))
.position(latLng));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON", e);
}
}
}
My map Activity
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
if (mapFragment != null) {
//setUpMap();
new MarkerTask().execute();
}
}}

getMapAsync error - Google maps api android

So Im trying to display markers on my map from a Jsonfile and they are not appearing Ive narrowed it down to the line
map = mapFragment.getMapAsync(this);
it gives me the error
Incompatible types:
Required: com.google.android.gms.maps.GoogleMap Found: Void
Here is the rest of the code:
public class MainActivity extends FragmentActivity implements OnMapReadyCallback {
private static final String LOG_TAG = "ExampleApp";
private static final String SERVICE_URL = "https://api.myjson.com/bins/4jb09";
protected GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (map == null) {
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
map = mapFragment.getMapAsync(this);
if (map != null) {
//setUpMap();
new MarkerTask().execute();
}
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
setUpMap();
}
private void setUpMap() {
// Retrieve the city data from the web service
// In a worker thread since it's a network operation.
new Thread(new Runnable() {
public void run() {
try {
retrieveAndAddCities();
} catch (IOException e) {
Log.e(LOG_TAG, "Cannot retrive cities", e);
return;
}
}
}).start();
}
protected void retrieveAndAddCities() throws IOException {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
// Connect to the web service
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Read the JSON data into the StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to service", e);
throw new IOException("Error connecting to service", e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
// Create markers for the city data.
// Must run this on the UI thread since it's a UI operation.
runOnUiThread(new Runnable() {
public void run() {
try {
createMarkersFromJson(json.toString());
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON", e);
}
}
});
}
void createMarkersFromJson(String json) throws JSONException {
// De-serialize the JSON string into an array of city objects
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
// Create a marker for each city in the JSON data.
JSONObject jsonObj = jsonArray.getJSONObject(i);
map.addMarker(new MarkerOptions()
.title(jsonObj.getString("name"))
.snippet(Integer.toString(jsonObj.getInt("population")))
.position(new LatLng(
jsonObj.getJSONArray("latlng").getDouble(0),
jsonObj.getJSONArray("latlng").getDouble(1)
))
);
}
}
private class MarkerTask extends AsyncTask<Void, Void, String> {
private static final String LOG_TAG = "ExampleApp";
private static final String SERVICE_URL = "https://api.myjson.com/bins/4jb09";
// Invoked by execute() method of this object
#Override
protected String doInBackground(Void... args) {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
// Connect to the web service
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Read the JSON data into the StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to service", e);
//throw new IOException("Error connecting to service", e); //uncaught
} finally {
if (conn != null) {
conn.disconnect();
}
}
return json.toString();
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String json) {
try {
// De-serialize the JSON string into an array of city objects
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
LatLng latLng = new LatLng(jsonObj.getJSONArray("latlng").getDouble(0),
jsonObj.getJSONArray("latlng").getDouble(1));
//move CameraPosition on first result
if (i == 0) {
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng).zoom(13).build();
map.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
// Create a marker for each city in the JSON data.
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
.title(jsonObj.getString("name"))
.snippet(Integer.toString(jsonObj.getInt("population")))
.position(latLng));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON", e);
}
}
}
}
Change it to
map.getMapAsync(this);
instead of
map = mapFragment.getMapAsync(this);
because
#Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap = googleMap;
}
return type of this method is void, so it will not return anything.
You have to do this:
map.getMapAsync(this)
mapFragment.getMapAsync(this); has return type Void
Change your setUpMapIfNeeded() to following one
private void setUpMapIfNeeded() {
if (map == null) {
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
}
Do the marker setting work in onMapReady().
Use SupportMapFragment instead of MapFragment.You can take help from following code sample.
Define MapFragment as :
private SupportMapFragment supportMapFragment;
GoogleMap mGoogleMap; //for google map
And in your activity creation, you can do like this:
if(supportMapFragment==null){
supportMapFragment = (SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
//do load your map and other map stuffs here...
}
});
hope this will help you ...
Your code is returning this error Incompatible types: Required: com.google.android.gms.maps.GoogleMap Found: Void
because getMapAsync() does not return anything. If you look at the documentation for this function:
public void getMapAsync (OnMapReadyCallback callback)
Sets a callback object which will be triggered when the GoogleMap instance is ready to be used.
Note:
This method must be called from the main thread. The callback will be executed in the main thread. In the case where Google Play services is not installed on the user's device, the callback will not be triggered until the user installs it. In the rare case where the GoogleMap is destroyed immediately after creation, the callback is not triggered. The GoogleMap object provided by the callback is non-null.
OnMapReadyCallback is an interface that needs implemented and passed to through this function. Nothing is currently assigned to your googleMap variable you should instead set its value in this block of code which implements OnMapReadyCallback
#Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap = googleMap;
}

Async and Google Maps

Here:Async and ListView Android
I asked about Async and Listview. Now I have a problem with Async and Maps. I want to set a marker with JSON that returns Async. Unfortunately, I set the default values and those that do not want to. You can help
public class MarkerInfo extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private LatLng sydney;
private String longituide;
private String latitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_marker_info);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Bundle bundle_list = getIntent().getExtras();
final String name_item = bundle_list.getString("name");
JSONObject toSend = new JSONObject();
try {
toSend.put("action", "getAllMarkers");
} catch (JSONException e) {
e.printStackTrace();
}
JSONTransmitter asyncTask = (JSONTransmitter) new JSONTransmitter(new JSONTransmitter.AsyncResponse() {
#Override
public void processFinish(String output) {
try {
JSONArray pages = new JSONArray(output);
for (int i = 0; i < pages.length(); ++i) {
JSONObject rec = pages.getJSONObject(i);
String name_task = rec.getString("nazwa");
latitude = rec.getString("latitude");
longituide = rec.getString("longitude");
mMap.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(longituide), Double.parseDouble(latitude))));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}).execute(toSend);
}
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
}
Execute your async map dependent operation (adding markers), after google map ready.
JSONTransmitter asyncTask;
GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
mapFragment.getMapAsync(this);
asyncTask = (JSONTransmitter) new JSONTransmitter(new JSONTransmitter.AsyncResponse() {
#Override
public void processFinish(String output) {
try {
JSONArray pages = new JSONArray(output);
for (int i = 0; i < pages.length(); ++i) {
JSONObject rec = pages.getJSONObject(i);
String name_task = rec.getString("nazwa");
latitude = rec.getString("latitude");
longituide = rec.getString("longitude");
mMap.addMarker(new MarkerOptions().position(
new LatLng(Double.parseDouble(longituide), Double.parseDouble(latitude))));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
JSONObject toSend = new JSONObject();
try {
toSend.put("action", "getAllMarkers");
} catch (JSONException e) {
e.printStackTrace();
}
asyncTask.execute(toSend);
}

Get longitude and latitude values to post into url - Android

I am creating an Android app that pulls XML data. I want to be able to use the longitude and latitude values to post into the web link to get specific XML data for the users current location.
Here is my code so far, which does not work:
public class GeoSplashActivity extends Activity {
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
private String GEORSSFEEDURL = "http://www.socialalertme.com/mobilealerts.xml?lat="+latitude+"lng="+longitude+"&distance=20";
GeoRSSFeed feed3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash2);
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null
&& !conMgr.getActiveNetworkInfo().isConnected()
&& !conMgr.getActiveNetworkInfo().isAvailable()) {
// No connectivity - Show alert
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Unable to reach server, \nPlease check your connectivity.")
.setTitle("TD RSS Reader")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
// Connected - Start parsing
new AsyncLoadXMLFeed().execute();
}
}
private class AsyncLoadXMLFeed extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Obtain feed
GeoDOMParser myParser = new GeoDOMParser();
feed3 = myParser.parseXml(GEORSSFEEDURL);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed3);
// launch List activity
Intent intent = new Intent(GeoSplashActivity.this, GeoListActivity.class);
intent.putExtras(bundle);
startActivity(intent);
// kill this activity
finish();
}
}
}
I have never used the location stuff before, so I'm not entirely sure what I'm doing here. If anyone could give some pointers, I'd really appreciate it!
Hopefully you are not forgetting
<uses-permission android:name=“android.permission.ACCESS_FINE_LOCATION”></uses-permission>
in your manifest file. This tutorial can help you to get better understanding.
Edit
Google already have provided Training to get current Location.
//Get coordinates if available:
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Location loc;
double latitude=0,longitude=0;
if ( ( loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER) )!=null ){
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}else if( ( loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER) )!=null ){
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
//If any coordinate value is recieved, use it.
if(latitude!=0 || longitude!=0){
String latitude = String.valueOf(latitude);
String longitude = String.valueOf(longitude);
//TODO post into url
}
You should move initialization of location variables to the onCreate method. Also you should also check if location != null:
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
longitude = location.getLongitude();
latitude = location.getLatitude();
GEORSSFEEDURL = "http://www.socialalertme.com/mobilealerts.xml?lat="+latitude+"lng="+longitude+"&distance=20";
} else {
...
}
I am doing the same thing, and this works for me!
But, the server I am requestiong is a node.js server, and the data is in JSON.
public class GetWeatherDataRest extends AsyncTask<Void, Void, String> {
private static final String TAG = "GetWeatherDataRest";
// get lat and long from main activity
double lat = MyActivity.lat;
double lng = MyActivity.lng;
// the url
String url = "http://ThisIsTheAddress/weather/5days?lat="+lat+"&lng="+lng;
public MyActivity context;
private List<Weather> posts;
public GetWeatherDataRest(MyActivity activity){
this.context = activity;
}
#Override
protected String doInBackground(Void... params) {
try {
//Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
//Perform the request and check the status code
HttpResponse response = client.execute(get);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
posts = new ArrayList<Weather>();
posts = Arrays.asList(gson.fromJson(reader, Weather[].class));
content.close();
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
}
} else {
Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
}
return null;
}
#Override
protected void onPostExecute(String result) {
context.updateFields(posts);
}
}
Okey! This is my GpsFragment, where I get the lng and lat!
I am not done with this yet, so It might not look like much, but it works, also it gives an address from the lng & lat using geocoder
You should implement the LocationListener.
public class GpsFragment extends Fragment implements LocationListener{
public Location location;
LocationManager locationManager;
String provider;
List<Address> mAddresses;
TextView mAddress1;
TextView mAddress2;
public static double lat;
public static double lng;
private static final String TAG = "MyGps";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myInflatedView = inflater.inflate(R.layout.gps_fragment, container,false);
mAddress1 = (TextView) myInflatedView.findViewById(R.id.address_text);
mAddress2 = (TextView) myInflatedView.findViewById(R.id.address_text2);
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 100, 1, this);
if(location != null){
onLocationChanged(location);
Log.v(TAG, "Location available!");
}
else{
mAddress1.setText("No location");
Log.e(TAG, "Location not available!");
}
return myInflatedView;
}
// So i think this is what you need! the 'onLocationChanged'
#Override
public void onLocationChanged(Location location) {
this.location = location;
lat = location.getLatitude();
lng = location.getLongitude();
Geocoder mLocation = new Geocoder(getActivity().getApplicationContext(), Locale.getDefault());
try {
mAddresses = mLocation.getFromLocation(lat, lng, 1);
if(mAddresses != null) {
Address returnedAddress = mAddresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
// mAddress.setText(strReturnedAddress.toString());
//mAddress1.setText("lat"+lat);
//mAddress2.setText("lng"+lng);
mAddress1.setText("Address: "+returnedAddress.getAddressLine(0).toString());
mAddress2.setText("City: "+returnedAddress.getAddressLine(1).toString());
}
else{
// mAddress.setText("No Address returned!");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//mAddress.setText("Cannot get Address!");
}
((MyActivity)getActivity()).fetchData();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}

Asyntask #1 Android error

NEW VERSION 1.1
Hi guys. I tried to follow your recommendations and now i'm trying to redo the code.
I added this part of the code to work on the Main Thread the GoogleMaps markers.
The problem is, when i call the Ubic() function, i get this error:
http://i.imgur.com/QD7JZjRh.jpg
http://i.imgur.com/xvzJ9ckh.jpg
This is the code that i added an the error is caused by String Latlon[][] = com.Ubic();
public class BuscarContrincantes extends FragmentActivity implements
LocationListener {
GoogleMap googlemapa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buscarcontrincante);
SupportMapFragment maps = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
googlemapa = maps.getMap();
googlemapa.setMyLocationEnabled(true);
googlemapa.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googlemapa.getUiSettings().setCompassEnabled(true);
googlemapa.getUiSettings().setZoomControlsEnabled(true);
googlemapa.getUiSettings().setAllGesturesEnabled(true);
double latitud;
double longitud;
String nombre;
Datos com = new Datos();
String latlon[][] = com.Ubic(); //HERE IS THE PROBLEM!
for (int i = 0; i < latlon.length - 1; i++) {
latitud = Double.parseDouble(latlon[i][0]);
longitud = Double.parseDouble(latlon[i][3]);
nombre = (latlon[i][2]);
LatLng posicion = new LatLng(latitud, longitud);
googlemapa.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.icono_canchas))
.position(posicion).title(nombre));
}
}
VERSION 1.0
I'm having a problem with a project that i'm doing for my college.
Actually, i'm trying to set a Marker on a Map (With Google Maps) that his information is on a MySQL Database.
The code is:
BuscarContrincantes.java
public class BuscarContrincantes extends FragmentActivity implements
LocationListener {
GoogleMap googlemapa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buscarcontrincante);
SupportMapFragment maps = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
googlemapa = maps.getMap();
googlemapa.setMyLocationEnabled(true);
googlemapa.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googlemapa.getUiSettings().setCompassEnabled(true);
googlemapa.getUiSettings().setZoomControlsEnabled(true);
googlemapa.getUiSettings().setAllGesturesEnabled(true);
new RetreiveFeedTask().execute();
}
class RetreiveFeedTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... args) {
double lat;
double lon;
String nombre;
Datos com = new Datos(); // File Datos.java
String latlon[][] = com.Ubic();
for (int i = 0; i < latlon.length - 1; i++) {
lat = Double.parseDouble(latlon[i][0]);
lon = Double.parseDouble(latlon[i][4]);
nombre = (latlon[i][2]);
LatLng pos3 = new LatLng(lat, lon);
googlemapa.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.icono_canchas))
.position(pos3).title(nombre));
}
return null;
}
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}}
Datos.java
public class Datos {
public String[][] Ubic() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://MY.IP/FOLDER/QUERY.php");
try {
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
JSONObject object = new JSONObject(jsonResult);
JSONArray arr = object.getJSONArray("products");
String[] lat = new String[arr.length()+1];
String[] lon = new String[arr.length()+1];
String[] nombre = new String[arr.length() + 1];
String[][] latlon = new String[arr.length() + 1][5];
for (int i = 0; i < arr.length(); i++) {
lat[i] = arr.getJSONObject(i).getString("latitude");
lon[i] = arr.getJSONObject(i).getString("longitude");
name[i] = arr.getJSONObject(i).getString("name");
latlon[i][0] = lat[i];
latlon[i][6] = lon[i];
latlon[i][2] = name[i];
}
return latlon;
} catch (JSONException e) {
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
private static String parse(String string) {
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
}
return answer;
}}
This code is trying to get Latitude, Longitude and Name of an object that is on a MySQL Database and must put this object on the Map, but i'm getting the AsynkTask #1 Error and i don't know why this is happening.
¿Can you help me, please? I'm getting really mad with this code and i don't know why this isn't working.
P.S: Sorry for my bad English. I'm from Chile :P
You can not access the GoogleMap instance at doInBackground method. The GoogleMap can only be read and modified from the main thread. Just the HTTP request shall be on background task.
You need to modify doInBackground to return the list of coordinates and implement the GoogleMap update at onPostExecute method (at main thread).
Here is the code based on Version 1.1:
GoogleMap googlemapa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buscarcontrincante);
SupportMapFragment maps = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googlemapa = maps.getMap();
googlemapa.setMyLocationEnabled(true);
googlemapa.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googlemapa.getUiSettings().setCompassEnabled(true);
googlemapa.getUiSettings().setZoomControlsEnabled(true);
googlemapa.getUiSettings().setAllGesturesEnabled(true);
new RetreiveFeedTask().execute();
}
class RetreiveFeedTask extends AsyncTask<Void, Void, String[][]> {
#Override
protected String[][] doInBackground(Void... args) {
// Execute the HTTP request on background task
Datos com = new Datos(); // File Datos.java
return com.Ubic();
}
#Override
protected void onPostExecute(String[][] latlon) {
double latitud;
double longitud;
String nombre;
// Update the UI
for (int i = 0; i < latlon.length - 1; i++) {
latitud = Double.parseDouble(latlon[i][0]);
longitud = Double.parseDouble(latlon[i][3]);
nombre = (latlon[i][2]);
LatLng posicion = new LatLng(latitud, longitud);
googlemapa.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.icono_canchas)).position(posicion).title(nombre));
}
}
}

Categories