android map giving Error while initialize - java

java.lang.RuntimeException: Unable to start activity ComponentInfo{in.jainrishabh.noteelite/in.jainrishabh.noteelite.MapView}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.setOnMapClickListener(com.google.android.gms .maps.GoogleMap$OnMapClickListener)' on a null object reference
anyone know why i am getting NullPointer Exception
GoogleMap googleMap;
SharedPreferences sharedPreferences;
int locationCount = 0;
private ArrayList<UserDetailsPojo> pojoArrayList;
private float latia;
private float longia;
private Editor editor;
SharedPreferences prefs;
float lat;
float lng;
String lat_temp;
String long_temp;
private ListView userNamesListView;
private ListAdapter userListAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_view);
prefs = this.getSharedPreferences("sharedpref", Context.MODE_PRIVATE);
latia = prefs.getFloat("latitude", -34);
longia = prefs.getFloat("longitude", 151);
LatLng myLocation = new LatLng(latia, longia);
pojoArrayList = new ArrayList<UserDetailsPojo>();
// For the third argument, we need a List that contains Strings.
//We decided to display undergraduates names on the ListView.
//Therefore we need to create List that contains undergraduates names
userListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList());
//Toast.makeText(getApplicationContext(), "lati is:"+latia, Toast.LENGTH_LONG).show();
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Getting reference to the SupportMapFragment of activity_main.xml
MapFragment fm = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Opening the sharedPreferences object
sharedPreferences = getSharedPreferences("location", -34);
// Getting number of locations already stored
locationCount = sharedPreferences.getInt("locationCount", 151);
// Getting stored zoom level if exists else return 0
String zoom = sharedPreferences.getString("zoom", "0");
// If locations are already saved
if(locationCount!=0){
String lat = "";
String lng = "";
// Iterating through all the locations stored
for(int i=0;i<locationCount;i++){
// Getting the latitude of the i-th location
lat = lat_temp;
// Getting the longitude of the i-th location
lng = long_temp;
// Drawing marker on the map
drawMarker(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng)));
}
// Moving CameraPosition to last clicked position
googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng))));
//googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myLocation, 13));
// Setting the zoom level in the map on last position is clicked
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
}
googleMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
locationCount++;
// Drawing marker on the map
drawMarker(point);
/** Opening the editor object to write data to sharedPreferences */
SharedPreferences.Editor editor = sharedPreferences.edit();
// Storing the latitude for the i-th location
editor.putString("lat"+ Integer.toString((locationCount-1)), Double.toString(point.latitude));
// Storing the longitude for the i-th location
editor.putString("lng"+ Integer.toString((locationCount-1)), Double.toString(point.longitude));
// Storing the count of locations or marker count
editor.putInt("locationCount", locationCount);
/** Storing the zoom level to the shared preferences */
editor.putString("zoom", Float.toString(googleMap.getCameraPosition().zoom));
/** Saving the values stored in the shared preferences */
editor.commit();
Toast.makeText(getBaseContext(), "Marker is added to the Map", Toast.LENGTH_SHORT).show();
}
});
googleMap.setOnMapLongClickListener(new OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng point) {
// Removing the marker and circle from the Google Map
googleMap.clear();
// Opening the editor object to delete data from sharedPreferences
SharedPreferences.Editor editor = sharedPreferences.edit();
// Clearing the editor
editor.clear();
// Committing the changes
editor.commit();
// Setting locationCount to zero
locationCount=0;
}
});
}
private void drawMarker(LatLng point){
// Creating an instance of MarkerOptions
MarkerOptions markerOptions = new MarkerOptions();
// Setting latitude and longitude for the marker
markerOptions.position(point);
// Adding marker on the Google Map
googleMap.addMarker(markerOptions);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public List<String> populateList(){
// We have to return a List which contains only String values. Lets create a List first
List<String> userNamesList = new ArrayList<String>();
// First we need to make contact with the database we have created using the DbHelper class
AndroidOpenDbHelper openHelperClass = new AndroidOpenDbHelper(this);
// Then we need to get a readable database
SQLiteDatabase sqliteDatabase = openHelperClass.getReadableDatabase();
// We need a a guy to read the database query. Cursor interface will do it for us
//(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
Cursor cursor = sqliteDatabase.query(AndroidOpenDbHelper.TABLE_USER, null, null, null, null, null, null);
// Above given query, read all the columns and fields of the table
startManagingCursor(cursor);
// Cursor object read all the fields. So we make sure to check it will not miss any by looping through a while loop
while (cursor.moveToNext()) {
// In one loop, cursor read one undergraduate all details
// Assume, we also need to see all the details of each and every undergraduate
// What we have to do is in each loop, read all the values, pass them to the POJO class
//and create a ArrayList of undergraduates
//int Time = cursor.getInt(cursor.getColumnIndex(AndroidOpenDbHelper.COLUMN_TIME));
double latia = cursor.getDouble(cursor.getColumnIndex(AndroidOpenDbHelper.COLUMN_LATI));
double longia = cursor.getDouble(cursor.getColumnIndex(AndroidOpenDbHelper.COLUMN_LONGI));
// Finish reading one raw, now we have to pass them to the POJO
UserDetailsPojo ugPojoClass = new UserDetailsPojo();
ugPojoClass.setLati(latia);
ugPojoClass.setLongi(longia);
// Lets pass that POJO to our ArrayList which contains undergraduates as type
pojoArrayList.add(ugPojoClass);
lat_temp = Double.toString(latia);
long_temp = Double.toString(longia);
Log.d("latis1",lat_temp);
Log.d("longis1",long_temp);
}
// If you don't close the database, you will get an error
// sqliteDatabase.close();
return userNamesList;
}
}
Blockquote
<fragment
android:id="#+id/map"
android:layout_width="wrap_content"
android:layout_height="700dp"
android:layout_weight="4"
android:name="com.google.android.gms.maps.MapFragment"
/>
This is my Mapview XML

You are probably referencing the googleMap variable before it's been instantiated. Try changing that first line GoogleMap googleMap;
to this instead. GoogleMap googleMap = new GoogleMap();
Also, be sure to set the setOnMapClickListener inside the else case so it works as intended. You don't want to set the event listener if the map object doesn't exist (aka if Google Play Services are NOT available).

Related

Create multiple markers on map works, but only remember the last marker

i use tho code to add markers on my map. The problem is that if i create more than one marker, i can see all my markers on map, but if i exit the app and reopen, it only remember the last marker. I think i must create an array list and a loop. Unfortunately i was not able to find example on how to do this, i think is also because i use Mapsforge 0.3.1 and not Google map.
This is outside onCreate
ListOverlay myListOverlay;
List<OverlayItem> myOverlayItems;
Marker myMarker = null;
SharedPreferences prefs = null;
This is the code in the onCreate
myListOverlay = new ListOverlay();
myOverlayItems = myListOverlay.getOverlayItems();
mapView.getOverlays().add(myListOverlay);
prefs = this.getSharedPreferences("MotionEvent",MODE_PRIVATE);
//Check whether your preferences contains any values then we get those values
if((prefs.contains("Lat")) && (prefs.contains("Lon"))){
String lat = prefs.getString("Lat","");
String lon = prefs.getString("Lon", "");
GeoPoint l =new GeoPoint(Double.parseDouble(lat),Double.parseDouble(lon));
myMarker = createMarker(l, R.drawable.ic_location);
myOverlayItems.add(myMarker);
byte viewMarker = this.mapView.getMapViewPosition().getZoomLevel();
this.mapView.getMapViewPosition().setZoomLevel(viewMarker);
this.mapView.getMapViewPosition().setCenter(l);
}
mGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
#Override
public void onLongPress(MotionEvent e) {
if (e.getAction() == MotionEvent.ACTION_DOWN) {
byte viewMarker = mapView.getMapViewPosition().getZoomLevel();
float x = e.getX();
float y = e.getY();
GeoPoint gPt = mapView.getProjection().fromPixels((int)x, (int)y);
myMarker = createMarker(gPt, R.drawable.ic_location);
myOverlayItems.add(myMarker);
mapView.getMapViewPosition().setZoomLevel(viewMarker);
prefs.edit().putString("Lat",String.valueOf(gPt.latitude)).commit();
prefs.edit().putString("Lon",String.valueOf(gPt.longitude)).commit();
DialogMyMarkers();
}
}
});
mapView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v0, MotionEvent e) {
// Only fires if Mapview touched
return mGestureDetector.onTouchEvent(e);
}
});
DialogMyMarkers open an edit text to give a name for the marker. Then the name of the marker is saved and show in the myMarkersDialog
protected void myMarkersDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.my_markers_listview, null);
builder.setView(convertView);
builder.setTitle("List");
lv = (ListView) convertView.findViewById(R.id.listView1);
if (prefs.contains("Name"))
{
String name = prefs.getString("Name", "0");
String[] values = new String[] {name};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,values);
lv.setAdapter(adapter);
}
builder.setNegativeButton(getResources().getString(R.string.no_dialog), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
But how can i do this when i have more than one marker on map?
i think the error saty on line:
myListOverlay = new ListOverlay();
myOverlayItems = myListOverlay.getOverlayItems();
Why you need to recreate the overlay?
Advice: write on GoogleMaps V2 is easier!
Yes your assumption is correct i think is also because i use Mapsforge 0.3.1 and not Google map you can use the Google Map API's and try to store the marker information using the sql-lite database . i think you will get the required output
go through this example here

How to save a marker using SharedPreferences

I'm using Mapsforge Library to develop my app. In the map, you can create your own mark by long press on the map.
Now i would like to save this marker using sharedPreferences, so if the user close the app and repp, the marker still there. Unfortunately, i have not found such information around the web on how to do so. I have found some information on how to do it using Google maps, but google map have different functions.
Can anyone help me how to do it?
this is how i add the mark on the map. the code is in the OnCreate part:
myListOverlay = new ListOverlay();
myOverlayItems = myListOverlay.getOverlayItems();
mapView.getOverlays().add(myListOverlay);
mGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
#Override
public void onLongPress(MotionEvent e) {
float x = e.getX();
float y = e.getY();
if (e.getAction() == MotionEvent.ACTION_DOWN) {
GeoPoint gPt = mapView.getProjection().fromPixels((int) x, (int)y);
myMarker = createMarker(gPt, R.drawable.ic_location);
myOverlayItems.add(myMarker);
byte viewMarker = mapView.getMapViewPosition().getZoomLevel();
mapView.getMapViewPosition().setZoomLevel(viewMarker);
}
}
public boolean onSingleTapConfirmed(MotionEvent motionEvent) {
myOverlayItems.remove(myMarker);
byte viewMarker = mapView.getMapViewPosition().getZoomLevel();
mapView.getMapViewPosition().setZoomLevel(viewMarker);
return true;
};
}
);
mapView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v0, MotionEvent e) {
// Only fires if Mapview touched
return mGestureDetector.onTouchEvent(e);
}
});
Thanks to zcg7009 i was able to let the shared preferences work, but still a problem. This is the code:
in onCreate
if((prefs.contains("Lat")) && (prefs.contains("Lon"))){
String lat = prefs.getString("Lat",""); //with "" it throw error " Invalid "" ", if i put "0" the marker appear somewhere in the map
String lng = prefs.getString("Lng", "");
GeoPoint l =new GeoPoint(Double.parseDouble(lat),Double.parseDouble(lng));
myMarker = createMarker(l, R.drawable.ic_location);
myOverlayItems.add(myMarker);
byte viewMarker = this.mapView.getMapViewPosition().getZoomLevel();
this.mapView.getMapViewPosition().setZoomLevel(viewMarker);
this.mapView.getMapViewPosition().setCenter(l);
}
In the LongPress method
float x = e.getX();
float y = e.getY();
GeoPoint gPt = mapView.getProjection().fromPixels((int)x, (int)y);
myMarker = createMarker(gPt, R.drawable.ic_location);
myOverlayItems.add(myMarker);
byte viewMarker = mapView.getMapViewPosition().getZoomLevel();
mapView.getMapViewPosition().setZoomLevel(viewMarker);
prefs.edit().putString("Lat",String.valueOf(gPt.latitude)).commit();
prefs.edit().putString("Lon",String.valueOf(gPt.latitude)).commit();
the problem is in the second and third line of the code inside onCreate. If i use "" it throw the error invalid "", if i use "0" , the marker appear somewhere on the map.
How can solve this?
Do something like this, in your class add
private SharedPreferecnes prefs;
Then when your activity is destroyed
#Override
public void onDestroy(){
prefs.putDouble("marker_latitude", marker.getPosition().latitude);
prefs.putDouble("marker_longitude", marker.getPosition().longitude);
}
Then in onCreate
prefs = this.getSharedPreferences("com.smashing_boxes.taskproject",
Context.MODE_PRIVATE);
double latitude = prefs.getDouble("marker_latitude", -1.0);
double longitude = prefs.getDouble("marker_latitude", -1.0);
if(latitude != -1.0 && longitude != -1.0){
Marker marker = mapView.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude)));
myOverlayItems.add(marker);
}
This says that if you have stored a latitude and longitude in your preferences, you want to draw the marker on your map at the given coordinates and add the marker to your overlay items list.
String fnail LOCATION_KEY = "key":
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
preferences = getPreferences(MODE_APPEND);
String location = preferences = getString(LOCATION_KEY ,"default Value");
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Editor editor = preferences.edit();
editor.putString(LOCATION_KEY, "what ever you want");
editor.commit();
}
this is in generally how to use SharedPreferences just do same thing in your project
i hope this helps

Not showing desired map

When I run the app, I get the world map, where you can see all the countries. But this is not what I want, I want it to show the map of my country or city as an example. Is there a way to do this? This is my code so far. I don't think the xml code should be necassary for this?
public class MainActivity extends Activity {
private GoogleMap gMap;
private LocationManager locationManager;
private Location location, g;
private double lati, longi;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
// gMap.setMyLocationEnabled(true);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
System.out.println("Last known location: " + location);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void showUsersPosition(View v) {
gMap.setMyLocationEnabled(true);
if(location != null) {
lati = location.getLatitude();
longi = location.getLongitude();
}
gMap.addMarker(new MarkerOptions().position(new LatLng(lati, longi)).title("You are here"));
}
}
I also have added a button, where I want to show the users location when this button is clicked. This happens in the method "showUsersPosition". But at this point, Location is null, even though I try to set it when the app is beeing started. Can anyone see why it is null? When the gMap.setMyLocation(true) is called, a symbole appears at the right corner, and if I click on this, it will show me my position. But I want it so that it does this when I click the button.
So the questions again are:
1. How to show the map of my country or city, and not the world map?
2. Why is Location null?
3. How do I make it show my exact location when the button is clicked
1)
You can use this on your fragment declaration to set the default latitude and longitude.
map:cameraTargetLat="Your Latitude"
map:cameraTargetLng="Your Longitude"
Do not forget to put xmlns:map="http://schemas.android.com/apk/res-auto" on your fragment if it is not there.
2) From the docs:
If the provider is currently disabled, null is returned.
Is the GPS turned on?. Also, you should use the new Location API.
3) The exactness of your Location will be based on the Provider used to get the Location. One of the advantages of using the new Fused Provider is that the system will try to get the best Location possible for you.

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