Firebase: two projects for one Android app [duplicate] - android

I'm trying to have one project in Firebase that will be responsible for one common thing that all Apps.
That is, I want to create Apps, then have these Apps access a particular Firebase Database of a project.
Looking at the Firebase Android docs, I can't find a way to send data to another firebase database in another project using the following, but where reference is of another project.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("example");
ref.push().setValue(d).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
finish();
}
});

You'll need to initialize a second FirebaseApp object with explicit options in your code:
FirebaseOptions options = new FirebaseOptions.Builder()
.setApiKey("AI...j0")
.setApplicationId("1:5...e0")
.setDatabaseUrl("https://myapp.firebaseio.com")
.build();
FirebaseApp secondApp = FirebaseApp.initializeApp(getApplicationContext(), options, "second app");
FirebaseDatabase secondDatabase = FirebaseDatabase.getInstance(secondApp);
secondDatabase.getReference().setValue(ServerValue.TIMESTAMP);
I got the configuration values from the second project's google-services.json. The API Key is under a property called api_key, the Application ID came from a property called mobilesdk_app_id and the database URL came from a property called firebase_url.
Also see the documentation on using multiple projects in your application.

Related

Can I get the Title/Name or Description of A/B-Test and the Variation-Name from Firebase into Activity?

Got this basic Firebase RemoteConfig A/B-Test running on Android. I want to get the title/name and description of the A/B-Test configurated in Firebase. Also it would be nice to get the name of the variations (Control, Variation A, ...)
How do I get these data?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// bind XML elements into variables
bindWidgets();
// Only for debugging: get Instance ID token from device
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
#Override
public void onComplete(#NonNull Task<InstanceIdResult> task) {
String deviceToken = task.getResult().getToken();
Log.wtf("Instance ID", deviceToken);
}
});
// Remote Config Setting
FirebaseRemoteConfigSettings mFirebaseRemoteConfigSettings = new FirebaseRemoteConfigSettings
.Builder()
.setDeveloperModeEnabled(BuildConfig.DEBUG)
.build();
mFirebaseRemoteConfig.setConfigSettings(mFirebaseRemoteConfigSettings);
// Remote Config with HashMap
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("buttonColor", "#999999");
mFirebaseRemoteConfig.setDefaults(hashMap);
final Task<Void> fetch = mFirebaseRemoteConfig.fetch(FirebaseRemoteConfig.VALUE_SOURCE_STATIC);
fetch.addOnSuccessListener(this, new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mFirebaseRemoteConfig.activateFetched();
// get value of key buttonColor from HashMap
String buttonColor = mFirebaseRemoteConfig.getString("buttonColor");
button.setBackgroundColor(Color.parseColor(buttonColor));
}
});
}
There is no official API to retrieve any information about your A/B test, besides the variant selected.
It's going to be much, much easier to just hardcode the values inside your app, or manually add them on Firebase Hosting / Cloud Firestore.
That being said, here's 2 vague ideas for more automatic solutions, but I really don't recommend trying either!
BigQuery
You could link your project to BigQuery, it will then contain your Analytics data. Specifically:
In this query, your experiment is encoded as a user property with the experiment name in the key and the experiment variant in the value.
Once your data is in BigQuery, you could then retrieve it using the SDKs. You will of course need to handle permissions and access control, and this is almost certainly extremely overkill.
Cloud Functions (and hosting)
Another solution is to just store the data you need elsewhere, and retrieve it. Firebase Cloud Functions have the ability to react to a new remote config (A/B tests use these under the hood). So you could create a function that:
Is triggered on new remote config creation.
Stores a mapping of parameter key to name etc in Cloud Firestore or similar.
Your app could then query this Cloud Firestore / hosted file / wherever you hosted it.
Note: I couldn't actually figure out how to get any info about the remote config in Cloud Functions. Things like version name, update time etc are available, but description seems suspiciously vague.
We wanted to get these informations for our Tracking/Analyzing Tools. So we implemented a workaround and added an additional Remote Config variable abTestName_variantInfo where we set a short info in the A/B-Testing configuration about the name of the A/B-Test and the variant we are running in. With this we can use the main Remote Config variable for the variant changes (e.g layout or functionality) without being dependent of our own naming-convention for tracking.
For example we used the two Remote Config variables ratingTest_variant (values: emojis or stars) and added the variable ratingTest_variantInfo (values: abTest_rating_emojis and abTest_rating_stars).

What will firebase.getInstance() get if there are multiple databases

I was using a firebase database in my Android app. Now I need to use another database but I want to know for the old versions of my app what will "firebaseDatabase.getInstance" return? Which database from my databases will be returned?
FirebaseDatabase.getInstance();
.getInstance() function actually gets a string of url as an input parameter. You can see it here.
Alternatively you can follow the tutorial here to actually create more than one instance in one app with manually setting FirebaseOptions, FirebaseApp and FirebaseDatabase objects.
// Manually configure Firebase Options
FirebaseOptions options = new FirebaseOptions.Builder()
.setApplicationId("1:27992087142:android:ce3b6448250083d1") // Required for Analytics.
.setApiKey("AIzaSyADUe90ULnQDuGShD9W23RDP0xmeDc6Mvw") // Required for Auth.
.setDatabaseUrl("https://myproject.firebaseio.com") // Required for RTDB.
.build();
// Initialize with secondary app.
FirebaseApp.initializeApp(this /* Context */, options, "secondary");
// Retrieve secondary app.
FirebaseApp secondary = FirebaseApp.getInstance("secondary");
// Get the database for the other app.
FirebaseDatabase secondaryDatabase = FirebaseDatabase.getInstance(secondary);
Please also read the notes in the end, as using different databases might confuse your Google Analytics, causing analytics data drops.

Use multiple firebase accounts in single android app for google analytics

I have a use case in which 1 app will be used by multiple separate companies (franchises) that will have their own marketing and management teams. I need the user to select a franchise when the mobile app starts up, and then from that point on, push all analytics data to that franchise's firebase (google analytics) account. Similarly any push notifications that are sent from that franchise's servers need to go to the user.
Is this configuration possible? In the past I used to set up a google analytics account for each franchise and just download the UA-xxx number from the server on franchise selection, and then set up the google analytics object based on that..
What is the appropriate way to achieve this via firebase connected to google analytics ?
I found the offical API reference: https://firebase.google.com/docs/configure/
This link explains how to do it for iOS but doesn't mention how to do it in android. It does say however that the firebase init runs before user code.. perhaps that means it is not possible?
Here is the init provider they mention: https://firebase.google.com/docs/reference/android/com/google/firebase/provider/FirebaseInitProvider
create for each new firebase app
FirebaseApp firebaseApp =
FirebaseApp.initializeApp(Context, FirebaseOptions,firebaseAppName);
you can create firebase app by passing options:
https://firebase.google.com/docs/reference/android/com/google/firebase/FirebaseOptions.Builder
FirebaseOptions options = new FirebaseOptions.Builder()
.setApiKey(String)
.setApplicationId(String)
.setDatabaseUrl(String)
.build();
then when You want to use Analytics you need to set default one by call:
FirebaseApp firebaseApp =
FirebaseApp.initializeApp(Context, FirebaseOptions,"[DEFAULT]");
keep in mind that only this DEFAULT firebase app will be used in analytics
but first off all you need to remove init provider in manifest
<!--remove firebase provider to init manually -->
<provider
android:name="com.google.firebase.provider.FirebaseInitProvider"
android:authorities="${applicationId}.firebaseinitprovider"
tools:node="remove"/>
and init default firebase app manually!
example how to send event via default firebase app(after initialized):
// get tracker instance
FirebaseAnalytics trakerInstance = FirebaseAnalytics.getInstance(context);
// create bundle for params
Bundle params = new Bundle();
// put param for example action
params.putString(ACTION_KEY, eventAction);
// send event
trackerInstance.logEvent(eventCategory, params);
#ceph3us I tried your solution, and it didn't work for me. If I
initialise firebase at runtime as you suggested then I get an error:
Missing google_app_id. Firebase Analytics disabled. Are you sure it is
working? – rMozes
first of all
did you removed default provider by putting in manifest tools:node="remove"?
did u initialized ['DEFAULT'] firebase app as i described
did you check if a ['DEFAULT'] firebase app is initialized before sending any event ?
ad 1) the error: Missing google_app_id suggests me that gardle plugin didn't removed provider as expected - and your app is starting a default provider which complains about missing app id
ad 3) don't do any calls relying on firebase app before firebase app is initialized
protected boolean isDefaultFirebaseAppInitialized() {
try {
// try get
return FirebaseApp.getInstance(FirebaseApp.DEFAULT_APP_NAME) != null;
// catch illegal state exc
} catch (IllegalStateException ise) {
// on such case not initialized
return false;
}
}
// check on default app
if(isDefaultFirebaseAppInitialized()) {
// get tracker
FirebaseAnalytics trakerInstance = FirebaseAnalytics.getInstance(context);
// log event
trackerInstance.logEvent(eventCategory, params);
} else {
// postpone
}
#ceph3us 1. I removed the provider as you said, if I wouldn't remove
the provider and try to initialise the default app then I would get a
IllegalStateException about default firebase app already exists. 2. I
initialised default firebase app as you described. 3. Yes, I logged
the app name and app_id and there is a log: AppName: [DEFAULT], Google
app id: valid_app_id But when I want to post something to analytics,
then it says that: Missing google_app_id. Firebase Analytics disabled.
– rMozes
99,99% you are trying to send event before app is initialized ! (see above example)
#ceph3us I initialise FirebaseApp in the onCreate method of
Application subclass. I send event to firebase when a button is
clicked. Anyway I uploaded a test project to github, can you take a
look at it? It is possible I misunderstand something.
github.com/rMozes/TestFirebaseAnalytics – rMozes
try (as initialization is asynchronous - so until you test its initialized you cant send events):
https://github.com/rMozes/TestFirebaseAnalytics/compare/master...c3ph3us:patch-2
if above fails you have two more chances :)
by define the string in xml: as a placeholder
<string name="google_app_id">fuck_you_google</string>
1) change the placeholder id via reflections to other one before any call to init/or use from firebase:
hint how to
2) provide a own text for the placeholder id via own Resources class implementation for Resources.getString(R.string.google_app_id) call:
an example how to achieve it (adding a new resources by id)
if you proper change R field via reflections or substitute a call to Resources.getString(R.string.google_app_id) with own text you will not get message wrong app id: "fuck_you_google"
& good luck :)
It's possible to have multiple Firebase instance in your apps
FirebaseOptions options = new FirebaseOptions.Builder()
.setApplicationId("Your AppId") // Required for Analytics.
.setApiKey("You ApiKey") // Required for Auth.
.setDatabaseUrl("Your DB Url") // If you wanted to
.build();
FirebaseApp.initializeApp(context, options, "CompanyA");
Which you can get Firebase instances by
FirebaseApp appCompanyA = FirebaseApp.getInstance("CompanyA");
You can see the full example use of Auth and Realtime Database using multiple Firebase instance here
I'll leave this solution here which may duplicate with another answers for someone who might need this
Hope this help :)

Is possible to use two firebase project in a single android application? if it is possible. how? [duplicate]

I'm trying to have one project in Firebase that will be responsible for one common thing that all Apps.
That is, I want to create Apps, then have these Apps access a particular Firebase Database of a project.
Looking at the Firebase Android docs, I can't find a way to send data to another firebase database in another project using the following, but where reference is of another project.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("example");
ref.push().setValue(d).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
finish();
}
});
You'll need to initialize a second FirebaseApp object with explicit options in your code:
FirebaseOptions options = new FirebaseOptions.Builder()
.setApiKey("AI...j0")
.setApplicationId("1:5...e0")
.setDatabaseUrl("https://myapp.firebaseio.com")
.build();
FirebaseApp secondApp = FirebaseApp.initializeApp(getApplicationContext(), options, "second app");
FirebaseDatabase secondDatabase = FirebaseDatabase.getInstance(secondApp);
secondDatabase.getReference().setValue(ServerValue.TIMESTAMP);
I got the configuration values from the second project's google-services.json. The API Key is under a property called api_key, the Application ID came from a property called mobilesdk_app_id and the database URL came from a property called firebase_url.
Also see the documentation on using multiple projects in your application.

Is it ok to keep constructing new Firebase refs or I should reuse? [duplicate]

This question already has answers here:
Best way to handle Firebase references with Android
(3 answers)
Closed 6 years ago.
I'm extremely new to Firebase. Naively, I would imagine it's ok to keep instantiating new Firebase refs that point to the same location and using them interchangeably.
However, I'm not sure if there are any subtleties around caching or other considerations I should be aware of that make reusing the same reference for the same Firebase location desireable/preferable over creating a new one.
Thank you.
Reuse old firebase ref instance when:
if you only refer to one filebase app url during get/set data to server progress.
Ex:
public class myActivity extends AppCompatActivity{
private Firebase firebaseRef; //declare unique refer instance for all code
#Override
protected void onCreate(Bundle bundle){
super(bundle);
//other code here......
Firebase.setAndroidContext(this);
firebaseRef = new Firebase("http://mydb.firebaseio.com/node");
}
}
Create new firebase ref instance when:
if use have plan to access to multi firebase app or multi nodes url then you can create a firebase instance at anytime, anywhare you want ref to them.
Ex:
Firebase firebaseFrefA = new Firebase("http://mydb.firebaseio.com/a");
Firebase firebaseFrefB = new Firebase("http://mydb.firebaseio.com/b");
Firebase firebaseFrefC = new Firebase("http://mydb.firebaseio.com/c");
Firebase firebaseFrefAU = new Firebase("http://mydb.firebaseio.com/a/u");
Note: firebase automaticly control all own's instance so you can free create new instance to use.

Categories

Resources