Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Last active November 23, 2025 12:01
Show Gist options
  • Select an option

  • Save sunmeat/aa041b8e4c500f0edd60fe3f77827915 to your computer and use it in GitHub Desktop.

Select an option

Save sunmeat/aa041b8e4c500f0edd60fe3f77827915 to your computer and use it in GitHub Desktop.
very simple example of usage firebase android
build.gradle.kts (Project):
plugins {
alias(libs.plugins.android.application) apply false
alias(libs.plugins.google.gms.google.services) apply false
}
==========================================================================================================
build.gradle.kts (Module):
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.google.gms.google.services) // !!!
}
android {
namespace = "site.sunmeat.helloworld"
compileSdk = 36
defaultConfig {
applicationId = "site.sunmeat.helloworld"
minSdk = 33
targetSdk = 36
versionCode = 1
versionName = "1.0"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
}
dependencies {
implementation(libs.appcompat)
implementation(libs.activity)
implementation(libs.constraintlayout)
implementation(libs.material)
implementation(libs.firebase.database) // !!!
implementation(libs.firebase.firestore)
implementation(libs.firebase.core)
}
==========================================================================================================
libs.versions.toml:
[versions]
agp = "8.13.1"
firebaseCore = "21.1.1"
firebaseFirestore = "26.0.2"
appcompat = "1.7.1"
material = "1.13.0"
activity = "1.12.0"
constraintlayout = "2.2.1"
googleGmsGoogleServices = "4.4.4"
firebaseDatabase = "22.0.1"
[libraries]
firebase-core = { module = "com.google.firebase:firebase-core", version.ref = "firebaseCore" }
firebase-firestore = { module = "com.google.firebase:firebase-firestore", version.ref = "firebaseFirestore" }
appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" }
material = { group = "com.google.android.material", name = "material", version.ref = "material" }
activity = { group = "androidx.activity", name = "activity", version.ref = "activity" }
constraintlayout = { group = "androidx.constraintlayout", name = "constraintlayout", version.ref = "constraintlayout" }
firebase-database = { group = "com.google.firebase", name = "firebase-database", version.ref = "firebaseDatabase" }
[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
google-gms-google-services = { id = "com.google.gms.google-services", version.ref = "googleGmsGoogleServices" }
==========================================================================================================
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.AppCompat.DayNight.DarkActionBar">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
==========================================================================================================
MAinActivity.java:
package site.sunmeat.helloworld;
import android.os.Bundle;
import android.util.Log;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import java.util.*;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
// колекція в Firestore, куди будемо зберігати числа
private static final String COLLECTION_NAME = "random_numbers";
private FirebaseFirestore db;
private ArrayList<String> numbersList;
private ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ініціалізація Firestore
db = FirebaseFirestore.getInstance();
Button btnSend = findViewById(R.id.btnSend);
Button btnLoad = findViewById(R.id.btnLoad);
ListView listView = findViewById(R.id.listView);
numbersList = new ArrayList<>();
adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, numbersList);
listView.setAdapter(adapter);
// надіслати випадкове число
btnSend.setOnClickListener(v -> sendRandomNumber());
// завантажити всі числа з Firestore
btnLoad.setOnClickListener(v -> loadAllNumbers());
}
// генеруємо випадкове число від 1 до 1000 і відправляємо в Firestore
private void sendRandomNumber() {
var random = new Random();
int randomNumber = random.nextInt(1000) + 1;
// cтворюємо об’єкт, який збережемо
Map<String, Object> data = new HashMap<>();
data.put("number", randomNumber);
data.put("timestamp", System.currentTimeMillis());
// додаємо документ у колекцію
db.collection(COLLECTION_NAME)
.add(data)
.addOnSuccessListener(documentReference -> {
Toast.makeText(MainActivity.this,
"Число надіслано: " + randomNumber, Toast.LENGTH_SHORT).show();
Log.d(TAG, "Документ додано з ID: " + documentReference.getId());
})
.addOnFailureListener(e -> {
Toast.makeText(MainActivity.this,
"Помилка: " + e.getMessage(), Toast.LENGTH_SHORT).show();
Log.w(TAG, "Помилка додавання", e);
});
}
// зчитуємо всі документи з колекції і виводимо числа
private void loadAllNumbers() {
db.collection(COLLECTION_NAME)
.orderBy("timestamp") // сортуємо за часом (не обов’язково)
.get()
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
numbersList.clear();
for (QueryDocumentSnapshot document : task.getResult()) {
Long num = document.getLong("number");
if (num != null) {
numbersList.add(num.toString());
}
}
adapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this,
"Завантажено " + numbersList.size() + " чисел", Toast.LENGTH_SHORT).show();
} else {
Log.w(TAG, "Помилка завантаження", task.getException());
Toast.makeText(MainActivity.this,
"Не вдалося завантажити дані", Toast.LENGTH_SHORT).show();
}
});
}
}
==========================================================================================================
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:text="Тест Firestore"
android:textSize="24sp" />
<Button
android:id="@+id/btnSend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="Надіслати випадкове число" />
<Button
android:id="@+id/btnLoad"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:text="Завантажити всі числа" />
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
==========================================================================================================
Project perspective, app / google-services.json: (цей файл маэ бути створено автоматично, якщо не буде - то можна завантажити в розділі Project Overview на сайті https://console.firebase.google.com/
{
"project_info": {
"project_number": "1055250888714",
"project_id": "site-sunmeat-student",
"storage_bucket": "site-sunmeat-student.firebasestorage.app"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:1055250888714:android:577b2fc50b2ddbf7db47f3",
"android_client_info": {
"package_name": "site.sunmeat.helloworld"
}
},
"oauth_client": [],
"api_key": [
{
"current_key": "AIzaSyCsB7y4Jq4fSUkjDYxdOsxdy9its6jo1hk"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": []
}
}
}
],
"configuration_version": "1"
}
==========================================================================================================
rules:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment