Essentially I am trying to close the GoogleApiClient when I pause or finish the fragment as it is crashing when I go back into said fragment.
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mGoogleApiClient = new GoogleApiClient
.Builder(getActivity())
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(getActivity(),this)
.build();
}
#Override
public void onPause() {
super.onPause();
mGoogleApiClient.disconnect();
}
FATAL EXCEPTION: main
Process: com.example.conornaylor.fyp, PID: 7055
java.lang.IllegalStateException: Already managing a GoogleApiClient
with id 0
at com.google.android.gms.common.internal.zzbo.zza(Unknown Source)
at com.google.android.gms.internal.zzbau.zza(Unknown Source)
at
com.google.android.gms.common.api.GoogleApiClient$Builder.build(Unknown
Source)
at
com.example.conornaylor.fyp.event.CreateEventFragment.onViewCreated(CreateEventFragment.java:164)
at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1343)
at
android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1574)
at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1641)
at
android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:794)
at
android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2415)
at
android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2200)
at
android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2153)
at
android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2063)
at
android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:725)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
Fixed the issue by calling mGoogleApiClient.stopAutoManage() in the onPause method of the fragment.
Related
I have an app with a login page.
First, I have my MainActivity where everything starts:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// here i launch LoginActivity
startActivityForResult(new Intent(this, LoginActivity.class), REQUEST_CODE);
emailText = findViewById(R.id.nav_text_email);
usernameText = findViewById(R.id.nav_text_username);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == REQUEST_CODE){
if(resultCode != Activity.RESULT_OK) {
finish();
}
// if login succesful, i attach to variable instance of
// logged user class.
// that part works correct, in object vars exist
loggedUser = loggedUser.getInstance();
// i want to attach strings after succesful login
emailText.setText(loggedUser.getEmail());
usernameText.setText(loggedUser.getUsername());
}
}
When run the app with the code above, after succesful LoginActivity app crashes with this exception:
2019-01-26 20:46:48.015 13071-13071/com.example.admin.keystroke_dynamics E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.admin.keystroke_dynamics, PID: 13071
java.lang.RuntimeException: Unable to resume activity {com.example.admin.keystroke_dynamics/com.example.admin.keystroke_dynamics.Activities.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3586)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3626)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2876)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.admin.keystroke_dynamics.Activities.MainActivity.onResume(MainActivity.java:89)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1279)
at android.app.Activity.performResume(Activity.java:7022)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3561)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3626)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2876)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
When I deleted the setText() methods from `onActivityResult(), I don't get that exception. The error appears when I click the Login button and the app crashes.
While debugging, compiler not even go in lines with setText()
My question is, how to set texts in textviews in the scenario that I coded above?
UPDATE
Even if i popualte strings in loggedUser in constructor as empty, move loggedUser = loggedUser.getInstance() and move setText() to onCreat, i still get that NPE.
EDIT:
I added onResume method:
#Override
protected void onResume()
{
if(isLogged) {
emailText.setText(loggedUser.getEmail());
usernameText.setText(loggedUser.getUsername());
}
super.onResume();
}
And edited onActivityResult():
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == REQUEST_CODE){
if(resultCode != Activity.RESULT_OK) {
finish();
}
isLogged = true; //var for if statement in onResume()
loggedUser = loggedUser.getInstance();
}
}
And i still get the same error on onResume() method when i setting up TextViews.
2019-01-26 21:21:57.752 18262-18262/com.example.admin.keystroke_dynamics E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.admin.keystroke_dynamics, PID: 18262
java.lang.RuntimeException: Unable to resume activity {com.example.admin.keystroke_dynamics/com.example.admin.keystroke_dynamics.Activities.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3586)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3626)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1618)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.admin.keystroke_dynamics.Activities.MainActivity.onResume(MainActivity.java:90)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1279)
at android.app.Activity.performResume(Activity.java:7022)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3561)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3626)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1618)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
A null view is usually a result of your layout not containing a view with the id you specified in findViewById(). Therefore findViewById() returns null and the variables are remaining null when onResume() is called. Double check your view ids in main_activity.xml.
It's also possible that the full content view is not available in onCreate() if you are using a more complicated layout. If you find that your views are null in onCreate(), try moving findViewById() to a later point in the lifecycle.
Try reordering the code like this
emailText = findViewById(R.id.nav_text_email);
usernameText = findViewById(R.id.nav_text_username);
startActivityForResult(new Intent(this, LoginActivity.class), REQUEST_CODE);
Try initializing the variables before accessing them.
public class MainActivity extends AppCompatActivity {
TextView emailText;
TextView usernameText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// here i launch LoginActivity
startActivityForResult(new Intent(this, LoginActivity.class), REQUEST_CODE);
emailText = findViewById(R.id.nav_text_email);
usernameText = findViewById(R.id.nav_text_username);
}
Could fit in a comment
You need to access the NavigationView from the activity
Update
NavigationView navigationView = findViewById(R.id.nav_id)
View header = navigationView.getHeaderView(0)
TextView usernameText = header.findViewById(R.id.username_text_view_id);
I'm getting this error and I don't know why. This same code was working before; the problem started occuring after an update at some point.
Stack trace:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.domain.appname, PID: 17964
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.domain.appname/com.domain.appname.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.domain.appname.NavigationDrawerFragment.setUp(int, android.support.v4.widget.DrawerLayout)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2441)
at android.app.ActivityThread.access$800(ActivityThread.java:162)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5431)
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:914)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.domain.appname.NavigationDrawerFragment.setUp(int, android.support.v4.widget.DrawerLayout)' on a null object reference
at com.domain.appname.MainActivity.onCreate(MainActivity.java:40)
at android.app.Activity.performCreate(Activity.java:6056)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2332)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2441)
at android.app.ActivityThread.access$800(ActivityThread.java:162)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5431)
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:914)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707)
Here's the offending code in MainActivity.java:
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (BuildConfig.DEBUG){ Log.d(TAG, "Created in debug mode"); }
NavigationDrawerFragment mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
// Set up the drawer.
Log.d(TAG, "Setting up drawer");
mNavigationDrawerFragment.setUp( // Line 40
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout)
);
...
I've found two questions that seem to have similar problems. (Here's the first and the second) The first doesn't seem relevant, and the second is unanswered.
I'm baffled. drawer_layout and navigation_drawer do not throw "symbol unresolved" errors. Like I said, this all used to work...
You are never calling Activity.setContentView(int). This is how it should be:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_containing_drawer);
// Rest.
}
I am new to android. I am trying to display current location in my MainActivity.
But as my network is slow I am getting the entire front end very late. So i decided to use Threads. So my location based part of the code runs silently in the background.Things worked Perfectly but my OnResume function throws an error. And I am not sure how to proceed further about it.
My Thread code in MainActivity OnCreate:
UserLocationDetails locationDetails=new UserLocationDetails();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
GoogleApiClient mGoogleApiClient;
SmsManager smsManager = SmsManager.getDefault();
private LocationRequest mLocationRequest;
TextView userLocationView;
Button settings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Runnable runnable=new Runnable() {
#Override
public void run() {
mGoogleApiClient=new GoogleApiClient.Builder(MainActivity.this).
addConnectionCallbacks(MainActivity.this).
addOnConnectionFailedListener(MainActivity.this).
addApi(LocationServices.API).build();
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
};
Thread googleApiClientThread=new Thread(runnable);
googleApiClientThread.start();
OnResume Function:
#Override
protected void onResume() {
super.onResume();
mGoogleApiClient.connect();
Log.i(TAG, "OnResume, Connected back!");
}
Logcat Error:
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'void com.google.android.gms.common.api.GoogleApiClient.connect()' on a null object reference
at androidfactory.mafi.com.wru.MainActivity.onResume(MainActivity.java:113)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1280)
at android.app.Activity.performResume(Activity.java:6096)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3011)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3063)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418)
at android.app.ActivityThread.access$800(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5343)
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:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
Null Pointer Exception is thrown because in onResume() it is trying to call method on mGoogleApiClient, but it is not created as its creation is done inside of Runnable background thread, so there is asynchronous execution of code.
you can check before calling connect() for null reference.
protected void onResume() {
super.onResume();
if(mGoogleApiClient != null){
mGoogleApiClient.connect();
Log.i(TAG, "OnResume, Connected back!");
}
}
Why do you need to initialize the GoogleApiClient inside a thread inside onCreate?
You can just declare it without a thread.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleApiClient=new GoogleApiClient.Builder(this).
addConnectionCallbacks(this).
addOnConnectionFailedListener(this).
addApi(LocationServices.API).build();
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
then your onResume should work fine.
#Override
protected void onResume() {
super.onResume();
mGoogleApiClient.connect();
Log.i(TAG, "OnResume, Connected back!");
}
About your comment :
If its NOT NULL , why should I connect again ? Only if its null I
should be connecting right ??
You cannot call connect() from a NULL Object such mGoogleApiClient. Since you initialized it on a separated thread, Android calls onCreate()-->onStart()-->onResume() one after another in this order, so when you reach onResume(), your mGoogleApiClient was not initialized yet by the thread, that's why you got the error.
Just by initializing a mGoogleApiClient you are NOT CONNECTING ANYTHING! So you need to call connect() if you plan to use any feature from Google Play Service.
I have spent a while trying to get this to work and I keep getting stuck somewhere at every tutorial. In short I am trying to make a tabbed app where one of the tabs it a google maps.
I have fixed all of the usual mistakes:
I have downloaded everything relevant through SDK.
I have an API key in place.
I have added compile com.google.android.gms:play-services:7.5.0 to my dependencies.
I am trying to follow this code, but I keep getting an error.
Error I am receiving from logcat:
07-06 13:46:20.046 17948-17948/dolphin.dolphinapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: dolphin.dolphinapp, PID: 17948
java.lang.NullPointerException: IBitmapDescriptorFactory is not initialized
at com.google.android.gms.common.internal.zzu.zzb(Unknown Source)
at com.google.android.gms.maps.model.BitmapDescriptorFactory.zzvH(Unknown Source)
at com.google.android.gms.maps.model.BitmapDescriptorFactory.defaultMarker(Unknown Source)
at dolphin.dolphinapp.MainActivity$MapFragment.onCreateView(MainActivity.java:655)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:490)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1105)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:551)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:513)
at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:494)
at dolphin.dolphinapp.MainActivity.onTabSelected(MainActivity.java:152)
at android.support.v7.internal.app.WindowDecorActionBar.selectTab(WindowDecorActionBar.java:640)
at android.support.v7.internal.app.WindowDecorActionBar$TabImpl.select(WindowDecorActionBar.java:1224)
at android.support.v7.internal.widget.ScrollingTabContainerView$TabClickListener.onClick(ScrollingTabContainerView.java:568)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Apparently to solve this write MapsInitializer.initialize(getActivity().getApplicationContext());, but that is already in the code I copied.
Here is my Java Code:
public class MapFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflat and return the layout
View v = inflater.inflate(R.layout.fragment_location_info, container,
false);
mMapView = (MapView) v.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();// needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
MapsInitializer.initialize(getApplicationContext());
googleMap = mMapView.getMap();
// latitude and longitude
double latitude = 17.385044;
double longitude = 78.486671;
// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(17.385044, 78.486671)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
// Perform any camera updates here
return v;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
My XML File:
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.gms.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Please let me know what I am doing wrong
you should call mMapView.getMapAsync() in your onCreateView then in the callback of onMapReady that you implement you would do MapsInitializer.initialize(this.context);
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
MapsInitializer.initialize(getApplicationContext());
// latitude and longitude
double latitude = 17.385044;
double longitude = 78.486671;
// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
}
});
I am getting this error when hitting the "Login With Facebook" (Simple login button).
I have Google, and read other topics here - but I can not see any thing matching my issue.
I am adding Login.java class below.
public class Login extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_login);
CallbackManager callbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("public_profile", "email", "user_friends");
// Other app specific specialization
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.i("Login", "Logged in: ");
Intent i = new Intent(Login.this, MainActivity.class);
startActivity(i);
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
Log.i("Error" , "Error");
}
});
}
}
StackTrace:
05-28 20:07:27.550 872-1363/? E/Parcel﹕ Class not found when unmarshalling: com.facebook.login.LoginClient$Request
java.lang.ClassNotFoundException: com.facebook.login.LoginClient$Request
at java.lang.Class.classForName(Native Method)
at java.lang.Class.forName(Class.java:308)
at java.lang.Class.forName(Class.java:272)
at android.os.Parcel.readParcelableCreator(Parcel.java:2275)
at android.os.Parcel.readParcelable(Parcel.java:2239)
at android.os.Parcel.readValue(Parcel.java:2146)
at android.os.Parcel.readArrayMapInternal(Parcel.java:2479)
at android.os.BaseBundle.unparcel(BaseBundle.java:221)
at android.os.BaseBundle.getString(BaseBundle.java:918)
at android.content.Intent.getStringExtra(Intent.java:5378)
at com.android.server.am.ActivityStackSupervisor.startActivityLocked(ActivityStackSupervisor.java:1768)
at com.android.server.am.ActivityStackSupervisor.startActivityMayWait(ActivityStackSupervisor.java:1313)
at com.android.server.am.ActivityManagerService.startActivityAsUser(ActivityManagerService.java:4522)
at com.android.server.am.ActivityManagerService.startActivity(ActivityManagerService.java:4368)
at android.app.ActivityManagerNative.onTransact(ActivityManagerNative.java:140)
at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:2964)
at android.os.Binder.execTransact(Binder.java:446)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.facebook.login.LoginClient$Request" on path: DexPathList[[directory "."],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
at java.lang.Class.classForName(Native Method)
at java.lang.Class.forName(Class.java:308)
at java.lang.Class.forName(Class.java:272)
at android.os.Parcel.readParcelableCreator(Parcel.java:2275)
at android.os.Parcel.readParcelable(Parcel.java:2239)
at android.os.Parcel.readValue(Parcel.java:2146)
at android.os.Parcel.readArrayMapInternal(Parcel.java:2479)
at android.os.BaseBundle.unparcel(BaseBundle.java:221)
at android.os.BaseBundle.getString(BaseBundle.java:918)
at android.content.Intent.getStringExtra(Intent.java:5378)
at com.android.server.am.ActivityStackSupervisor.startActivityLocked(ActivityStackSupervisor.j
Java:1768) at com.android.server.am.ActivityStackSupervisor.startActivityMayWait(ActivityStackSupervisor.java:1313)
at com.android.server.am.ActivityManagerService.startActivityAsUser(ActivityManagerService.java:4522)
at com.android.server.am.ActivityManagerService.startActivity(ActivityManagerService.java:4368)
at android.app.ActivityManagerNative.onTransact(ActivityManagerNative.java:140)
at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:2964)
at android.os.Binder.execTransact(Binder.java:446)
Suppressed: java.lang.ClassNotFoundException: com.facebook.login.LoginClient$Request
at java.lang.Class.classForName(Native Method)
at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
... 18 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
Check your android:noHistory flag on the activity.
See link
https://developers.facebook.com/bugs/1621984714705591/
look for post by Andreas Bergenwall
This can happen when the user has the native Facebook App installed.
You can suppress the attempt to open it by initializing the LoginManager's LoginBehaviour:
// Don't allow the Facebook App to open.
LoginManager.getInstance().setLoginBehavior(LoginBehavior.WEB_VIEW_ONLY);
I too had this issue. Mine however was a login call made within the FBActivity.OnResume method for callbacks to login after accepting fb perms.
I simply moved the request into the profile tracker in the onCreate method
ProfileTracker profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
Profile.fetchProfileForCurrentAccessToken();
if(currentProfile != null) {
String fbUserId = currentProfile.getId();
profileUrl = currentProfile.getProfilePictureUri(200, 200).toString();
Log.d("FB profile", "got new/updated profile from thread " + fbUserId);
// jump if logged in already
GetFacebookProfileAndJump(currentProfile);
}
}
};
Also ensure your OnCreate super is as follows
FacebookSdk.sdkInitialize(getApplicationContext());
mCallbackmanager = CallbackManager.Factory.create();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fbauth_);
...
You should add this to your acctivity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
but if your using parse SDK add this
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ParseFacebookUtils.onActivityResult(requestCode, resultCode, data);
}
I had the same problem, and solved by putting the facebook_app_id to strings.xml instead of a constant:
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id" />
In my case i forgot to add application package name and class name on the developer page of facebook. After i added this information then it worked.
I have struggled with this problem and I fixed with multidex enabled
add this in your build file
multiDexEnabled true
also this code in your activity
#Override
protected void attachBaseContext(Context context) {
super.attachBaseContext(context);
MultiDex.install(this);
}
after adding this in your build gradle dependencies
compile 'com.android.support:multidex:1.0.1'
Actually this is happend. Because of the onActivityResult method has not implemented in side your Activity and also you must call
callbackManager.onActivityResult(requestCode, resultCode, data);
method inside this method. I am sure 100% your problem resolved.