How to draw the current location information in osmdroid - java

Assumption and what I want to achieve
 I'm working on an application that receives current location information from an external RTK-GPS via serial communication, and draws dots or lines on an osmdroid map.
 I have already realized receiving the location information and converting the received data to a type that can be displayed on TextView.
For serial communication, I am using FTDI's "usb-serial-for-android" library, and for map functions, I am using "osmdroid".
Currently
Receive location data from RTK-GPS via serial communication.
Get the latitude and longitude in double type from the received data (String type).
Create a GeoPoint from the acquired latitude and longitude, set it to a marker, and draw it on the map. At this time, the GeoPoint is also stored in the GeoPoint list.
The following procedure is used to display the marker of the current location on the map. Currently, the received latitude and longitude are set to the marker and all the markers are drawn.
Eventually, I'd like to draw the trajectory of movement as a line while updating the current location marker.
Problems and error messages
The problem we are experiencing is that when we start drawing, the application immediately becomes sluggish and freezes.
Since 10 data are sent from GPS per second, if we try to draw all the received data on the map, the number of markers will be huge and the app will freeze.
Therefore, we tried to draw markers in 10 marker skips, but even so, the application became sluggish and froze as soon as it started drawing.
Next, when the number of data exceeded 100, I deleted the oldest data first, and the application did not freeze after starting drawing. However, I don't think it is possible to draw all the loci with this method. If possible, I would like to draw all the loci that have been moved.
My questions are as follows.
Is it possible to draw the movement locus using the above method and policy?
Is it impossible to draw such a moving locus in Android?
Does OSMDROID have a function to draw the movement locus?
Are there any similar questions?
Please let me know.
Here is my code.
public class MapGeneratorMainActivity extends Activity {
private static final double MAP_ZOOM = 15.0;
private static final double MAP_ZOOM2 = 17.0;
static MapView mapGeneratorMainMap = null;
public static List<Marker> currentMarkers = new ArrayList<>();
ArrayList<GeoPoint> currentPoints = new ArrayList<>();
ArrayList<GeoPoint> currentPoints2hz = new ArrayList<>();
ArrayList<Polyline> currentTrajectory = new ArrayList<>();
public static int receiveCount = 0;
public static GeoPoint currentP2hz;
public MapGeneratorMainActivity() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
org.osmdroid.config.Configuration.getInstance().load(getApplicationContext(),
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()));
setContentView(R.layout.map_generator_main_activity);
MapView mapGeneratorMainMap = findViewById(R.id.MapGaneratorMainMap);
mapGeneratorMainMap.setMultiTouchControls(true);
IMapController mapController = mapGeneratorMainMap.getController();
mapController.setZoom(MAP_ZOOM);
GeoPoint centerPoint = new GeoPoint(aveLat, aveLon);
mapController.setCenter(centerPoint);
mapGeneratorMainMap.setTilesScaledToDpi(true);
final MapTileProviderBasic tileProvider = new MapTileProviderBasic(getApplicationContext());
ITileSource tileSource = new XYTileSource("GSI", 14, 24, 256, ".jpg", new String[]{TILE_SEVER});
tileProvider.setTileSource(tileSource);
final TilesOverlay tilesOverlay = new TilesOverlay(tileProvider, this.getApplicationContext());
tilesOverlay.setLoadingBackgroundColor(Color.TRANSPARENT);
mapGeneratorMainMap.getOverlays().add(tilesOverlay);
mapGeneratorMainMap.invalidate();
FloatingActionButton myLocationButton = findViewById(R.id.myLocationButton);
myLocationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentService = new Intent(getApplication(), gpsService.class); //位置情報受信サービス
intentService.putExtra("REQUEST_CODE", 1);
startForegroundService(intentService);
}
});
//Receiver
UpdateReceiver receiver = new UpdateReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("DO_ACTION");
registerReceiver(receiver, filter);
}
protected class UpdateReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String currentLat = null;
String currentLon = null;
MapView mapGeneratorMainMap = findViewById(R.id.MapGaneratorMainMap);
mapGeneratorMainMap.setMultiTouchControls(true);
IMapController mapController = mapGeneratorMainMap.getController();
mapController.setZoom(MAP_ZOOM2);
Bundle extras = intent.getExtras();
String msg = extras.getString("message"); //String型の位置情報
TextView currentLocatonTextView = findViewById(R.id.CurrentLocation);
currentLocatonTextView.setText(msg);
String[] currentLocaton = msg.split(",", -1);
currentLat = currentLocaton[0];
currentLon = currentLocaton[1];
double Lat = Double.parseDouble(currentLat);
double Lon = Double.parseDouble(currentLon);
GeoPoint currentP = new GeoPoint(Lat, Lon);
if(receiveCount == 0){
currentP2hz = new GeoPoint(Lat, Lon);
currentPoints.add(currentP);
currentPoints2hz.add(currentP2hz);
currentPtMarker = new Marker(mapGeneratorMainMap);
Drawable currentMarkerIcon = ResourcesCompat.getDrawable(getResources(), R.drawable.current_point_marker, null);
currentPtMarker.setIcon(currentMarkerIcon);
currentPtMarker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER);
currentPtMarker.setPosition(currentP);
currentMarkers.add(currentPtMarker);
mapGeneratorMainMap.getOverlayManager().add(currentPtMarker);
mapGeneratorMainMap.invalidate();
}
else if(receiveCount == 100) {
currentPoints.add(currentP);
currentP2hz = new GeoPoint(Lat, Lon);
currentPoints2hz.add(currentP2hz);
receiveCount = 0;
currentPtMarker = new Marker(mapGeneratorMainMap);
Drawable currentMarkerIcon = ResourcesCompat.getDrawable(getResources(), R.drawable.current_point_marker, null);
currentPtMarker.setIcon(currentMarkerIcon);
currentPtMarker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER);
currentPtMarker.setPosition(currentP);
currentMarkers.add(currentPtMarker);
mapGeneratorMainMap.getOverlayManager().add(currentPtMarker);
mapGeneratorMainMap.invalidate();
}
if(currentMarkers.size() >= 100){
currentMarkers.get(0).remove(mapGeneratorMainMap);
currentMarkers.remove(0);
}
receiveCount += 1;
}
}

Good morning everyone.
I was able to solve this problem.
The reason why it didn't work was that some of the data received by serial communication was not good.
After eliminating this bad data and receiving only the good data, I was able to do what I wanted.
thanks so much.

Related

Parsing JSON to array not working when back button pressed

I'm having some trouble with an issue in my Android Studio application that is to do with pressing the back button. Basically the user inputs into a text view and another method (not included as it works fine but I can post if requested) searches an API for the relevant data and displays it in a recycler view. Then the user makes a selection from the recycler view and the method below parses a JSON file and adds relevant data from it to an array in a separate class "Director". Once this happens the next activity "GraphActivity" starts and draws a number of nodes on a canvas for each director in the array.
The issue I am having is that when I make an input into the text view and then press the back button to close the soft keyboard on my Android device (it covers up the recycler view) and go through the steps I just mentioned, when the GraphActivity activity starts it does not work (no nodes are drawn). However, if I then press the back button to go back to the first activity and then make the same selection from the recycler view again, it works.
From what I can tell, the issue seems to be with the data being added to the "Director" array but I cannot figure out what is causing it, Logcat shows that the first time the GraphActivity activity starts the "Director" array is empty and therefore, no nodes are drawn but when I press back and then make the same selection again the array has the correct data and the nodes are drawn.
I would really appreciate some help with this as I am very new to Android Studio and have been searching around for hours to try and find a solution.
public class MainActivity extends AppCompatActivity implements MainAdapter.OnCompanyClickedListener {
private RecyclerView recyclerView;
private TextView userInput;
private Button search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.rView);
RecyclerView.LayoutManager manager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(manager);
}
//Parse JSON File
public void searchCompanyDirectors(final String companyNumber){
Thread thread = new Thread(new Runnable(){
#Override
public void run(){
HttpClient httpClient = new HttpClient();
try{
final String response = httpClient.run("myURL");
runOnUiThread(new Runnable(){
#Override
public void run(){
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("items");
for (int i = 0; i < array.length();i++){
JSONObject o = array.getJSONObject(i);
String appointment = o.getString("links");
String parsedAppointment = parseApp(appointment);
Director director = new Director(o.getString("name"),parsedAppointment);
Director.directorList.add(director);
}
}catch (JSONException e){
e.printStackTrace();
}
}
});
}
catch (Exception ex){
ex.printStackTrace();
}
}
});
thread.start();
}
#Override
public void onCompanyClicked(int position) {
Toast.makeText(this,Company.companyList.get(position).getTitle(),Toast.LENGTH_LONG).show();
chosenCompanyNumber = Company.companyList.get(position).getCompanyNumber();
chosenCompany = Company.companyList.get(position).getTitle();
searchCompanyDirectors(chosenCompanyNumber);
Intent intent = new Intent(this,GraphActivity.class);
startActivity(intent);
}
}
The GraphActivity class:
public class GraphActivity extends AppCompatActivity {
DrawGraph drawGraph;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawGraph = new DrawGraph(this);
setContentView(drawGraph);
The DrawGraph class:
public class DrawGraph extends View {
private Paint p1;
private Paint p2;
private Paint p3;
private Paint paint;
private Path path;
private Point point1;
private int radius = 300;
double x;
double y;
double angle;
int mWidth = this.getResources().getDisplayMetrics().widthPixels;
int mHeight = this.getResources().getDisplayMetrics().heightPixels;
List<Director> directorList = Director.getDirectorList();
private String chosenCompany = MainActivity.getChosenCompany();
private static List<Float> ordinates = new ArrayList<>();
public DrawGraph(Context context) {
super(context);
p1 = new Paint(Paint.ANTI_ALIAS_FLAG);
p1.setStrokeWidth(10);
p2 = new Paint(Paint.ANTI_ALIAS_FLAG);
p2.setStrokeWidth(10);
p3 = new Paint(Paint.ANTI_ALIAS_FLAG);
p3.setStrokeWidth(5);
path = new Path();
paint = new Paint();
point1 = new Point(mWidth/2, mHeight/2);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Colors
p1.setStyle(Paint.Style.FILL);
p1.setColor(Color.RED);
p2.setStyle(Paint.Style.FILL);
p2.setColor(Color.GREEN);
p3.setStyle(Paint.Style.STROKE);
p3.setColor(Color.CYAN);
paint.setColor(Color.BLACK);
paint.setTextSize(18f);
paint.setAntiAlias(true);
paint.setTextAlign(Paint.Align.CENTER);
Rect bounds = new Rect();
paint.getTextBounds(chosenCompany, 0, chosenCompany.length(),bounds);
//Draw company and directors
for (int i = 1; i <= directorList.size(); i++)
{
//Divide the company node
angle = i * (360/directorList.size());
x = point1.x + radius * cos(angle);
y = point1.y + radius * sin(angle);
//Draw directors
canvas.drawCircle((float)x,(float)y - (bounds.height() / 2), bounds.width() + 5,p2);
canvas.drawText(directorList.get(i-1).getName(),(float)x,(float)y,paint);
}
Okay, I've found an issue in DrawGraph class noted here;
List<Director> directorList = Director.getDirectorList();
private String chosenCompany = MainActivity.getChosenCompany();
You should not directly access the data objects of one activity from another. The previous activity could be destroyed etc as per Android OS and its lifecycle. You must think of it like out of sight, out of memory; which can cause the current activity to not be able to access the data in the previous one.
You'd need to properly send the parsed data from your JSON file, the variables List directorList and the String chosenCompany from your MainActivity to GraphActivity.
You can send data from one activity to another by adding it to the intent with which you call the next activity. The Intent class has features to help you send a small amount of information via itself; called putExtra() and getExtra(). More about them here.
You will need to add those variable datasets through intent.putExtra and fetch them back in your other activity onCreate by using getExtras.
Activity A >> Intent call to Activity B + Data >> Activity B
Hope this helps.

Update gps location in android studio every couple seconds

I am new to android development but am taking a shot at making myself a golf rangefinder.. I have this activity -
public class hole_1 extends Activity implements View.OnClickListener {
Button nextBtn;
GPSTracker gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hole_1);
gps = new GPSTracker(hole_1.this);
// Get Variable From Home Activity
Bundle extras = getIntent().getExtras();
String course = null;
if (extras != null) {
course = extras.getString("Course");
}
//Set Next Hole Button
nextBtn = (Button) findViewById(R.id.nextButton);
nextBtn.setOnClickListener(this);
gps = new GPSTracker(hole_1.this);
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
double lat2 = 39.765718;
double lon2 = -121.860080;
Location loc1 = new Location("");
loc1.setLatitude(latitude);
loc1.setLongitude(longitude);
Location loc2 = new Location("");
loc2.setLatitude(lat2);
loc2.setLongitude(lon2);
float distanceInMeters = loc1.distanceTo(loc2);
int myDist = (int) (distanceInMeters * 1.0936);
TextView latView = (TextView) findViewById(R.id.yardage);
latView.setText(String.valueOf(myDist));
}else{
gps.showSettingsAlert();
}
}
#Override
public void onClick(View v) {
Intent myIntent = new Intent(this, end.class);
myIntent.putExtra("Hole",1);
startActivity(myIntent);
}
}
What I would like to do is update the myDist variable which is the distance between my current coordinates and the fixed coordinates (lat2, lon2). I have done some research and found asyncTask, threading and setting a timer but cannot figure out the best method for this application.. The app works great as is but I have to refresh the page to get updated distances and would like it to just update itself every few seconds.. What should I do?
Thanks!
1)You can't update every couple of seconds. GPS only updates every 30s to a minute.
2)You wouldn't use an async task here or any oter form of threading, GPS works on a callback system. You request updates and it will call you back whenever an update is available.
3)DO NOT USE the GpsTracker LIBRARY EVER. It's broken. Badly. See the full writeup I have on why its broken at http://gabesechansoftware.com/location-tracking/

Arcgis: multiple pins on map

Hie,
I would like to put multiple pins on the map. Currently, I have one pin displayed on map. I tried writing more than one location name but it loads only one location ..
This is my code.
public class test extends Activity {
MapView mMapView = null;
ArcGISTiledMapServiceLayer mapLayer;
GraphicsLayer grahpicslayer = new GraphicsLayer();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Geocoder gc = new Geocoder(this, Locale.getDefault());
try {
String locationName = "";
//Change this to respective library
//The library name get from the NLB rss feed from the previous page
//pin 1
locationName = "Bishan Public Library";
//pin2
locationName = "Hougang";
//pin3
locationName = "Sengkang";
//get list of address base on location name
List<Address> list = gc.getFromLocationName(locationName,1);
//get the first result appear on the list
Address address = list.get(0);
//get the latitude of that address
double lat = address.getLatitude();
//get the longitude of that address
double lng = address.getLongitude();
// Retrieve the map and initial extent from XML layout
mMapView = (MapView)findViewById(R.id.map);
/* create a #ArcGISTiledMapServiceLayer */
mapLayer = new ArcGISTiledMapServiceLayer(
//"http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer");
"http://e1.onemap.sg/ArcGIS/rest/services/SM128/MapServer");
// Add tiled layer to MapView
mMapView.addLayer(mapLayer);
SpatialReference worldMap = SpatialReference.create(4326);
SpatialReference oneMap = SpatialReference.create(3414);
//Set the point to the longitude and latitude
Point point = new Point(lng,lat);
//Point point = new Point(103.799598,1.443603);
//Change world spatial reference to one map reference
Point oneMapPoint = (Point) GeometryEngine.project(point, worldMap, oneMap);
//create red color diamond graphics
grahpicslayer.addGraphic(new Graphic(oneMapPoint,new SimpleMarkerSymbol(Color.RED,20,STYLE.CIRCLE)));
//Display the red color diamond graphics
mMapView.addLayer(grahpicslayer);
//zoom the map to the location
mMapView.zoomToResolution(oneMapPoint, 0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Error");
}
}
You're only calling addGraphic once, so of course you're only getting one graphic.
For each of your place-names, you'll need to geocode, create and project a point, and create and add a graphic. Right now, you're only doing those things for one place-name: "Sengkang". Use an array of place-names and a for loop. Better yet, make a method and call it three times.

onMarkerClick using switch Case

I want to make marker Application using Google Maps but . I Have problem about onMarkerClick using switch Case, Iam using array to add Marker to My Application and when marker OnCLick he can call different Activity for each marker .I Have problom about that.. How I can using onMarkerClick with switch case for my application..??? Please Help . Here is My Code :
public static final String TAG = markerbanyak.TAG;
final LatLng CENTER = new LatLng(43.661049, -79.400917);
class Data {
public Data(float lng, float lat, String title, String snippet, String icon) {
super();
this.lat = (float)lat;
this.lng = (float)lng;
this.title = title;
this.snippet = snippet;
this.icon = icon;
}
float lat;
float lng;
String title;
String snippet;
String icon;
}
Data[] data = {
new Data(-79.400917f,43.661049f, "New New College Res",
"Residence building (new concrete high-rise)", "R.drawable.mr_kun"),
new Data(-79.394524f,43.655796f, "Baldwin Street",
"Here be many good restaurants!", "R.drawable.mr_kun"),
new Data(-79.402206f,43.657688f, "College St",
"Lots of discount computer stores if you forgot a cable or need to buy hardware.", "R.drawable.mr_kun"),
new Data(-79.390381f,43.659878f, "Queens Park Subway",
"Quickest way to the north-south (Yonge-University-Spadina) subway/metro line", "R.drawable.mr_kun"),
new Data(-79.403732f,43.666801f, "Spadina Subway",
"Quickest way to the east-west (Bloor-Danforth) subway/metro line", "R.drawable.mr_kun"),
new Data(-79.399696f,43.667873f, "St George Subway back door",
"Token-only admittance, else use Spadina or Bedford entrances!", "R.drawable.mr_kun"),
new Data(-79.384163f,43.655083f, "Eaton Centre (megamall)",
"One of the largest indoor shopping centres in eastern Canada. Runs from Dundas to Queen.", "R.drawable.mr_kun"),
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.peta);
SupportMapFragment supportMapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
// Getting a reference to the map
mMap = supportMapFragment.getMap();
Marker kuningan = mMap.addMarker(new MarkerOptions()
.position(KUNINGAN)
.title("Kuningan")
.snippet("Kuningan ASRI")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.mr_kun)));
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(KUNINGAN, 2));
// Zoom in, animating the camera.
mMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
}
public void wisata(){
if (mMap==null) {
Log.d(TAG, "Map Fragment Not Found or no Map in it!!");
return;
}
for (Data d : data) {
LatLng location = new LatLng(d.lat, d.lng);
Marker wisata =mMap.addMarker(new MarkerOptions()
.position(location)
.title(d.title)
.snippet(d.snippet)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.mr_wis)));
// Let the user see indoor maps where available.
mMap.setIndoorEnabled(true);
// Enable my-location stuff
mMap.setMyLocationEnabled(true);
// Move the "camera" (view position) to our center point.
mMap.moveCamera(CameraUpdateFactory.newLatLng(CENTER));
// Then animate the markers while the map is drawing,
// since you can't combine motion and zoom setting!
final int zoom = 14;
mMap.animateCamera(CameraUpdateFactory.zoomTo(zoom), 2000, null);
mMap.setOnMarkerClickListener(new OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker v) {
// TODO Auto-generated method stub
//(PLEASE HELP ME !!! :))
return false;
}
});
}
}
#Override
public boolean onMarkerClick(Marker v) {
// TODO Auto-generated method stub
//(PLEASE HELP ME !!! :))
if(v.getTitle().contains("New New College Res")){
// do if marker has this title
}else if(v.getTitle().contains("Baldwin Street")){
// do if marker has this title
} // and so on
return false;
}
});
Marker class if final so you can't extend it and add your own attributes. You will have to handle this using your own logic.
You can do this in two ways.
You already have a Data list with all marker data.
1) You could try to set "snippet" attribute of Marker with your array index of Data array and on onMarkerClick you can get Snippet change it back to int and that would be your Data Array's index. So you can get that your clicked Marker and it's Data object and do whatever you want to do.
2) Use HashMap.
It will look something like this
HashMap<Marker, Integer> hashMap = new HashMap<Marker, Integer>();
// now even in your loop where you are adding markers. you can also add that marker to this hashmap with the id of Data array's index.
hashMap.add(marker, indexOfDataArray);
// final in your onMarkerClick, you can just pass marker to hashMap and get indexOfDataArray and base of that do whatever you want to do.
int id = hashMap.get(marker);

Why doesn't my call to the Facebook Graph API display anything?

Ok, so I'm editing this to include the whole class with some new code I added over the past couple of hours. Basically, I'm looking to populate a Google Map with markers that represent a Facebook user's checkins. Unfortunately, my code has not been cooperating - I've tried reviewing the documentation that Facebook provides and searching the web for answers without coming up with anything useful. So far all I've been able to get the app to do is validate the app's permissions with Facebook and display the map, though I had tested the ability to add markers with dummy values in an earlier version of the app and that worked fine.
My earlier question dealt with why my calls to the Graph API weren't displaying anything - I had made the same call as listed in the AuthorizeListener sub-class, but was merely attempting to output the raw JSON string in a log entry instead of manipulating it. I think that whatever was the cause of that problem is probably the same cause of my current problem.
Anyway, how do I get my app to display markers for locations a user has checked in to? I think my code gets me off to a pretty good start, but there are obviously issues in my AuthorizeListener sub-class. What do you guys think?
public class FBCTActivity extends MapActivity {
public static Context mContext;
List<Overlay> mapOverlays;
FBCTMarkerOverlay markerLayer;
ArrayList<OverlayItem> overlays = new ArrayList<OverlayItem>();
// Facebook Application ID
private static final String APP_ID = "";
Facebook mFacebook = new Facebook(APP_ID);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.main);
// Set up Facebook stuff
mFacebook.authorize(this, new String[]{"user_checkins", "offline_access"}, new AuthorizeListener());
// Set up map stuff
MapView mMapView = (MapView)findViewById(R.id.map);
mMapView.setSatellite(true);
MapController mMapController = mMapView.getController();
mMapController.animateTo(getCurrentLocation());
mMapController.setZoom(3);
// Set up overlay stuff
mapOverlays = mMapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.icon);
markerLayer = new FBCTMarkerOverlay(drawable);
// markerLayer is populated in the AuthorizeListener sub-class
mapOverlays.add(markerLayer);
}
/**
* Determines the device's current location, but does not display it.
* Used for centering the view on the device's location.
* #return A GeoPoint object that contains the lat/long coordinates for the device's location.
*/
private GeoPoint getCurrentLocation() {
LocationManager mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria mCriteria = new Criteria();
mCriteria.setAccuracy(Criteria.ACCURACY_COARSE);
mCriteria.setPowerRequirement(Criteria.POWER_LOW);
String mLocationProvider = mLocationManager.getBestProvider(mCriteria, true);
Location mLocation = mLocationManager.getLastKnownLocation(mLocationProvider);
int mLat = (int)(mLocation.getLatitude()*1E6);
int mLong = (int)(mLocation.getLongitude()*1E6);
return new GeoPoint(mLat, mLong);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private class AuthorizeListener implements DialogListener {
public void onComplete(Bundle values) {
new Thread() {
#Override
public void run() {
try {
String response = mFacebook.request("me/checkins"); // The JSON to get
JSONObject jObject = Util.parseJson(response);
JSONArray jArray = jObject.getJSONArray("data"); // Read the JSON array returned by the request
for (int i = 0; i < jArray.length(); i++) { // Iterate through the array
JSONObject outerPlace = jArray.getJSONObject(i); // The outer JSON object
JSONObject place = outerPlace.getJSONObject("place"); // Second-tier JSON object that contains id, name, and location values for the "place"
String placeName = place.getString("name"); // The place's name
JSONObject placeLocation = place.getJSONObject("location"); // Third-tier JSON object that contains latitude and longitude coordinates for the place's "location"
int lat = (int) (placeLocation.getDouble("latitude")*1E6); // The place's latitude
int lon = (int) (placeLocation.getDouble("longitude")*1E6); // The place's longitude
String date = outerPlace.getString("created_time"); // Timestamp of the checkin
overlays.add(new OverlayItem(new GeoPoint(lat, lon), placeName, "Checked in on: " + date)); // Add the place's details to our ArrayList of OverlayItems
}
mFacebook.logout(mContext); // Logout of Facebook
for (int i = 0; i < overlays.size(); i++) {
markerLayer.addOverlayItem(overlays.get(i));
}
} catch(IOException e) {
Log.v("FBCTActivity", e.getMessage());
} catch(JSONException e) {
Log.v("FBCTActivity", e.getMessage());
}
}
}.start();
}
public void onFacebookError(FacebookError e) {
Log.w("FBCTActivity", e.getMessage());
// TODO: Add more graceful error handling
}
public void onError(DialogError e) {
Log.w("FBCTActivity", e.getMessage());
}
public void onCancel() {
// TODO Auto-generated method stub
}
}
}
It might not be the reason but you haven't defined your app ID:
private static final String APP_ID = "";
Also, you have to override the onActivityResult in the activity where you call the mFacebook.authorize, so add this to your code:
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
If you don't do so, your app won't get the token for the Graph and your connection will return a JSON error msg.

Categories

Resources