FirebaseApp not initializing despite FirebaseApp.initializeApp() being called in Application class - android

I am creating an Android application and I'm currently trying to implement user authentication using Firebase. As far as I can tell, my app is connected to my Firebase server.
I encounter a runtime error when attempting to switch from the SignIn activity to the SignUp activity via a button press. The app crashes and I encounter a runtime error.
So far as I can tell, the runtime error is from the SignUp activity's onCreate() call when I attempt to initialize a FirebaseAuth object with FirebaseAuth.getInstance(). This call fails due to
java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process seniordesign.phoneafriend. Make sure to call FirebaseApp.initializeApp(Context).
However, I make this call in my Application class' onCreate() method which I thought would be fine. I added the initalizeApp() call to the SignUp's onCreate() call but no dice. I've looked for others with this issue but have not found anything similar. Thanks for any help.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="seniordesign.phoneafriend">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme"
android:name="seniordesign.phoneafriend.PhoneAFriend">
<activity android:name=".SignIn">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SignUp"></activity>
</application>
</manifest>
PhoneAFriend.java (My Application class)
public class PhoneAFriend extends Application {
public void onCreate(){
super.onCreate();
Firebase.setAndroidContext(this);
FirebaseApp.initializeApp(this);
}
}
SignUp.java
public class SignUp extends AppCompatActivity {
protected Firebase ref;
protected EditText emailText;
protected EditText passText;
protected EditText confirmText;
protected Button button;
protected SignUp thisContext;
protected FirebaseAuth auth;
protected FirebaseAuth.AuthStateListener authListener;
private View.OnClickListener onClickListener;
public static Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
ref = new Firebase("https://phoneafriend-7fb6b.firebaseio.com");
emailText = (EditText) findViewById(R.id.signup_emailText);
passText = (EditText) findViewById(R.id.signup_passwordText);
confirmText = (EditText) findViewById(R.id.signup_passwordConfirm);
intent = new Intent(this, SignIn.class);
//Tried this already
//FirebaseApp.initializeApp(this);
auth = FirebaseAuth.getInstance();
button = (Button) findViewById(R.id.signup_button);
onClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
createUser(view);
Log.v("SignUp Button" , "Clicked; Attempting to create user");
}
};
button.setOnClickListener(onClickListener);
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged( FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d("FirebaseAuth", "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d("FirebaseAuth", "onAuthStateChanged:signed_out");
}
// ...
}
};
thisContext = this;
}
#Override
public void onStart(){
super.onStart();
//auth.addAuthStateListener(authListener);
}
#Override
public void onStop(){
super.onStop();
if(authListener != null) {
//auth.removeAuthStateListener(authListener);
}
}
protected void createUser(View view){
String cString = null;
String pString = null;
String eString = emailText.getText().toString();
if(passText.getText() != null && confirmText.getText() != null) {
pString = passText.getText().toString();
cString = confirmText.getText().toString();
Log.v("SignUP: Pass Null check" , "Pass" );
if (emailText.getText() != null && pString.equals(cString) && passText.getText() != null) {
Log.v("SignUP: Sign up check " , "Pass");
auth.createUserWithEmailAndPassword(emailText.getText().toString() , passText.getText().toString())
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.v("createUser complete" , "status: " + task.isSuccessful());
if(task.isSuccessful()){
startActivity(SignUp.intent);
}
}
});
}
}
return;
}
}

I know there's already an accepted answer. However, I ran into the same error message saying: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process (name). Make sure to call FirebaseApp.initializeApp(Context).
I tried several solutions found on SO, and double checking everything, until I finally found that the package name defined in the Firebase Console didn't match the package name defined in my manifest file.
Try go to your Firebase Console -> Project settings -> check if package names matches.
Hope it may help some :)

Just as qbix stated, you much use the API calls from whichever version you are going to use. If possible, you should use the newer API because it will definitely be supported much further into the future.
See the docs here:
https://firebase.google.com/docs/database/android/start/
Remove:
Firebase.setAndroidContext(this);
FirebaseApp.initializeApp(this);
And put:
FirebaseDatabase database = FirebaseDatabase.getInstance();
If qbix puts his comment into an answer, you should accept his rather than mine seeing has how he beat me by a few minutes.
Also:
If you are using the old firebase and need help switching, this guide is spot on and will help you with the switch. It's a fairly simple switch.
https://firebase.google.com/support/guides/firebase-android

I encountered this problem after I deleted and re-cloned my app and forgot to include the google-services.json inside the app module. After I re-added it, the problem went away. Nevertheless, you should init the context inside your custom Application class:
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
FirebaseApp.initializeApp(this)
}
}
<manifest
package="your.app">
<application
android:name=".MyApplication"

It is easier to use the Firebase wizard that is included in Android Studio: it adds all the dependencies in the gradle files, creates the firebase project if needed, connects the app with the project, etc.
In Android Studio open menu Tools / Firebase and follow the instructions.
Then FirebaseApp.initializeApp() will return a valid value.

First check up should be the Firebase documentation and the tools from
Android Studio -> Tools -> Firebase -> Cloud Messaging.
Even if you have done that before.
See this, that and that.
Again, even if you already done that before as firebase versions tend to require an up to date configuration JSON.

After much frustration, enabling Internet Permissions fixed this issue for me.

Upgrading classpath 'com.google.gms:google-services:4.1.0' to classpath 'com.google.gms:google-services:4.2.0' in the project Gradle worked for me.

Update 2019 : If you update your Firebase dependencies to latest then you should update Google play services as well.
During the writing of this answer I had updated all my Firebase libs to 17.0.+ but my Google play service was still pointing at 4.1.0.
Updating play service version to 4.3.0(Latest) fixed it for me.

Related

Android Studio - Log.i does not work

Below is code
String messageToken = FirebaseInstanceId.getInstance().getToken();
SharedPreferences sharedPreferences = getSharedPreferences(Constants.USER_INFO_PREFERENCE,
Context.MODE_PRIVATE);
String userEmail = sharedPreferences.getString(Constants.USER_EMAIL,"");
if (!userEmail.equals("")) {
Log.i(TAG,userEmail);
} else {
Log.i(TAG,"Nao ha info");
}
if (messageToken!=null && !userEmail.equals("")) {
DatabaseReference tokenReference = FirebaseDatabase.getInstance().getReference()
.child(Constants.FIREBASE_PATH_USER_TOKEN).child(Constants.encodeEmail(userEmail));
tokenReference.child("token").setValue(messageToken);
Log.i(InboxActivity.class.getSimpleName(),messageToken);
}
I have no idea why any of the Log.i is not printing in the log.
Maybe it's because of your build type , logs are not displayed in release mode
I got this problem solved! Matheus Brandino, from Alura.com.br, just pointed me that I had a wrongly overriden the onCreate method (its not showing here because I had my original post edited). So the solution was to delete the second argument from onCreate.
I had:
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
Now:
public void onCreate(Bundle savedInstanceState) {
Try going to developer settings on your android phone, Find "Monitoring" Option and then "Enable OpenGL Traces" and then select LogCat.
Run -> Edit Configurations -> Android app -> app -> Miscellaneous -> Tick all the check boxes -> Apply
Hope this help.

Few memory leaks in Facebook SDK

I tried to make social module for my app, something like wrapper, that will contain Google+,Facebook and twitter integration templates.
Now I am working with Facebook SDK and decided to use LeakCanary in my app, after successful log in I rotated the device few times, and see the following information:
Here is MainActivity.class:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
setFragment();
}
private void setFragment(){
getSupportFragmentManager()
.beginTransaction()
.add(R.id.container, new MainFragment())
.commit();
}
}
Here is how I log in to Facebook:
public void configureFacebook(#NonNull Fragment fragment,
#Nullable String permissions, #Nullable String requestFields) {
setPermissionAndRequestFields(permissions, requestFields);
loginManager = LoginManager.getInstance();
callbackManager = CallbackManager.Factory.create();
loginManager.registerCallback(callbackManager, facebookCallback);
loginManager.logInWithReadPermissions(fragment, Arrays.asList(this.permissions));
loginManager=null;
}
I tried log in using Login Button too, in this case I catch this issue and new one, with following info:
Here is how I log in using LoginButton.class:
public void configureFacebook(#NonNull Fragment fragment,
#Nullable String permissions, #Nullable String requestFields, #NonNull LoginButton button) {
callbackManager = CallbackManager.Factory.create();
setFbButton(button);
setPermissionAndRequestFields(permissions, requestFields);
fbButton.setFragment(fragment);
fbButton.setReadPermissions(this.permissions);
fbButton.registerCallback(callbackManager, facebookCallback);
}
I can't figure out how to fix those issues. What I am doing wrong?
UPDATE: Leak in Facebook Activity.class has been shown without the rotation device.
Looks like they may have fixed this for Facebook SDK Version 4.2.0. see here
Updating the Facebook SDK may be the solution to your problem.
I updated it to 4.7.0 and I think this issue has been fixed.
Fixed in 4.10. I tried without facebook app and checked with memory manager.

SharedPreferencesBackupHelper auto restore doesn't work

I'm trying to use SharedPreferencesBackupHelper to save my SharedPreferences value to cloud.
AndroidManifest.xml
<application
android:allowBackup="true"
android:backupAgent=".DataBackupAgent"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data android:name="com.google.android.backup.api_key" android:value="AEdPqrEAAAAIXMH86OqosQlXYuS0QbfyOaZT8fUadY1QUDzo2w" />
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
DataBackupAgent.java:
public class DataBackupAgent extends BackupAgentHelper {
public static final String PREFS = "data_prefs";
public static final String PREFS_BACKUP_KEY = "myprefs";
#Override
public void onCreate() {
SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);
addHelper(PREFS_BACKUP_KEY, helper);
}
}
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
backupManager = new BackupManager(this);
prefs = getSharedPreferences(DataBackupAgent.PREFS, Context.MODE_PRIVATE);
edit = prefs.edit();
text = (EditText)findViewById(R.id.editText);
String value = prefs.getString(DataBackupAgent.PREFS_BACKUP_KEY,"");
text.setText(value);
Button btnBackup = (Button)findViewById(R.id.button);
btnBackup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edit.putString(DataBackupAgent.PREFS_BACKUP_KEY,text.getText().toString());
edit.commit();
backupManager.dataChanged();
}
});
}
My steps:
Write something at the EditText, click Backup button
Close app and open again. The saved value will be shown in EditText
Uninstall the app and reinstall again. The saved value is not shown in EditText at all.
Edit at 27/02/2015:
I added the following code to restore manually:
backupManager.requestRestore(new RestoreObserver() {
#Override
public void restoreFinished(int error) {
super.restoreFinished(error);
String value = prefs.getString(DataBackupAgent.PREFS_BACKUP_KEY,"");
text.setText(value);
}
#Override
public void restoreStarting(int numPackages) {
super.restoreStarting(numPackages);
}
#Override
public void onUpdate(int nowBeingRestored, String currentPackage) {
super.onUpdate(nowBeingRestored, currentPackage);
}
});
Unfortunately no callback functions are called.
This means back or auto restore doesn't work at all. Any idea? Thanks
My steps:
1. Write something at the EditText, click Backup button
2. Close app and open again. The saved value will be shown in EditText
3. Uninstall the app and reinstall again. The saved value is not shown in EditText at all.
To test your implementation there are others steps related to the use of bmgras we can see here.
Nevertheless I implemented this feature some days ago and following the steps in the documentation using a real device - Samsung SII - the automatic restore doesn't happen BUT using the emulator all was fine.
Logcat will show you all the operation output details.
IMO, the Android Data Backup feature is not reliable today. We can see some discussion about the implementation problems here and here.
Hope it helps!

Nothing happens when I configure RoboGuice

I am new to RoboGuice and I am trying to set up my activity to use DI. However, nothing happens when I attempt to use it. I only get a blank black window with no content and no logging in my Activity.onCreate() method after I call "super.onCreate(savedInstanceState);"
See these 2 snippets of code:
public class ClikClokActivity extends RoboActivity{
#Inject
private TileAdapter tileAdapter;
#Inject
private GameLogicService gameLogicService;
#Inject
private GridOperationQueue gridOperationQueue;
private GridView gridView;
#Inject
private Handler handler;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
Log.v(this.getClass().toString(), "Entering onCreate");
super.onCreate(savedInstanceState);
Log.v(this.getClass().toString(), "Never logs this with RoboGuice");
setContentView(R.layout.main);
gridView = (GridView) findViewById(R.id.gridview);
gridView.setNumColumns(Constants.GRID_WIDTH);
gridView.setAdapter(tileAdapter);
Log.v(this.getClass().toString(), "GridView initialized");
gridOperationQueue.start();
Log.v(this.getClass().toString(), "Completed onCreate");
}
and
public class ClikClokApplication extends RoboApplication{
#Override
protected void addApplicationModules(List<Module> modules) {
modules.add(new ClikClokModule());
}
}
and
public class ClikClokModule extends AbstractAndroidModule {
#Override
protected void configure() {
}
}
and
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.clikclok"
android:versionCode="1"
android:versionName="1.0">
<application android:name="com.clikclok.ClikClokApplication" android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".ClikClokActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
If you look at the above code, I never get the second logging. However, if I was to extend from Activity instead and remove the android:name="com.clikclok.ClikClokApplication" attribute from my manifest then I do get the second logging (albeit fails with NullPointers as there is no initialization performed).
So what may be happening in super.onCreate(savedInstanceState); that is causing my application not to work?
Thanks
Update from the above:
I've spent quite a bit of time investigating this and using Eclipse's debugger can now see where my code seems to hang within RoboGuice.
The following code is from the InjectorImpl class:
public void injectMembers(Object instance) {
// Reaches here but...
MembersInjector membersInjector = getMembersInjector(instance.getClass());
// ....this comment is never reached
membersInjector.injectMembers(instance);
}
So I dug into the Guice 3.0 code using my debugger and into the FailableCache class:
public V get(K key, Errors errors) throws ErrorsException {
// Reaches here....
Object resultOrError = delegate.get(key);
// ...but not here
if (resultOrError instanceof Errors) {
errors.merge((Errors) resultOrError);
throw errors.toException();
} else {
#SuppressWarnings("unchecked") // create returned a non-error result, so this is safe
V result = (V) resultOrError;
return result;
}
}
How could this be that it just hangs while retrieving a key from a map? I'm not familiar enough with the code and it is quite confusing to troubleshoot.
Any advice is appreciated.
Try to add some bindings in your configure method.
You can also try to inject your grid view like this
#InjectView(R.id.gridview)
GridView gridView;
I hope this will help you.
Regards.
This was caused by me attempting to inject my Activity class into a service class.
So I was attempting to #Inject an instance of "ClikClokActivity" instead of "Activity".
Once I removed this injection attempt, everything worked fine. Not sure if this exposes some other issue with RoboGuice or Guice itself.

How is clickView used properly?

I'm trying to write a simple test app to run in JUnit. I've been having trouble getting clickView to click on the proper view. Below is some sample code that can be used on SkeletonActivity sample app that comes with the SDK.
public class SkeletonInstrumentation extends ActivityInstrumentationTestCase2<Activity>{
private Activity act;
private Button bClear;
private Button bBack;
private EditText eMain;
public SkeletonInstrumentation(){
super("com.example.android.skeletonapp", Activity.class);
}
public void setUp() {
String app = this.getInstrumentation().getTargetContext().getPackageName();
this.setActivityInitialTouchMode(true);
act = this.launchActivity(app, SkeletonActivity.class, Bundle.EMPTY);
bClear = (Button) act.findViewById(R.id.clear);
bBack = (Button) act.findViewById(R.id.back);
eMain = (EditText) act.findViewById(R.id.editor);
}
public void testClick()
{
TouchUtils.clickView(this, bClear);
}
public void testSendKeys()
{
act.runOnUiThread(
new Runnable(){
public void run(){
bClear.clearFocus();
eMain.requestFocus();
}
}
);
this.sendKeys("A B C D E F G ENTER");
}
}
testClick runs, but clicks on the main EditText view that has focus when the Activity starts and ends up bringing up the on-screen keyboard. I want it to click on the 'Clear' button below the EditText. Can someone tell me what's wrong here?
Adding the min and max target SDK in the AndroidManifest.xml worked for me; I got the idea from this answer. In the project that is being tested (not the test project) I added the following line to AndroidManifest.xml:
<uses-sdk android:targetSdkVersion="17" android:minSdkVersion="17"/>
and all of my uses of TouchUtils started behaving consistently again.
I had the same problem in this question and while I was able to find a workaround but it became really cumbersome so I spent more hours getting to the bottom of it.
The use of clickView here is correct. The problem was in the AndroidManifest.xml. Min and Target SDK must be set for it to work properly.

Categories

Resources