When I run the app I get an error while launching the app. It shows me that I forgot to do something with FireBase and it shows me this as well: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.t.androiduberremake. Make sure to call FirebaseApp.initializeApp(Context) first.
there's my code
private final static int LOGIN_REQUEST_CODE =7171;
private List<AuthUI.IdpConfig> providers;
private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener listener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FirebaseApp.initializeApp(this);
init();
}
private void init() {
providers = Arrays.asList(
new AuthUI.IdpConfig.PhoneBuilder().build(),
new AuthUI.IdpConfig.GoogleBuilder().build());
firebaseAuth =FirebaseAuth.getInstance();
listener = myFirebaseAuth ->{
FirebaseUser user = myFirebaseAuth.getCurrentUser();
if(user != null)
delaySplashScreen();
else
showLoginLayout();
};
}
private void showLoginLayout() {
AuthMethodPickerLayout authMethodPickerLayout = new AuthMethodPickerLayout
.Builder(R.layout.layout_sign_in).setPhoneButtonId(R.id.btn_phone_sign_in)
.setGoogleButtonId(R.id.btn_google_sign_in).build() ;
startActivityForResult(AuthUI.getInstance()
.createSignInIntentBuilder()
.setAuthMethodPickerLayout(authMethodPickerLayout)
.setIsSmartLockEnabled(false).setAvailableProviders(providers)
.build(), LOGIN_REQUEST_CODE);
}
private void delaySplashScreen() {
Completable.timer(5, TimeUnit.SECONDS, AndroidSchedulers.mainThread())
.subscribe(() -> Toast.makeText(SplashScreenActivity.this, "Splash Screen done!! ", Toast.LENGTH_SHORT).show());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == LOGIN_REQUEST_CODE){
IdpResponse response = IdpResponse.fromResultIntent(data);
if(resultCode == RESULT_OK){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
}
else {
Toast.makeText(this, "[ERROR]: "+ response.getError().getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
that is what console shows me when I try to run a given app:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.t.androiduberremake/com.t.androiduberremake.SplashScreenActivity}: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.t.androiduberremake. Make sure to call FirebaseApp.initializeApp(Context) first.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3760)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3939)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2373)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:8147)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.t.androiduberremake. Make sure to call FirebaseApp.initializeApp(Context) first.
at com.google.firebase.FirebaseApp.getInstance(com.google.firebase:firebase-common##19.3.0:184)
at com.google.firebase.auth.FirebaseAuth.getInstance(com.google.firebase:firebase-auth##19.3.2:1)
at com.t.androiduberremake.SplashScreenActivity.init(SplashScreenActivity.java:49)
at com.t.androiduberremake.SplashScreenActivity.onCreate(SplashScreenActivity.java:39)
at android.app.Activity.performCreate(Activity.java:8066)
at android.app.Activity.performCreate(Activity.java:8054)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1313)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3733)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3939)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2373)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:8147)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
2020-08-13 15:33:55.746 12265-12265/? I/Process: Sending signal. PID: 12265 SIG: 9
You haven't added the google-services plugin to your build.gradle. Its important.
According to the documentation, you also have to add:
apply plugin: 'com.google.gms.google-services'
Related
I'm trying to publish my app in google play console.
But it tells me that it crashes on Google Pixel 2 (virtuel) (works on the 9 others) with 2 errors (very similar)
Google Pixel 2 (virtuel) 1080x1920 Android 12 (SDK 31) - x86_64 en_US
Error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.activity.result.ActivityResultLauncher.launch(java.lang.Object)' on a null object reference
Detail:
FATAL EXCEPTION: Thread-2
Process: xxxxxxxx, PID: 8724
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.activity.result.ActivityResultLauncher.launch(java.lang.Object)' on a null object reference
at xxxxxxxx.models.StockInputDialog.lambda$init$9$xxxxxxxx-models-StockInputDialog(StockInputDialog.java:417)
at xxxxxxxx.models.StockInputDialog$$ExternalSyntheticLambda9.onClick(Unknown Source:2)
at android.view.View.performClick(View.java:7441)
at android.view.View.performClickInternal(View.java:7418)
at android.view.View.access$3700(View.java:835)
at android.view.View$PerformClick.run(View.java:28676)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at androidx.test.espresso.base.Interrogator.loopAndInterrogate(Interrogator.java:10)
at androidx.test.espresso.base.UiControllerImpl.loopUntil(UiControllerImpl.java:7)
at androidx.test.espresso.base.UiControllerImpl.loopUntil(UiControllerImpl.java:1)
at androidx.test.espresso.base.UiControllerImpl.injectMotionEvent(UiControllerImpl.java:5)
at androidx.test.espresso.action.MotionEvents.sendUp(MotionEvents.java:6)
at androidx.test.espresso.action.MotionEvents.sendUp(MotionEvents.java:1)
at androidx.test.espresso.action.Tap.sendSingleTap(Tap.java:5)
at androidx.test.espresso.action.Tap.-$$Nest$smsendSingleTap(Unknown Source:0)
at androidx.test.espresso.action.Tap$1.sendTap(Tap.java:1)
at androidx.test.espresso.action.GeneralClickAction.perform(GeneralClickAction.java:4)
at androidx.test.espresso.ViewInteraction$SingleExecutionViewAction.perform(ViewInteraction.java:2)
at androidx.test.espresso.ViewInteraction.doPerform(ViewInteraction.java:21)
at androidx.test.espresso.ViewInteraction.-$$Nest$mdoPerform(Unknown Source:0)
at androidx.test.espresso.ViewInteraction$1.call(ViewInteraction.java:6)
at androidx.test.espresso.ViewInteraction$1.call(ViewInteraction.java:1)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
My code is explained (and the reason why) startActivityForResult migration, call registerForActivityResult outside activity, and simplified to the maximum:
public class StockActivity extends AppCompatActivity implements DialogCloseListener {
private ActivityResultLauncher<Intent> stockGalleryActivityResultLauncher;
private ActivityResultLauncher<Intent> stockCameraActivityResultLauncher;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
stockCameraActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
// code
});
stockGalleryActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
// code
});
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (id == R.id.action_add) {
mStockInputDialog = new StockInputDialog(this, stockCameraActivityResultLauncher, stockGalleryActivityResultLauncher,);
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
}
public class StockInputDialog {
private final Context mContext;
private AlertDialog mInputDialog;
private ActivityResultLauncher<Intent> stockCameraActivityResultLauncher;
private ActivityResultLauncher<Intent> stockGalleryActivityResultLauncher;
public StockInputDialog(Context context, ActivityResultLauncher<Intent> pStockCameraActivityResultLaunchera, ActivityResultLauncher<Intent> pStockGalleryActivityResultLauncher) {
mContext = context;
stockCameraActivityResultLauncher = pStockCameraActivityResultLaunchera;
stockGalleryActivityResultLauncher = pStockGalleryActivityResultLauncher;
LayoutInflater li = LayoutInflater.from(this.mContext);
mPromptsView = li.inflate(R.layout.text_input_stock, null);
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this.mContext);
alertDialogBuilder.setView(mPromptsView);
final ImageButton imgButtonCam = mPromptsView.findViewById(R.id.addCam);
final ImageButton imgButtonGal = mPromptsView.findViewById(R.id.addGal);
imgButtonCam.setOnClickListener(view -> {
Uri uri = FileProvider.getUriForFile(mContext, "fr.foo.bar.provider",
new Product(Consts.TEMP_NUM).getIMGPathCacheFile(mContext));
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
stockCameraActivityResultLauncher.launch(intent); <= ERROR
});
imgButtonGal.setOnClickListener(view -> {
stockGalleryActivityResultLauncher.launch(new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)) <= ERROR
});
}
}
The 2 errors correspond to the 2 launch()
What I don't understand is that I'm using this same principle elsewhere in the application without an error being raised.
No more crashes when testing the "nullity" of the launchers (#Abdo21 2nd answer).
imgButtonCam.setOnClickListener(view -> {
Uri uri = FileProvider.getUriForFile(mContext, "fr.novazur.donteat.provider",
new Product(Consts.TEMP_NUM).getIMGPathCacheFile(mContext));
if (stockCameraActivityResultLauncher != null)
stockCameraActivityResultLauncher.launch(uri);
else
Toast.makeText(mContext, R.string.featureAbsent, Toast.LENGTH_LONG).show();
});
imgButtonGal.setOnClickListener(view -> {
if (stockGalleryActivityResultLauncher != null)
stockGalleryActivityResultLauncher.launch("image/*");
else
Toast.makeText(mContext, R.string.featureAbsent, Toast.LENGTH_LONG).show();
});
That's what I should have done from the start. I'm a little sorry for not having thought of it, it's so obvious. I guess it's related to the creation of the AlertDialog which should not allow immediate access to the launchers. What I don't understand in this case is why only the Pixel 2 crashes, but problem seems to be solved for the moment. Thanks all.
I'm using the AppAuth library and trying to open the google website and go back to my activity (baseActivity) that calls a webview.
Basically i have a method that makes a call to open a webview page that i cannot put in the "OAuthJava" class, so I created an interface in the BaseActivity class, which I pass to the "OAuthJava" activity that makes the request for appAuth and after giving success uses the interface that is in the other activity to open the method that opens the webview
Error android : IlegalStateException: can not perform this action after onSaveInstance
#EActivity
public abstract class BaseActivity extends AppCompatActivity {
//code
private void test() {
//this builder is to create an intent to open the new activity and I pass this interface so that the next //activity can call the method that calls the webview
new OpenAppAuth.Builder()
.context(this)
.listener(new abc())
.build();
}
class abc implements RedirectInterface {
#Override
public void goToWebView() {
gotoScreen();
}
}
private void gotoScreen(String menuItem) {
//code that calls a webview screen
}
}
this class makes the call from the google site using appAuth
public class OAuthJava extends AppCompatActivity {
public static final int OAUTH_RC = 7777;
private RedirectInterface repository; // receives the abc class
#Override
public void onCreate(final Bundle icicle) {
// create the appauth request by opening google
Intent authIntent = authService.getAuthorizationRequestIntent(authRequest);
startActivityForResult(authIntent, OAUTH_RC);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == OAUTH_RC) {
AuthorizationResponse resp = AuthorizationResponse.fromIntent(data);
AuthorizationException ex = AuthorizationException.fromIntent(data);
if (resp != null) {
//success
//after I click on my email enter the "if" that calls goToWebView (interface abc)
repository.goToWebView();
}
}
}
error:
- beginning of crash
2021-04-01 18:52:58.729 9870-9870/com. E/AndroidRuntime: FATAL EXCEPTION: main
Process: com., PID: 9870
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=7777, result=-1, data=Intent { (has extras) }} to activity {com./br.o.commons.repository.OAuthJava}: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.app.ActivityThread.deliverResults(ActivityThread.java:4423)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4465)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at androidx.fragment.app.FragmentManager.checkStateLoss(FragmentManager.java:1832)
at androidx.fragment.app.FragmentManager.enqueueAction(FragmentManager.java:1872)
at androidx.fragment.app.BackStackRecord.commitInternal(BackStackRecord.java:329)
at androidx.fragment.app.BackStackRecord.commit(BackStackRecord.java:294)
I'm creating a mobile application for android and I have a problem when after the download connection by Google
the application crashes. Could someone give me a reason and how to attach it?
Main activities within reach.
public class MainActivity extends AppCompatActivity {
GoogleSignInClient mGoogleSignInClient;
private int RC_SIGN_IN = 3;
SignInButton signInButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signInButton = findViewById(R.id.sign_in_button);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.sign_in_button:
signIn();
break;
// ...
}
}
});
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
Intent intent = new Intent(MainActivity.this, MenuActivity.class);
startActivity(intent);
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w("TAG", "signInResult:failed code=" + e.getStatusCode());
// updateUI(null);
}
}
}
Target activity after logging in:
public class MenuActivity extends AppCompatActivity {
GoogleSignInClient mGoogleSignInClient;
Button logoutBtn;
TextView userName;
ImageView profileImage;
private GoogleSignInOptions gso;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
logoutBtn=(Button)findViewById(R.id.button_wyl);
profileImage=(ImageView)findViewById(R.id.profileImage);
userName = findViewById(R.id.name);
logoutBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
// ...
case R.id.button_wyl:
signOut();
break;
// ...
}
}
});
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(this);
if (acct != null) {
String personName = acct.getDisplayName();
Uri personPhoto = acct.getPhotoUrl();
userName.setText(personName);
Glide.with(this).load(String.valueOf(personPhoto)).into(profileImage);
}
}
private void signOut() {
mGoogleSignInClient.signOut()
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(MenuActivity.this, "Signed out Successfully", Toast.LENGTH_LONG).show();
finish();
}
});
}
}
Exception:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.goodmath, PID: 1780
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.goodmath/com.example.goodmath.MenuActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
at com.example.goodmath.MenuActivity.onCreate(MenuActivity.java:46)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
I/Process: Sending signal. PID: 1780 SIG: 9
You do not call setContentView() in onCreate() of MenuActivity, so your findViewById() lookups will fail. As a result, logoutBtn is null, so you crash with a NullPointerException when you try calling a method on it.
The actual error is:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object
So findViewById fails.
Do setContentView(R.layout.activity_menu) directly after super.onCreate()
And if that doesn't work, are you sure that the view you are referencing is within the activity_menu layout file?
I am new to Android development and I am facing an issue in invoking an activity from a generic class where I have a reusable function.
I have MainActivity where I need to check if the application has Network connectivity and then check if the user is already signed in.
If the user is signed in I need to open the Rate activity otherwise I will open the Login activity.
I thought I can keep the logic that checks the Network connectivity and shows the popup reusable and move it to a Global class as below
public class Global extends AppCompatActivity {
public static boolean hasConnectivity = false;
public static boolean userSignedIn = false;
String TAG = "Debug Log - Helper";
Context context;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
context = this;
}
private void networkConnectionErrorDialog(final Context context, final Class targetClass){
Log.d(TAG, "Show Alert Dialog");
new AlertDialog.Builder(context)
.setTitle(R.string.connection_error_title)
.setMessage(R.string.connection_error_message)
.setIcon(R.drawable.warning)
.setPositiveButton(
R.string.try_again,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, "Trying Again");
isNetworkAvailable(context, targetClass);
}
}).show();
}
protected void isNetworkAvailable(Context context, Class targetClass) {
if(NetworkUtil.isConnected(context)){
Log.d(TAG, "Has connectivity");
if(targetClass != null){
Log.d(TAG, targetClass.toString());
Intent targetIntent = new Intent(context, targetClass);
startActivity(targetIntent);
}
hasConnectivity = true;
return;
}else{
Log.d(TAG, "Has no connectivity");
hasConnectivity = false;
networkConnectionErrorDialog(context, targetClass);
}
}
}
I pass in the targetClass as Login.class or Rate.class (based on user signed in state) from the MainActivity where isNetworkAvailable() is invoked.
I am getting the following error. Could someone help me fix the issue and help me understand if my approach needs improvement?
java.lang.RuntimeException: Unable to resume activity {com.solitontech.dayatsoliton/com.solitontech.dayatsoliton.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3581)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3621)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2862)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
at android.app.Activity.startActivityForResult(Activity.java:4488)
at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
at android.app.Activity.startActivityForResult(Activity.java:4445)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
at android.app.Activity.startActivity(Activity.java:4806)
at android.app.Activity.startActivity(Activity.java:4774)
at com.solitontech.dayatsoliton.Global.isNetworkAvailable(Global.java:50)
at com.solitontech.dayatsoliton.MainActivity.onResume(MainActivity.java:68)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1355)
at android.app.Activity.performResume(Activity.java:7117)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3556)
It looks like your application is experiencing a null pointer exception in your activity's onResume method. If you had called startActivityForResult, make sure that the data in
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{..}
is non null before processing it.
As for your question about starting an activity from your helper class Global, you can define a function like this.
private static void goToActivity(Context context, Class<?> activityClass){
Intent intent = new Intent(context, activityClass);
context.startActivity(intent);
}
You can call this method as below.
goToActivity(context,TargetActivity.class);
Good luck.
Intent targetIntent = new Intent(context, targetClass);
startActivity(targetIntent);
above code is wrong. You should pass your current activity and target activity here.
Intent intent = new Intent(CurrentActivity.this, TargetingActivity.class);
startActivity(intent);
As a example :
If you want to start ActivtyB form ActivtyA
Intent intent = new Intent(ActivityA.this, ActivityD.class);
startActivity(intent);
1st try to correct this error. then you can find some others.
When the app starts for the first time and the user grants permission, the app crashes. If the app is restarted the user is already logged in and the app works perfectly.
To recreate the error I have to delete the app from the phone and disassociate the app from my Facebook account. ( if this helps )
Also to clarify, I understand what a null pointer exception is, just don't quite understand why it is happening on only the first run. Do I need to add some kind of statement for the first time run?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
Parse.enableLocalDatastore(this);
Parse.initialize(this);
//parse test
ParseObject testObject = new ParseObject("TestObject");
testObject.put("foo", "bar");
testObject.saveInBackground();
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main_page);
info = (TextView) findViewById(R.id.info);
loginButton = (LoginButton) findViewById(R.id.login_button);
Bundle logout_req = getIntent().getExtras();
if (logout_req != null) {
String logout = logout_req.getString("user_logout");
if (logout == "logout") {
LoginManager.getInstance().logOut();
}
}
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
if (Profile.getCurrentProfile() != null) {
Profile profile1 = Profile.getCurrentProfile();
Intent myIntent = new Intent(getBaseContext(), Home.class);
myIntent.putExtra("user_id", profile1.getId());
myIntent.putExtra("user_name", profile1.getName());
MainPage.this.startActivity(myIntent);
}
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Profile profile = Profile.getCurrentProfile();
ParseUser.logInInBackground(profile.getId(), "0", new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user == null) {
//No such user, create a new user.
ParseUser newUser = new ParseUser();
Profile profile = Profile.getCurrentProfile();
newUser.setUsername(profile.getId());
newUser.setPassword("0");
newUser.signUpInBackground();
//Send required data to home page
Intent myIntent = new Intent(getBaseContext(), Home.class);
myIntent.putExtra("user_id", profile.getId());
myIntent.putExtra("user_name", profile.getName());
MainPage.this.startActivity(myIntent);
System.out.println("NEW USER CREATED! LOGGED IN AND SENT TO HOMEPAGE");
} else {
Profile profile = Profile.getCurrentProfile();
//Send required data to home page
Intent myIntent = new Intent(getBaseContext(), Home.class);
myIntent.putExtra("user_id", profile.getId());
myIntent.putExtra("user_name", profile.getName());
MainPage.this.startActivity(myIntent);
System.out.println("USER LOGGED IN! SENT TO HOMEPAGE");
}
}
});
}
#Override
public void onCancel() {
info.setText("Login attempt canceled .");
}
#Override
public void onError(FacebookException e) {
info.setText("Login attempt failed.");
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
The error appears to happen just after loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>()
The error:
Process: com.george.coffeeconversation, PID: 16920
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=64206, result=-1, data=Intent { (has extras) }} to activity {com.george.coffeeconversation/com.george.coffeeconversation.MainPage}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.facebook.Profile.getId()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3680)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3723)
at android.app.ActivityThread.access$1300(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1400)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5373)
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:1020)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.facebook.Profile.getId()' on a null object reference
at com.george.coffeeconversation.MainPage.run(MainPage.java:108)
at com.george.coffeeconversation.MainPage$1.onSuccess(MainPage.java:90)
at com.george.coffeeconversation.MainPage$1.onSuccess(MainPage.java:87)
at com.facebook.login.LoginManager.finishLogin(LoginManager.java:510)
at com.facebook.login.LoginManager.onActivityResult(LoginManager.java:193)
at com.facebook.login.LoginManager$1.onActivityResult(LoginManager.java:136)
at com.facebook.internal.CallbackManagerImpl.onActivityResult(CallbackManagerImpl.java:82)
at com.george.coffeeconversation.MainPage.onActivityResult(MainPage.java:144)
at android.app.Activity.dispatchActivityResult(Activity.java:6192)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3676)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3723)
at android.app.ActivityThread.access$1300(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1400)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5373)
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:1020)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.facebook.Profile.getId()' on a null object reference
Apparently the Profile object you're trying to access is null at the point in time you're referencing it.
Since you mentioned it's occurring after returning from Facebook, it's probably happening in either done(ParseUser user, ParseException e) or onSuccess(LoginResult loginResult).
Try logging whether Profile.getCurrentProfile() is null at those points and you'll be able to track it down.