List<GraphUser> users is null - java

I am trying to get the friends list of the current logged-in user.
Here's how I am trying to get it:
private void fetchFriends(Session session) {
Request.newMyFriendsRequest(session, new GraphUserListCallback() {
#Override
public void onCompleted(List<GraphUser> users, Response response) {
if (users != null) {
friendsList = new ArrayList<FriendInfoHolder>();
for (GraphUser u : users) {
friendsList.add(buildFriendInfoHolder(u));
}
Intent intent = new Intent(parentActivity,
FriendListActivity.class);
intent.putParcelableArrayListExtra("friends_list",
friendsList);
parentActivity.startActivity(intent);
} else {
Log.i("users_status", "null");
}
}
}).executeAsync();
}
The problem is the users list (List<GraphUser> users) is always null.
I previously set the read permission as follows:
authButton.setReadPermissions(Arrays.asList("read_friendlists"));
So, I am not sure what's wrong. Here is the full Code:
Solved: I didn't add the INTERNET permission in my manifest file.
package home.example.logintest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.facebook.Request;
import com.facebook.Request.GraphUserListCallback;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends FragmentActivity {
private MainFragement mainFragement;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragement = new MainFragement();
mainFragement.setParentActivity(this);
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, mainFragement).commit();
} else {
// Or set the fragment from restored state info
mainFragement = (MainFragement) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
// try {
// PackageInfo info = getPackageManager().getPackageInfo(
// "home.example.logintest", PackageManager.GET_SIGNATURES);
// for (Signature signature : info.signatures) {
// MessageDigest md = MessageDigest.getInstance("SHA");
// md.update(signature.toByteArray());
// Log.d("KeyHash:",
// Base64.encodeToString(md.digest(), Base64.DEFAULT));
// }
// } catch (NameNotFoundException e) {
//
// } catch (NoSuchAlgorithmException e) {
//
// }
}
#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 static class MainFragement extends Fragment {
private UiLifecycleHelper uiHelper;
private ArrayList<FriendInfoHolder> friendsList;
private Activity parentActivity;
public Activity getParentActivity() {
return parentActivity;
}
public void setParentActivity(Activity parentActivity) {
this.parentActivity = parentActivity;
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container,
false);
LoginButton authButton = (LoginButton) view
.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setReadPermissions(Arrays.asList("read_friendlists"));
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
Session session = Session.getActiveSession();
if (session != null && (session.isOpened() || session.isClosed())) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
Log.i("msg", "Logged in...");
fetchFriends(session);
} else if (state.isClosed()) {
Log.i("msg", "Logged out...");
}
}
private void fetchFriends(Session session) {
Request.newMyFriendsRequest(session, new GraphUserListCallback() {
#Override
public void onCompleted(List<GraphUser> users, Response response) {
if (users != null) {
friendsList = new ArrayList<FriendInfoHolder>();
for (GraphUser u : users) {
friendsList.add(buildFriendInfoHolder(u));
}
Intent intent = new Intent(parentActivity,
FriendListActivity.class);
intent.putParcelableArrayListExtra("friends_list",
friendsList);
parentActivity.startActivity(intent);
} else {
Log.i("users_status", "null");
}
}
}).executeAsync();
}
private FriendInfoHolder buildFriendInfoHolder(GraphUser user) {
String profilePictureUrl = "graph.facebook.com/" + user.getId()
+ "/picture?type=square";
return new FriendInfoHolder(user.getFirstName(),
user.getLastName(), profilePictureUrl);
}
}
}

The problem was that I didn't add the INTERNET permission in the manifest file.

Related

How can I show navigation route to a fixed location from current location?

This is my code which shows route to some point from curent location of user to that point....
My code works fine...
My current code shows route when marker is added after onclick event occurs but what I want to achieve is if I have a predefined marker at fixed longitude and latitude which is defined as p1 variable in below code, then it should show the route from the current location...
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.google.android.material.navigation.NavigationView;
import com.mapbox.android.core.permissions.PermissionsListener;
import com.mapbox.android.core.permissions.PermissionsManager;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import com.mapbox.geojson.Feature;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.location.LocationComponent;
import com.mapbox.mapboxsdk.location.modes.CameraMode;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.maps.Style;
import com.mapbox.mapboxsdk.style.layers.SymbolLayer;
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncher;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncherOptions;
import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconAllowOverlap;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconIgnorePlacement;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconImage;
public class ViewMapActivity extends AppCompatActivity implements OnMapReadyCallback, MapboxMap.OnMapClickListener, PermissionsListener {
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
private NavigationView navigationView;
Toolbar toolbar;
MapView mapView;
MapboxMap mapboxMap;
LocationComponent locationComponent;
private PermissionsManager permissionmanager;
DirectionsRoute currentRoute;
NavigationMapRoute navigationMapRoute;
LatLng p1=new LatLng(72.843214,19.018335);//this is the fixed marker cordinates which I want to use
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this,getString(R.string.mapbox_access_token) );
setContentView(R.layout.activity_view_map);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
toolbar=findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Navigation");
Toolbar toolbar=findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawerLayout=findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(ViewMapActivity.this,drawerLayout,R.string.drawer_open,R.string.drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
navigationView = findViewById(R.id.naivgation_view);
View navView = navigationView.inflateHeaderView(R.layout.navigation_header);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
// UserMenuSelected(menuItem);
return false;
}
});
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
}
#Override
public void onPermissionResult(boolean granted) {
if (granted) {
enableLocationComponent(mapboxMap.getStyle());
} else {
Toast.makeText(this, "Permission not granted", Toast.LENGTH_SHORT).show();
finish();
}
}
#Override
public boolean onMapClick(#NonNull LatLng point) {
Point destinationPoint = Point.fromLngLat(point.getLongitude(), point.getLatitude());
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
Point originPoint = Point.fromLngLat(locationComponent.getLastKnownLocation().getLongitude(), locationComponent.getLastKnownLocation().getLatitude());
GeoJsonSource source = mapboxMap.getStyle().getSourceAs("destination-source-id");
if (source != null) {
source.setGeoJson(Feature.fromGeometry(destinationPoint));
}
getRoute(originPoint, destinationPoint);
return true;
}
private void getRoute(Point originPoint, Point destinationPoint) {
NavigationRoute.builder(this)
.accessToken(Mapbox.getAccessToken())
.origin(originPoint)
.destination(destinationPoint)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
Log.d("response inside fun", String.valueOf(response.body().routes().size()));
if (response.body() != null && response.body().routes().size() >= 1) {
currentRoute = response.body().routes().get(0);
Log.d("current route", String.valueOf(currentRoute));
if (navigationMapRoute != null) {
navigationMapRoute.removeRoute();
} else {
navigationMapRoute = new NavigationMapRoute(null, mapView, mapboxMap, R.style.NavigationMapRoute);
}
navigationMapRoute.addRoute(currentRoute);
}
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable t) {
}
});
}
#Override
public void onMapReady(#NonNull MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
this.mapboxMap.setMinZoomPreference(15);
mapboxMap.setStyle(getString(R.string.navigation_guidance_day), new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
enableLocationComponent(style);
addDestinationIconLayer(style);
mapboxMap.addOnMapClickListener(ViewMapActivity.this);
}
});
}
private void addDestinationIconLayer(Style style) {
style.addImage("destination-icon-id",
BitmapFactory.decodeResource(this.getResources(), R.drawable.mapbox_marker_icon_default));
GeoJsonSource geoJsonSource = new GeoJsonSource("destination-source-id");
style.addSource(geoJsonSource);
SymbolLayer destinationSymbolLayer = new SymbolLayer("destination-symbol-layer-id", "destination-source-id");
destinationSymbolLayer.withProperties(iconImage("destination-icon-id"), iconAllowOverlap(true), iconIgnorePlacement(true));
style.addLayer(destinationSymbolLayer);
}
public void startNavigationBtnClick(View v) {
boolean simulateRoute = true;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(currentRoute)
.shouldSimulateRoute(false)
.build();
NavigationLauncher.startNavigation(ViewMapActivity.this, options);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionmanager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
private void enableLocationComponent(#NonNull Style style) {
if (PermissionsManager.areLocationPermissionsGranted(this)) {
locationComponent = mapboxMap.getLocationComponent();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationComponent.activateLocationComponent(this, style);
locationComponent.setLocationComponentEnabled(true);
locationComponent.setCameraMode(CameraMode.TRACKING);
} else {
permissionmanager = new PermissionsManager(this);
permissionmanager.requestLocationPermissions(this);
}
}
// Add the mapView lifecycle to the activity's lifecycle methods
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}
How can I achieve this?
In onStyleLoaded(), instead of calling mapboxMap.addOnMapClickListener, you should just put the code you have in the onClick() method, like this:
Point destinationPoint = Point.fromLngLat(p1.getLongitude(), p1.getLatitude());
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
Point originPoint = Point.fromLngLat(locationComponent.getLastKnownLocation().getLongitude(), locationComponent.getLastKnownLocation().getLatitude());
GeoJsonSource source = mapboxMap.getStyle().getSourceAs("destination-source-id");
if (source != null) {
source.setGeoJson(Feature.fromGeometry(destinationPoint));
}
getRoute(originPoint, destinationPoint);

How to detect the direction of a suggested route in MapBox Directions API?

I am working on a project where I create an app that will direct users through a college campus using AR (Much like the one shown here: https://www.youtube.com/watch?v=vRmTn25xm7Q (7:20)).
I am starting off with the Navigation API for Android from MapBox. I want to know if there is any possible way to fetch a variable where the route guides you a direction(left, right, and forward) and put it through a parameter to prompt a UI element such as an arrow on AR screen in a Unity Android Project.
Here is my code from the Navigation API:
package com.creighton.adh81910.creighton_navigation;
import android.content.Context;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatDelegate;
import android.view.SearchEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.mapbox.api.directions.v5.DirectionsCriteria;
import com.mapbox.api.directions.v5.MapboxDirections;
import com.mapbox.services.;
import com.mapbox.android.core.;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncherOptions.*;
import com.mapbox.android.core.location.LocationEngine;
import com.mapbox.android.core.location.LocationEngineListener;
import com.mapbox.android.core.location.LocationEnginePriority;
import com.mapbox.android.core.location.LocationEngineProvider;
import com.mapbox.android.core.permissions.PermissionsListener;
import com.mapbox.android.core.permissions.PermissionsManager;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.plugins.locationlayer.LocationLayerPlugin;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.plugins.locationlayer.modes.CameraMode;
import com.mapbox.mapboxsdk.plugins.locationlayer.modes.RenderMode;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncher;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncherOptions;
import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import com.mapbox.services.android.navigation.v5.utils.LocaleUtils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import android.util.Log;
import java.security.acl.Permission;
import java.util.List;
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, LocationEngineListener, PermissionsListener, MapboxMap.OnMapClickListener {
private MapView mapView;
private MapboxMap map;
private Button startButton;
private PermissionsManager permissionsManager;
private LocationEngine locationEngine;
private LocationLayerPlugin locationLayerPlugin;
private Location originLocation;
private Point originPosition;
private Point destinationPosition;
private Marker destinationMarker;
private NavigationMapRoute navigationMapRoute;
private static final String TAG = "MainActivity";
private DirectionsRoute currentRoute;
private MapboxDirections mapboxDirections;
private MapboxDirections.Builder directionsBuilder;
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
#override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, "pk.eyJ1IjoiYWRoYXJtYXZhcmFwdSIsImEiOiJjampzdXBkMW4wY25jM3BtcnUzNGpwdTA4In0.qN9Y1LoHxPaONtXLp7rBCw");
setContentView(R.layout.activity_main);
mapView = (MapView) findViewById(R.id.mapView);
startButton = findViewById(R.id.startButton);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
startButton.setOnClickListener(new View.OnClickListener() {
#override
public void onClick(View v) {
boolean simulateRoute = true;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(currentRoute)
.shouldSimulateRoute(simulateRoute)
.build();
NavigationLauncher.startNavigation(MainActivity.this, options);
}
});
// Example of a call to a native method
//TextView tv = (TextView) findViewById(R.id.sample_text);
//tv.setText(stringFromJNI());
}
#override
public void onMapReady(MapboxMap mapboxMap) {
map = mapboxMap;
map.addOnMapClickListener(this);
enableLocation();
}
private void enableLocation() {
if (PermissionsManager.areLocationPermissionsGranted(this)) {
initializeLocationEngine();
initializeLocationLayer();
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
private void initializeLocationEngine() {
locationEngine = new LocationEngineProvider(this).obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.activate();
Location lastLocation = locationEngine.getLastLocation();
if (lastLocation != null) {
originLocation = lastLocation;
setCameraPosition(lastLocation);
} else {
locationEngine.addLocationEngineListener(this);
}
}
private void initializeLocationLayer() {
locationLayerPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationLayerPlugin.setLocationLayerEnabled(true);
locationLayerPlugin.setCameraMode(CameraMode.TRACKING);
locationLayerPlugin.setRenderMode(RenderMode.NORMAL);
}
private void setCameraPosition(Location location) {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 17));
}
#override
public void onMapClick(#nonnull LatLng point) {
destinationMarker = map.addMarker(new MarkerOptions().position(point));
destinationPosition = Point.fromLngLat(point.getLongitude(), point.getLatitude());
originPosition = Point.fromLngLat(originLocation.getLongitude(), originLocation.getLatitude());
getRoute(originPosition, destinationPosition);
startButton.setEnabled(true);
startButton.setBackgroundResource(R.color.mapbox_blue);
}
private void getRoute(Point origin, Point destination) {
NavigationRoute.builder(getApplicationContext())
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback() {
#override
public void onResponse(Call call, Response response) {
if (response.body() == null) {
Log.e(TAG, "No routes found, check right user and access token");
return;
} else if (response.body().routes().size() == 0) {
Log.e(TAG, "No routes found");
return;
}
currentRoute = response.body().routes().get(0);
if (navigationMapRoute != null) {
navigationMapRoute.removeRoute();
} else {
navigationMapRoute = new NavigationMapRoute(null, mapView, map);
}
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable t) {
Log.e(TAG, "Error" + t.getMessage());
}
});
}
#override
#SuppressWarnings("MissingPermission")
public void onConnected() {
locationEngine.requestLocationUpdates();
}
#override
public void onLocationChanged(Location location) {
if (location != null) {
originLocation = location;
setCameraPosition(location);
}
}
#override
public void onExplanationNeeded(List permissionsToExplain) {
//Present Dialog
}
#override
public void onPermissionResult(boolean granted) {
if (granted) {
enableLocation();
}
}
#override
public void onRequestPermissionsResult(int requestCode, #nonnull String[] permissions, #nonnull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#override
public void onStart() {
super.onStart();
if (locationEngine != null) {
locationEngine.requestLocationUpdates();
}
if (locationLayerPlugin != null) {
locationLayerPlugin.onStart();
}
mapView.onStart();
}
#override
public void onResume() {
super.onResume();
mapView.onResume();
}
#override
public void onPause() {
super.onPause();
mapView.onPause();
}
#override
public void onStop() {
super.onStop();
if (locationEngine != null) {
locationEngine.removeLocationUpdates();
}
if (locationLayerPlugin != null) {
locationLayerPlugin.onStop();
}
mapView.onStop();
}
#override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#override
protected void onDestroy() {
super.onDestroy();
if (locationEngine != null) {
locationEngine.deactivate();
}
mapView.onDestroy();
}
#override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
/**
A native method that is implemented by the 'native-lib' native library,
which is packaged with this application.
*/
public native String stringFromJNI();
public static final class Builder {
private final MapboxDirections.Builder directionsBuilder;
private Builder() {
directionsBuilder = MapboxDirections.builder();
}
public Builder Profile(#NonNull #DirectionsCriteria.ProfileCriteria String profile) {
directionsBuilder.profile(profile);
return this;
}
public static Builder builder(Context context) {
return builder(context, new LocaleUtils());
}
static Builder builder(Context contect, LocaleUtils localeUtils) {
return new Builder()
.Profile(DirectionsCriteria.PROFILE_WALKING);
}
}
}

how to add a request to a request queue in fragment [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am making an app that has four tabs in the tabs I am using a json request to get the data of events from a url.When I run the code its displays a null pointer exception error.
Here is my code
package com.alex.jay.turnapp;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import static com.alex.jay.turnapp.AppController.*;
public class EventsActivity extends Fragment {
String url = "http://192.168.43.114/Turnapp/retrieveevents.php";
ProgressDialog dialog;
private List<EventItem> array_events = new ArrayList<>();
EventsAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final View V = inflater.inflate(R.layout.events_tab, container, false);
RecyclerView recycler = (RecyclerView) V.findViewById(R.id.rv);
adapter = new EventsAdapter(getActivity(), array_events);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
recycler.setLayoutManager(mLayoutManager);
recycler.setItemAnimator(new DefaultItemAnimator());
recycler.setAdapter(adapter);
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Loading events...");
dialog.show();
if (array_events != null) {
array_events.clear();
}
StringRequest request = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
hideDialog();
Log.d("Sever Message", s);
JSONObject events = new JSONObject(s);
JSONArray jsonArray = events.getJSONArray("events");
JSONObject jobject = null;
int len = jsonArray.length();
for (int i = 0; i < len; i++) {
jobject = jsonArray.getJSONObject(i);
EventItem eventsdata = new EventItem();
eventsdata.setEventname(jobject.getString("1"));
eventsdata.setVenue(jobject.getString("2"));
eventsdata.setImages(jobject.getString("3"));
eventsdata.setEventdate(jobject.getString("4"));
array_events.add(eventsdata);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
});
AppController.getInstance().addToRequestQueue(request);
recycler.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recycler, new ClickListener() {
#Override
public void onClick(View view, int position) {
Intent intent = new Intent(getActivity(), Events.class);
intent.putExtra("eventname", array_events.get(position).getEventname());
intent.putExtra("eventlocation", array_events.get(position).getvenue());
intent.putExtra("eventimage", array_events.get(position).getImages());
startActivity(intent);
}
#Override
public void onLongClick(View view, int position) {
}
}));
return V;
}
public void hideDialog() {
if (dialog != null) {
dialog.dismiss();
dialog = null;
}
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
GestureDetector gestureDetector;
EventsActivity.ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final EventsActivity.ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView recycler, MotionEvent e) {
View child = recycler.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, recycler.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView recycler, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
}
Here is the AppController code
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new BitmapCache());
}
return this.mImageLoader;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Here is the error
05-05 13:43:21.083 17540-17540/com.alex.jay.turnapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.alex.jay.turnapp, PID: 17540
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.alex.jay.turnapp.AppController.addToRequestQueue(com.android.volley.Request)' on a null object reference
at com.alex.jay.turnapp.EventsActivity.onCreateView(EventsActivity.java:100)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:742)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
at android.support.v4.app.FragmentTabHost.onAttachedToWindow(FragmentTabHost.java:283)
at android.view.View.dispatchAttachedToWindow(View.java:13716)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2815)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2822)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2822)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2822)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2822)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2822)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2822)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2822)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1560)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1301)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6607)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:800)
at android.view.Choreographer.doCallbacks(Choreographer.java:603)
at android.view.Choreographer.doFrame(Choreographer.java:572)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:786)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5631)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
Please help
Seems like the method AppController.getInstance() returns NULL. Please find an example of how to implement the Singleton below.
https://gist.github.com/Akayh/5566992

Facebook permissions - Android Mobile app

I am trying to retrieve the info of Facebook user in my android app
This is what I got so far:
MainActivity.java
package com.firstandroidapp;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.facebook.*;
import com.facebook.Session.OpenRequest;
import com.facebook.model.*;
import com.facebook.widget.LoginButton;
import android.widget.TextView;
import android.content.Intent;
public class MainActivity extends FragmentActivity {
private MainFragment mainFragment;
//
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager()
.beginTransaction()
.add(android.R.id.content, mainFragment)
.commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
}
and the MainFragment.java
package com.firstandroidapp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphObjectList;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainFragment extends Fragment {
private static final String TAG = "MainFragment";
private TextView userInfoTextView;
private UiLifecycleHelper uiHelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
userInfoTextView = (TextView) view.findViewById(R.id.userInfoTextView);
authButton.setFragment(this);
List<String> permission=new ArrayList<String>();
permission.add("public_profile");
permission.add("email");
permission.add("user_birthday");
permission.add("user_location");
permission.add("user_likes");
permission.add("user_interests");
permission.add("user_relationships");
authButton.setReadPermissions(permission);
return view;
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
userInfoTextView.setVisibility(View.VISIBLE);
// Request user data and show the results
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// TODO Auto-generated method stub
userInfoTextView.setText(buildUserInfoDisplay(user));
}
});
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
userInfoTextView.setVisibility(View.INVISIBLE);
}
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
#Override
public void onResume() {
super.onResume();
// For scenarios where the main activity is launched and user
// session is not null, the session state change notification
// may not be triggered. Trigger it if it's open/closed.
Session session = Session.getActiveSession();
if (session != null &&
(session.isOpened() || session.isClosed()) ) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
private interface MyGraphLanguage extends GraphObject {
// Getter for the ID field
String getId();
// Getter for the Name field
String getName();
}
private String buildUserInfoDisplay(GraphUser user) {
StringBuilder userInfo = new StringBuilder("");
//Settings.addLoggingBehavior(LoggingBehavior.REQUESTS);
// Example: typed access (name)
// - no special permissions required
userInfo.append(String.format("Name: %s\n\n",
user.getName()));
// Example: typed access (birthday)
// - requires user_birthday permission
// userInfo.append(String.format("Birthday: %s\n\n",
// user.getBirthday()));
//
userInfo.append(String.format("E-mail: %s\n\n",
user.asMap().get("email").toString()));
// Example: partially typed access, to location field,
// name key (location)
// - requires user_location permission
// userInfo.append(String.format("Location: %s\n\n",
// user.getLocation().getProperty("name")));
// Example: access via property name (locale)
// - no special permissions required
userInfo.append(String.format("Locale: %s\n\n",
user.getProperty("locale")));
// Example: access via key for array (languages)
// - requires user_likes permission
// JSONArray languages = (JSONArray)user.getProperty("languages");
// if (languages.length() > 0) {
// ArrayList<String> languageNames = new ArrayList<String> ();
//
// // Get the data from creating a typed interface
// // for the language data.
// GraphObjectList<MyGraphLanguage> graphObjectLanguages =
// GraphObject.Factory.createList(languages,
// MyGraphLanguage.class);
//
// // Iterate through the list of languages
// for (MyGraphLanguage language : graphObjectLanguages) {
// // Add the language name to a list. Use the name
// // getter method to get access to the name field.
// languageNames.add(language.getName());
// }
//
// userInfo.append(String.format("Languages: %s\n\n",
// languageNames.toString()));
// }
Log.d(TAG, user.getName() + user.asMap().get("email").toString() + user.getProperty("locale") );
return userInfo.toString();
}
}
and I only get he Name and e-mail and language and I want more information such as the birthday and pages he/she likes and already added these permissions but for example the birthday returns null any idea what I am doing wrong please ??
Any help would be appreciate it
Thanks
Are you sure if the birthday date exists on Facebook profile as well? or they may have set to privacy.

<s3dReadConfigFile:75>: Can't open file for reading error

I'm recieving an error when running on my galaxy s3 called ": Can't open file for reading" twice in my LogCat.
Here is my code:
package com.example.speechrecognizertest;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.TextView;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
public static final String TAG = null;
private ListView wordList;
private SpeechRecognizer mSpeechRecognizer;
private Intent mSpeechRecognizerIntent;
private boolean mIslistening;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button speechBtn = (Button) findViewById(R.id.speech_btn);
wordList = (ListView) findViewById(R.id.word_list);
PackageManager packManager = getPackageManager();
List<ResolveInfo> intActivities = packManager.queryIntentActivities(
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
if (!mIslistening)
{
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
} else {
speechBtn.setEnabled(false);
Toast.makeText(this, "Oops - Speech Recognition Not Supported!",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onDestroy() {
if (mSpeechRecognizer != null)
{
mSpeechRecognizer.destroy();
}
super.onDestroy();
}
#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;
}
protected class SpeechRecognitionListener implements RecognitionListener
{
#Override
public void onBeginningOfSpeech()
{
Log.d(TAG, "onBeginingOfSpeech");
}
#Override
public void onBufferReceived(byte[] buffer)
{
}
#Override
public void onEndOfSpeech()
{
Log.d(TAG, "onEndOfSpeech");
}
#Override
public void onError(int error)
{
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
Log.d(TAG, "error = " + error);
}
#Override
public void onEvent(int eventType, Bundle params)
{
}
#Override
public void onPartialResults(Bundle partialResults)
{
}
#Override
public void onReadyForSpeech(Bundle params)
{
Log.d(TAG, "OnReadyForSpeech"); //$NON-NLS-1$
}
#Override
public void onResults(Bundle results)
{
//Log.d(TAG, "onResults"); //$NON-NLS-1$
ArrayList<String> suggestedWords = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
// matches are the return values of speech recognition engine
// Use these values for whatever you wish to do
wordList.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.word, suggestedWords));
}
#Override
public void onRmsChanged(float rmsdB){}}
}
My LogCat is displaying idsactly what I described. Would really appreciate a fix guys!
I've seen this for a number of months on my S3 and it's never appeared to cause any problems. The answer here sounds probable to me.

Categories