├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── drawable
│ │ │ │ ├── gift.png
│ │ │ │ ├── console.png
│ │ │ │ ├── crash.png
│ │ │ │ ├── email.png
│ │ │ │ ├── github.png
│ │ │ │ ├── google.png
│ │ │ │ ├── iterate.png
│ │ │ │ ├── money.png
│ │ │ │ ├── phone.png
│ │ │ │ ├── profile.png
│ │ │ │ ├── server.png
│ │ │ │ ├── sign_up.png
│ │ │ │ ├── twitter.png
│ │ │ │ ├── analytics.png
│ │ │ │ ├── anonymous.png
│ │ │ │ ├── facebook.png
│ │ │ │ ├── stopwatch.png
│ │ │ │ ├── crashlytics.png
│ │ │ │ ├── dynamic_link.png
│ │ │ │ ├── ic_launcher.png
│ │ │ │ ├── btn_gift.xml
│ │ │ │ └── btn_default.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── values
│ │ │ │ ├── colors.xml
│ │ │ │ ├── dimens.xml
│ │ │ │ ├── styles.xml
│ │ │ │ └── strings.xml
│ │ │ ├── xml
│ │ │ │ └── remote_config_defaults.xml
│ │ │ ├── values-w820dp
│ │ │ │ └── dimens.xml
│ │ │ ├── layout
│ │ │ │ ├── activity_git_auth.xml
│ │ │ │ ├── activity_remote_config.xml
│ │ │ │ ├── activity_analytics.xml
│ │ │ │ ├── activity_fabric_crashlytics.xml
│ │ │ │ ├── user_row.xml
│ │ │ │ ├── activity_download_file.xml
│ │ │ │ ├── activity_rewarded_ad_colony.xml
│ │ │ │ ├── activity_video_rewarded.xml
│ │ │ │ ├── activity_monitoring.xml
│ │ │ │ ├── activity_uilist_adapter.xml
│ │ │ │ ├── activity_push_server.xml
│ │ │ │ ├── activity_users.xml
│ │ │ │ ├── activity_users_ui.xml
│ │ │ │ ├── activity_push_notifications.xml
│ │ │ │ ├── activity_google_login.xml
│ │ │ │ ├── activity_sort.xml
│ │ │ │ ├── activity_login_facebook.xml
│ │ │ │ ├── activity_dynamic_link.xml
│ │ │ │ ├── activity_delete.xml
│ │ │ │ ├── activity_dbretriever.xml
│ │ │ │ ├── activity_anonymous.xml
│ │ │ │ ├── activity_crash.xml
│ │ │ │ ├── activity_ads.xml
│ │ │ │ ├── activity_invites.xml
│ │ │ │ ├── activity_account.xml
│ │ │ │ ├── activity_phone_auth.xml
│ │ │ │ ├── activity_github.xml
│ │ │ │ ├── activity_google_logged.xml
│ │ │ │ ├── activity_facebook_user.xml
│ │ │ │ ├── activity_login_email_pass.xml
│ │ │ │ ├── activity_twitter_auth.xml
│ │ │ │ ├── activity_register.xml
│ │ │ │ ├── activity_update_user.xml
│ │ │ │ └── activity_main.xml
│ │ │ └── values-es
│ │ │ │ └── strings.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── melardev
│ │ │ │ └── tutorialsfirebase
│ │ │ │ ├── model
│ │ │ │ └── User.java
│ │ │ │ ├── AppFirebase.java
│ │ │ │ ├── service
│ │ │ │ ├── FirebaseInstanceIDService.java
│ │ │ │ └── FirebaseMessageingService.java
│ │ │ │ └── activities
│ │ │ │ ├── ActivityFabricCrashlytics.java
│ │ │ │ ├── ActivityPushNotificationsConsole.java
│ │ │ │ ├── ActivityCrash.java
│ │ │ │ ├── ActivityInvites.java
│ │ │ │ ├── ActivityPushNotificationsServer.java
│ │ │ │ ├── ActivityDelete.java
│ │ │ │ ├── ActivityMonitoring.java
│ │ │ │ ├── ActivityAds.java
│ │ │ │ ├── ActivityAnalytics.java
│ │ │ │ ├── ActivityFacebookUser.java
│ │ │ │ ├── ActivityGoogleLogged.java
│ │ │ │ ├── ActivityVideoRewarded.java
│ │ │ │ ├── ActivityUIListAdapter.java
│ │ │ │ ├── MainActivity.java
│ │ │ │ ├── ActivityRemoteConfig.java
│ │ │ │ ├── ActivityLoginEmailPass.java
│ │ │ │ ├── ActivityUsersUI.java
│ │ │ │ ├── ActivityAnonymous.java
│ │ │ │ ├── ActivityRegister.java
│ │ │ │ ├── ActivityGoogleLogin.java
│ │ │ │ ├── ActivityLoginFacebook.java
│ │ │ │ ├── ActivityPhoneAuth.java
│ │ │ │ ├── ActivitySort.java
│ │ │ │ ├── ActivityDownloadFile.java
│ │ │ │ ├── ActivityUsers.java
│ │ │ │ ├── ActivityDynamicLink.java
│ │ │ │ ├── ActivityTwitterAuth.java
│ │ │ │ ├── ActivityUpdateUser.java
│ │ │ │ └── ActivityDBRetriever.java
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── melardev
│ │ │ └── tutorialsfirebase
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── melardev
│ │ └── tutorialsfirebase
│ │ └── ExampleInstrumentedTest.java
├── fabric.properties
├── proguard-rules.pro
├── google-services.json
└── build.gradle
├── settings.gradle
├── .idea
├── copyright
│ └── profiles_settings.xml
├── encodings.xml
├── vcs.xml
├── kotlinc.xml
├── modules.xml
├── runConfigurations.xml
├── gradle.xml
├── compiler.xml
└── misc.xml
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── README.md
├── gradle.properties
├── phpScripts
├── register_token.php
└── send_push.php
├── gradlew.bat
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/.idea/copyright/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/gift.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/melardev/TutsAndroidFirebase/HEAD/app/src/main/res/drawable/gift.png
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/melardev/TutsAndroidFirebase/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/drawable/console.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/melardev/TutsAndroidFirebase/HEAD/app/src/main/res/drawable/console.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/crash.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/melardev/TutsAndroidFirebase/HEAD/app/src/main/res/drawable/crash.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/email.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/melardev/TutsAndroidFirebase/HEAD/app/src/main/res/drawable/email.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/github.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/melardev/TutsAndroidFirebase/HEAD/app/src/main/res/drawable/github.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/google.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/melardev/TutsAndroidFirebase/HEAD/app/src/main/res/drawable/google.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/iterate.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/melardev/TutsAndroidFirebase/HEAD/app/src/main/res/drawable/iterate.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/money.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/melardev/TutsAndroidFirebase/HEAD/app/src/main/res/drawable/money.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/phone.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/melardev/TutsAndroidFirebase/HEAD/app/src/main/res/drawable/phone.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/profile.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/melardev/TutsAndroidFirebase/HEAD/app/src/main/res/drawable/profile.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/server.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/melardev/TutsAndroidFirebase/HEAD/app/src/main/res/drawable/server.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/sign_up.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/melardev/TutsAndroidFirebase/HEAD/app/src/main/res/drawable/sign_up.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/twitter.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/melardev/TutsAndroidFirebase/HEAD/app/src/main/res/drawable/twitter.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/analytics.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/melardev/TutsAndroidFirebase/HEAD/app/src/main/res/drawable/analytics.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/anonymous.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/melardev/TutsAndroidFirebase/HEAD/app/src/main/res/drawable/anonymous.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/facebook.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/melardev/TutsAndroidFirebase/HEAD/app/src/main/res/drawable/facebook.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/stopwatch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/melardev/TutsAndroidFirebase/HEAD/app/src/main/res/drawable/stopwatch.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/crashlytics.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/melardev/TutsAndroidFirebase/HEAD/app/src/main/res/drawable/crashlytics.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/dynamic_link.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/melardev/TutsAndroidFirebase/HEAD/app/src/main/res/drawable/dynamic_link.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/melardev/TutsAndroidFirebase/HEAD/app/src/main/res/drawable/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/melardev/TutsAndroidFirebase/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/melardev/TutsAndroidFirebase/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/melardev/TutsAndroidFirebase/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/melardev/TutsAndroidFirebase/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/melardev/TutsAndroidFirebase/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 | .externalNativeBuild
10 |
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/btn_gift.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/fabric.properties:
--------------------------------------------------------------------------------
1 | #Contains API Secret used to validate your application. Commit to internal source control; avoid making secret public.
2 | #Fri Jun 30 18:28:21 CEST 2017
3 | apiSecret=ce5750cc30323c1ea0f503eff35a9b6280cfc1040e1678271923f7efcc1c4e9d
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/.idea/kotlinc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Fri Nov 03 12:53:12 CET 2017
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
7 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # TutsAndroidFirebase
2 |
3 | - Code for my youtube playlist on Firebase with Android, I leave her the project code as well as the php scripts (in phpScripts folder)
4 | - Código para la lista de reproducción de Youtube de Cómo usar Firebase en Android, dejo aquí el proyecto así como los scripts PHP(en la carpeta phpScripts)
5 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/btn_default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
9 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/remote_config_defaults.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | performance_enabled
5 | false
6 |
7 |
8 | msg_of_the_day
9 | work hard today to get good(remote) results tomorrow
10 |
11 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/model/User.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.model;
2 |
3 | /**
4 | * Created by melardev on 3/22/2017.
5 | */
6 |
7 | public class User {
8 | public String name;
9 | public String image;
10 |
11 | public User() {
12 | }
13 |
14 | public User(String name, String image) {
15 | this.name = name;
16 | this.image = image;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_git_auth.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/test/java/com/melardev/tutorialsfirebase/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_remote_config.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_analytics.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
14 |
15 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/AppFirebase.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase;
2 |
3 | import android.app.Application;
4 |
5 | import com.crashlytics.android.Crashlytics;
6 |
7 | import io.fabric.sdk.android.Fabric;
8 |
9 | /**
10 | * Created by melardev on 6/30/2017.
11 | */
12 |
13 | public class AppFirebase extends Application {
14 | @Override
15 | public void onCreate() {
16 | super.onCreate();
17 | Fabric.with(this, new Crashlytics());
18 | Crashlytics.setUserName("Melardev_tester");
19 | Crashlytics.setUserEmail("melardev@test.com");
20 | Crashlytics.setUserIdentifier("owner");
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_fabric_crashlytics.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/user_row.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
13 |
14 |
18 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_download_file.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_rewarded_ad_colony.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_video_rewarded.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
14 |
15 |
18 |
19 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in C:\Users\melardev\AppData\Local\Android\Sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_monitoring.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
14 |
15 |
20 |
21 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_uilist_adapter.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
17 |
18 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_push_server.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
17 |
18 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_users.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
17 |
18 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_users_ui.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
17 |
18 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_push_notifications.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
17 |
18 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/service/FirebaseInstanceIDService.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.service;
2 |
3 | import com.google.firebase.iid.FirebaseInstanceId;
4 | import com.google.firebase.iid.FirebaseInstanceIdService;
5 | import com.melardev.tutorialsfirebase.activities.ActivityPushNotificationsServer;
6 |
7 | /*
8 | to handle the creation, rotation, and updating of registration tokens. This is required for sending to specific devices or for creating device groups.
9 | */
10 | public class FirebaseInstanceIDService extends FirebaseInstanceIdService {
11 | public FirebaseInstanceIDService() {
12 | }
13 |
14 | @Override
15 | public void onTokenRefresh() {
16 | super.onTokenRefresh();
17 | String token = FirebaseInstanceId.getInstance().getToken();
18 |
19 | ActivityPushNotificationsServer.registerToken(token);
20 | }
21 |
22 | }
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
19 | #disable Monitoring at build time. useful for pre-release app
20 | #firebasePerformanceInstrumentationEnabled=false
--------------------------------------------------------------------------------
/phpScripts/register_token.php:
--------------------------------------------------------------------------------
1 | multi_query($query);
17 | $result = $conn->store_result();
18 | $rows = $result->fetch_all();*/
19 | $q = "INSERT IGNORE INTO `firebase` SET `token`= ?;";
20 | $stmt = $conn->prepare($q);
21 |
22 | if (!$stmt)
23 | exit();
24 |
25 | $stmt->bind_param("s", $token);
26 | if ($stmt->execute())
27 | echo "Success!";
28 |
29 | $stmt->close();
30 | $conn->close();
31 | }
32 | ?>
33 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityFabricCrashlytics.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.support.v7.app.AppCompatActivity;
4 | import android.os.Bundle;
5 | import android.view.View;
6 |
7 | import com.crashlytics.android.Crashlytics;
8 | import com.melardev.tutorialsfirebase.R;
9 |
10 | import io.fabric.sdk.android.Fabric;
11 |
12 | public class ActivityFabricCrashlytics extends AppCompatActivity {
13 |
14 | @Override
15 | protected void onCreate(Bundle savedInstanceState) {
16 | super.onCreate(savedInstanceState);
17 | //Fabric.with(this, new Crashlytics());
18 | setContentView(R.layout.activity_fabric_crashlytics);
19 |
20 | //in the dashboard we are going to see this info
21 | }
22 |
23 | public void forceCrash(View view) {
24 | throw new RuntimeException("this is a crash");
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/melardev/tutorialsfirebase/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.melardev.tutorialsfirebase", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_google_login.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_sort.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
17 |
18 |
22 |
23 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_login_facebook.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
20 |
21 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_dynamic_link.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
13 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_delete.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
18 |
19 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_dbretriever.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
14 |
15 |
20 |
21 |
22 |
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityPushNotificationsConsole.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.support.v7.app.AppCompatActivity;
4 | import android.os.Bundle;
5 | import android.util.Log;
6 | import android.widget.TextView;
7 | import android.widget.Toast;
8 |
9 | import com.google.firebase.iid.FirebaseInstanceId;
10 | import com.google.firebase.messaging.FirebaseMessaging;
11 | import com.melardev.tutorialsfirebase.R;
12 |
13 | public class ActivityPushNotificationsConsole extends AppCompatActivity {
14 |
15 | private TextView txt;
16 |
17 | @Override
18 | protected void onCreate(Bundle savedInstanceState) {
19 | super.onCreate(savedInstanceState);
20 | setContentView(R.layout.activity_push_notifications);
21 |
22 | txt = (TextView) findViewById(R.id.txtResult);
23 | // FirebaseMessaging.getInstance().subscribeToTopic("Tutorials");
24 | if (getIntent().hasExtra("result")) {
25 | txt.setText(getIntent().getStringExtra("result"));
26 | return;
27 | }
28 | String token = FirebaseInstanceId.getInstance().getToken();
29 | Log.d("token", token);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_anonymous.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
18 |
19 |
24 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_crash.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
18 |
19 |
24 |
25 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_ads.xml:
--------------------------------------------------------------------------------
1 |
2 |
14 |
15 |
21 |
22 |
28 |
29 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_invites.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
19 |
20 |
30 |
31 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_account.xml:
--------------------------------------------------------------------------------
1 |
2 |
13 |
14 |
19 |
20 |
26 |
27 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/phpScripts/send_push.php:
--------------------------------------------------------------------------------
1 | query($sql);
7 | $tokens = array();
8 |
9 | if ($result->num_rows > 0) {
10 |
11 | while ($row = $result->fetch_assoc()) {
12 | $tokens[] = $row["token"];
13 | }
14 | }
15 |
16 |
17 | $message = array("message" => "Message from server",
18 | "customKey" => "customValue");
19 |
20 | $url = 'https://fcm.googleapis.com/fcm/send';
21 | $fields = array(
22 | //'registration_ids' => $tokens, //tokens
23 | //"condition" => "'dogs' in topics || 'cats' in topics",
24 | "to" => "/topics/news",
25 | 'data' => $message
26 | );
27 |
28 | $headers = array('Content-Type: application/json',
29 | 'Authorization:key=AAAARXTrehs:APA91bExefFtL890BcFO4-Sq8_Kdrk251Sq_BM6WyC4bk-1cfD_s8gk-9-kW2iqm5ywaTM7JUh_yFQKWwuR_eYILaQR3ad0g--Fpd3Mr6sxHOtwnMKCFSNbQl3uahsBmVnH3mL2U7Xlwg3adH_QVF1yAiXpw8Nglmg'
30 | );
31 |
32 | $ch = curl_init($url);
33 | curl_setopt($ch, CURLOPT_POST, true);
34 | curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
35 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
36 | curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
37 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
38 | curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
39 | $result = curl_exec($ch);
40 |
41 | if ($result == FALSE)
42 | die('Curl failed: ' . curl_error($ch));
43 |
44 | curl_close($ch);
45 | $conn->close();
46 |
47 | ?>
48 |
--------------------------------------------------------------------------------
/app/src/main/res/values-es/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | Registro
4 | Login con email y contraseña
5 | Login con numero de telefono
6 | Login anonimamente
7 | Login con Github
8 | Editar mi perfil
9 | Iterar base de datos
10 | Push Notifications desde Consola
11 | Push Notifications desde servidor
12 | Login con Facebook
13 | Base de datos como objeto y Map
14 | Editar mi perfil
15 | Cuando pulsas el boton para verificar tu telefono se enviara un SMS, es posible que se apliquen tasas dependiendo de tu compañia o país.
16 | Iniciar sesión
17 | sesión cerrada
18 | TutorialesFirebase
19 | Sesión iniciada
20 | cerrar sesión
21 | view my profile
22 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_phone_auth.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
17 |
18 |
23 |
24 |
29 |
30 |
36 |
37 |
42 |
43 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_github.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
15 |
16 |
21 |
22 |
29 |
30 |
31 |
32 |
38 |
39 |
43 |
44 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_google_logged.xml:
--------------------------------------------------------------------------------
1 |
2 |
13 |
14 |
19 |
20 |
25 |
26 |
32 |
33 |
39 |
40 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_facebook_user.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
20 |
21 |
26 |
27 |
33 |
34 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityCrash.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.app.ProgressDialog;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.os.Bundle;
6 | import android.util.Log;
7 | import android.view.View;
8 |
9 | import com.google.firebase.crash.FirebaseCrash;
10 | import com.melardev.tutorialsfirebase.R;
11 |
12 | import java.util.ArrayList;
13 |
14 |
15 | public class ActivityCrash extends AppCompatActivity {
16 |
17 | @Override
18 | protected void onCreate(Bundle savedInstanceState) {
19 | super.onCreate(savedInstanceState);
20 | setContentView(R.layout.activity_crash);
21 | }
22 |
23 | public void reportFatal(View view) {
24 | ArrayList array = new ArrayList();
25 | String value = array.get(2);
26 | Log.d("Log", value);
27 | }
28 |
29 | public void reportNonFatal(View view) {
30 | FirebaseCrash.logcat(Log.INFO, "INFO_LOGCAT", "ClassCastException will ocurr");
31 | FirebaseCrash.log("LogExample");
32 | try {
33 | throw new ClassCastException();
34 | } catch (ClassCastException ex) {
35 |
36 | FirebaseCrash.logcat(Log.ERROR, "ERROR_LOGCAT", "ClassCastException caught");
37 | FirebaseCrash.report(ex);
38 | }
39 | }
40 |
41 | public void reportNonFatal2(View view) {
42 | FirebaseCrash.logcat(Log.INFO, "INFO_LOGCAT", "RuntimeException will occur");
43 | FirebaseCrash.log("LogExample");
44 | try {
45 | throw new RuntimeException();
46 | } catch (RuntimeException ex) {
47 | FirebaseCrash.report(ex);
48 | FirebaseCrash.logcat(Log.ERROR, "ERROR_LOGCAT", "RuntimeException caught");
49 |
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_login_email_pass.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
20 |
21 |
33 |
34 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_twitter_auth.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
13 |
14 |
21 |
22 |
32 |
33 |
34 |
38 |
39 |
43 |
44 |
48 |
49 |
50 |
51 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/service/FirebaseMessageingService.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.service;
2 |
3 | import android.app.NotificationManager;
4 | import android.app.PendingIntent;
5 | import android.content.Intent;
6 | import android.support.v4.app.NotificationCompat;
7 |
8 | import com.google.firebase.messaging.FirebaseMessagingService;
9 | import com.google.firebase.messaging.RemoteMessage;
10 | import com.melardev.tutorialsfirebase.activities.ActivityPushNotificationsServer;
11 |
12 | import java.util.Map;
13 |
14 | public class FirebaseMessageingService extends FirebaseMessagingService {
15 | public FirebaseMessageingService() {
16 | }
17 |
18 | @Override
19 | public void onMessageReceived(RemoteMessage remoteMessage) {
20 | super.onMessageReceived(remoteMessage);
21 |
22 | String result = "From : " + remoteMessage.getFrom() + "\nMessageId = " + remoteMessage.getMessageId() + "\nMessageType = " + remoteMessage.getMessageType()
23 | + "\nCollapeseKey = " + remoteMessage.getCollapseKey() + "\nTo: " + remoteMessage.getTo() + "\nTtl = " + remoteMessage.getTtl()
24 | + "\nSent Time = " + remoteMessage.getSentTime();/*+"\nTitle = " + remoteMessage.getNotification().getTitle()
25 | + "\nBody = " + remoteMessage.getNotification().getBody()*/
26 | Map map = remoteMessage.getData();
27 | for (String key : map.keySet())
28 | result += "\n(" + key + "," + map.get(key) + ")";
29 |
30 | Intent intent = new Intent(this, ActivityPushNotificationsServer.class);
31 | intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
32 | intent.putExtra("result", result);
33 | PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
34 |
35 | NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
36 | .setAutoCancel(true)
37 | .setContentTitle("Firebase Cloud Messaging Demo")
38 | .setSmallIcon(android.R.drawable.stat_notify_chat)
39 | .setContentIntent(pi);
40 |
41 | NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
42 | manager.notify(0, builder.build());
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityInvites.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.content.Intent;
4 | import android.net.Uri;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.os.Bundle;
7 | import android.view.View;
8 | import android.webkit.WebView;
9 | import android.webkit.WebViewClient;
10 | import android.widget.Toast;
11 |
12 | import com.google.android.gms.appinvite.AppInviteInvitation;
13 | import com.melardev.tutorialsfirebase.R;
14 |
15 | public class ActivityInvites extends AppCompatActivity {
16 |
17 | private static final int RC_INVITE = 99;
18 |
19 | @Override
20 | protected void onCreate(Bundle savedInstanceState) {
21 | super.onCreate(savedInstanceState);
22 | setContentView(R.layout.activity_invites);
23 | }
24 |
25 | public void inviteFriend(View view) {
26 | Intent intent = new AppInviteInvitation.IntentBuilder("Check this awesome app!")
27 | .setMessage("Hi!, have you tested the new TutorialsFirebase App! check this out!")
28 | .setDeepLink(Uri.parse("https://m9guj.app.goo.gl/j6mu"))
29 | .setCustomImage(Uri.parse("http://www.iconsdb.com/icons/preview/orange/gift-3-xxl.png"))
30 | .setCallToActionText("LET'S GIVE IT A TRy!")
31 | //.setOtherPlatformsTargetApplication(AppInviteInvitation.IntentBuilder.PlatformMode.PROJECT_PLATFORM_IOS, "IOS_APP_CLIENT_ID")
32 | .build();
33 | startActivityForResult(intent, RC_INVITE);
34 | }
35 |
36 | @Override
37 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
38 | super.onActivityResult(requestCode, resultCode, data);
39 | if (requestCode == RC_INVITE) {
40 | if (resultCode == RESULT_OK) {
41 | String[] ids = AppInviteInvitation.getInvitationIds(resultCode, data);
42 | String message = "Invitations sent to the following ids : ";
43 | for (String id : ids) {
44 | message += id + ", ";
45 | }
46 | Toast.makeText(this, message.substring(0, message.length() - 1 - 1/*do not show last comma*/), Toast.LENGTH_SHORT).show();
47 | } else {
48 | Toast.makeText(this, "invitation failed to send or canceled", Toast.LENGTH_SHORT).show();
49 | }
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_register.xml:
--------------------------------------------------------------------------------
1 |
2 |
13 |
14 |
22 |
23 |
31 |
32 |
41 |
42 |
50 |
51 |
57 |
58 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityPushNotificationsServer.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.support.v7.app.AppCompatActivity;
4 | import android.os.Bundle;
5 | import android.util.Log;
6 | import android.widget.TextView;
7 |
8 | import com.google.android.gms.common.GoogleApiAvailability;
9 | import com.google.firebase.iid.FirebaseInstanceId;
10 | import com.google.firebase.messaging.FirebaseMessaging;
11 | import com.melardev.tutorialsfirebase.R;
12 |
13 | import java.io.IOException;
14 |
15 | import okhttp3.Call;
16 | import okhttp3.Callback;
17 | import okhttp3.FormBody;
18 | import okhttp3.OkHttpClient;
19 | import okhttp3.Request;
20 | import okhttp3.RequestBody;
21 | import okhttp3.Response;
22 |
23 | public class ActivityPushNotificationsServer extends AppCompatActivity {
24 |
25 | private TextView txt;
26 |
27 | @Override
28 | protected void onCreate(Bundle savedInstanceState) {
29 | super.onCreate(savedInstanceState);
30 | setContentView(R.layout.activity_push_server);
31 |
32 | txt = (TextView) findViewById(R.id.txtResult);
33 | if (getIntent().hasExtra("result")) {
34 | txt.setText(getIntent().getStringExtra("result"));
35 | return;
36 | }
37 | FirebaseMessaging.getInstance().subscribeToTopic("news");
38 | String token = FirebaseInstanceId.getInstance().getToken();
39 |
40 | Log.d("token", token);
41 | registerToken(token);
42 | }
43 |
44 | public static void registerToken(String token) {
45 | OkHttpClient client = new OkHttpClient();
46 | RequestBody body = new FormBody.Builder()
47 | .add("token", token)
48 | .build();
49 |
50 | Request request = new Request.Builder()
51 | .url("http://192.168.1.107:3333/firebase/register_token.php?XDEBUG_SESSION_START=netbeans")
52 | .post(body)
53 | .build();
54 |
55 | client.newCall(request).enqueue(new Callback() {
56 | @Override
57 | public void onFailure(Call call, IOException e) {
58 | Log.d("OkHttp", call.toString());
59 | }
60 |
61 | @Override
62 | public void onResponse(Call call, Response response) throws IOException {
63 | if (response.isSuccessful()) {
64 | String responseStr = response.body().string();
65 | Log.d("OkHttp", responseStr);
66 | }
67 | }
68 | });
69 |
70 | }
71 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityDelete.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.support.annotation.NonNull;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.os.Bundle;
6 | import android.view.View;
7 | import android.widget.Button;
8 |
9 | import com.google.firebase.auth.FirebaseAuth;
10 | import com.google.firebase.database.DatabaseReference;
11 | import com.google.firebase.database.FirebaseDatabase;
12 | import com.melardev.tutorialsfirebase.R;
13 |
14 | public class ActivityDelete extends AppCompatActivity {
15 |
16 | private DatabaseReference databasePost;
17 | private FirebaseAuth.AuthStateListener mAuthListener;
18 | private Button btnCreate;
19 | private Button btnDelete;
20 | private FirebaseAuth mAuth;
21 |
22 | @Override
23 | protected void onStart() {
24 | super.onStart();
25 | mAuth.addAuthStateListener(mAuthListener);
26 | }
27 |
28 |
29 |
30 | @Override
31 | protected void onCreate(Bundle savedInstanceState) {
32 | super.onCreate(savedInstanceState);
33 | setContentView(R.layout.activity_delete);
34 |
35 | mAuth = FirebaseAuth.getInstance();
36 | btnCreate = (Button) findViewById(R.id.createPost);
37 | btnDelete = (Button) findViewById(R.id.deletePosts);
38 |
39 | btnCreate.setOnClickListener(new View.OnClickListener() {
40 | @Override
41 | public void onClick(View v) {
42 | if (mAuth.getCurrentUser() == null || databasePost == null)
43 | return;
44 |
45 | DatabaseReference newPost = databasePost.push();
46 | newPost.child("title").setValue("titleExample");
47 | newPost.child("description").setValue("descriptionExample");
48 | }
49 | });
50 |
51 |
52 | btnDelete.setOnClickListener(new View.OnClickListener() {
53 | @Override
54 | public void onClick(View v) {
55 | if (mAuth.getCurrentUser() == null || databasePost == null)
56 | return;
57 |
58 | databasePost.setValue(null);
59 | }
60 | });
61 |
62 | mAuthListener = new FirebaseAuth.AuthStateListener() {
63 | @Override
64 | public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
65 | if (firebaseAuth.getCurrentUser() != null) {
66 | databasePost = FirebaseDatabase.getInstance().getReference().child("posts");
67 |
68 | }
69 | }
70 | };
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityMonitoring.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.os.Build;
4 | import android.os.Handler;
5 | import android.os.Message;
6 | import android.support.v7.app.AppCompatActivity;
7 | import android.os.Bundle;
8 | import android.view.View;
9 | import android.widget.Toast;
10 |
11 |
12 | import com.google.firebase.perf.FirebasePerformance;
13 | import com.google.firebase.perf.metrics.AddTrace;
14 | import com.google.firebase.perf.metrics.Trace;
15 | import com.melardev.tutorialsfirebase.R;
16 |
17 | import java.util.Random;
18 | import java.util.concurrent.ThreadLocalRandom;
19 |
20 | public class ActivityMonitoring extends AppCompatActivity {
21 |
22 | private Random random;
23 | Handler mHandlerMainThread = new Handler(new Handler.Callback() {
24 | @Override
25 | public boolean handleMessage(Message msg) {
26 | Toast.makeText(ActivityMonitoring.this, "Done ...", Toast.LENGTH_SHORT).show();
27 | return true;
28 | }
29 | });
30 |
31 | @Override
32 | protected void onCreate(Bundle savedInstanceState) {
33 | super.onCreate(savedInstanceState);
34 | setContentView(R.layout.activity_monitoring);
35 | random = new Random();
36 | }
37 |
38 | public void loadData(View view) {
39 | Trace tracer = FirebasePerformance.getInstance().newTrace("loadDataTrace");
40 | tracer.start();
41 | //load some data
42 | int value = random.nextInt(100);
43 | if (value < 50)
44 | tracer.incrementCounter("load_data_fails");
45 | else
46 | tracer.incrementCounter("load_data_successes");
47 |
48 | tracer.stop();
49 | mHandlerMainThread.sendEmptyMessage(0);
50 | }
51 |
52 |
53 | public void loadData2(View view) {
54 | final int min = 2 * 1000;
55 | final int max = 10 * 1000;
56 | new Thread(new Runnable() {
57 | @AddTrace(name = "loadData", enabled = true)
58 | @Override
59 | public void run() {
60 | try {
61 | int timeToSleep;
62 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
63 | timeToSleep = ThreadLocalRandom.current().nextInt(min, max);
64 | } else
65 | timeToSleep = random.nextInt((max - min) + 1) + min;
66 | Thread.sleep(timeToSleep);
67 | mHandlerMainThread.sendEmptyMessage(0);
68 | } catch (InterruptedException e) {
69 | e.printStackTrace();
70 | }
71 | }
72 | }).start();
73 |
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityAds.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.support.v7.app.AppCompatActivity;
4 | import android.os.Bundle;
5 | import android.view.View;
6 | import android.widget.Button;
7 | import android.widget.Toast;
8 |
9 | import com.google.android.gms.ads.AdListener;
10 | import com.google.android.gms.ads.AdRequest;
11 | import com.google.android.gms.ads.AdView;
12 | import com.google.android.gms.ads.InterstitialAd;
13 | import com.google.android.gms.ads.MobileAds;
14 | import com.google.android.gms.ads.NativeExpressAdView;
15 | import com.melardev.tutorialsfirebase.R;
16 |
17 | public class ActivityAds extends AppCompatActivity {
18 |
19 | private AdView adBanner;
20 | private InterstitialAd adInterstitial;
21 | private NativeExpressAdView adNativeExpress;
22 | private AdRequest adRequest;
23 |
24 | @Override
25 | protected void onCreate(Bundle savedInstanceState) {
26 | super.onCreate(savedInstanceState);
27 | setContentView(R.layout.activity_ads);
28 | MobileAds.initialize(getApplicationContext(), getResources().getString(R.string.app_id));
29 | adRequest = new AdRequest.Builder()
30 | .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
31 | .build();
32 | adBanner = (AdView) findViewById(R.id.ad_banner);
33 | adNativeExpress = (NativeExpressAdView) findViewById(R.id.adNativeExpress);
34 |
35 | adInterstitial = new InterstitialAd(this);
36 | adInterstitial.setAdUnitId(getResources().getString(R.string.intersticial_aui));
37 | adInterstitial.loadAd(adRequest);
38 | adInterstitial.setAdListener(new AdListener() {
39 | @Override
40 | public void onAdLoaded() {
41 | super.onAdLoaded();
42 | if(adInterstitial.isLoaded())
43 | adInterstitial.show();
44 | }
45 |
46 | @Override
47 | public void onAdClosed() {
48 | loadOtherAds();
49 | }
50 | });
51 |
52 | }
53 |
54 | private void loadOtherAds() {
55 | adBanner.loadAd(adRequest);
56 | adNativeExpress.loadAd(adRequest);
57 | }
58 |
59 | @Override
60 | protected void onPause() {
61 | if (adBanner != null)
62 | adBanner.pause();
63 |
64 | super.onPause();
65 | }
66 |
67 | @Override
68 | protected void onResume() {
69 | super.onResume();
70 | if (adBanner != null)
71 | adBanner.resume();
72 |
73 | }
74 |
75 | @Override
76 | protected void onDestroy() {
77 | if (adBanner != null)
78 | adBanner.destroy();
79 |
80 | super.onDestroy();
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/app/google-services.json:
--------------------------------------------------------------------------------
1 | {
2 | "project_info": {
3 | "project_number": "298314332699",
4 | "firebase_url": "https://melardebug.firebaseio.com",
5 | "project_id": "melardebug",
6 | "storage_bucket": "melardebug.appspot.com"
7 | },
8 | "client": [
9 | {
10 | "client_info": {
11 | "mobilesdk_app_id": "1:298314332699:android:f68ff7187fe197c7",
12 | "android_client_info": {
13 | "package_name": "com.melardev.firebasetutorials"
14 | }
15 | },
16 | "oauth_client": [
17 | {
18 | "client_id": "298314332699-c6kda9dovia4i6lrbioekgfih78k7f61.apps.googleusercontent.com",
19 | "client_type": 1,
20 | "android_info": {
21 | "package_name": "com.melardev.firebasetutorials",
22 | "certificate_hash": "0225FA6D00EAFC3FE98B39475410E3F30D4DBE40"
23 | }
24 | },
25 | {
26 | "client_id": "298314332699-jlllv0f21b0fj9jjv4pt86t0n29jagtk.apps.googleusercontent.com",
27 | "client_type": 3
28 | }
29 | ],
30 | "api_key": [
31 | {
32 | "current_key": "AIzaSyBv3k8c4KJtjSpnOVgMxMY1xjdAat7OIqA"
33 | }
34 | ],
35 | "services": {
36 | "analytics_service": {
37 | "status": 1
38 | },
39 | "appinvite_service": {
40 | "status": 1,
41 | "other_platform_oauth_client": []
42 | },
43 | "ads_service": {
44 | "status": 2
45 | }
46 | }
47 | },
48 | {
49 | "client_info": {
50 | "mobilesdk_app_id": "1:298314332699:android:3fdc68652208d5a1",
51 | "android_client_info": {
52 | "package_name": "com.melardev.tutorialsfirebase"
53 | }
54 | },
55 | "oauth_client": [
56 | {
57 | "client_id": "298314332699-6b4trlgibuns9giuakgr06m9i9k8u9j6.apps.googleusercontent.com",
58 | "client_type": 1,
59 | "android_info": {
60 | "package_name": "com.melardev.tutorialsfirebase",
61 | "certificate_hash": "0225FA6D00EAFC3FE98B39475410E3F30D4DBE40"
62 | }
63 | },
64 | {
65 | "client_id": "298314332699-jlllv0f21b0fj9jjv4pt86t0n29jagtk.apps.googleusercontent.com",
66 | "client_type": 3
67 | }
68 | ],
69 | "api_key": [
70 | {
71 | "current_key": "AIzaSyBv3k8c4KJtjSpnOVgMxMY1xjdAat7OIqA"
72 | }
73 | ],
74 | "services": {
75 | "analytics_service": {
76 | "status": 1
77 | },
78 | "appinvite_service": {
79 | "status": 1,
80 | "other_platform_oauth_client": []
81 | },
82 | "ads_service": {
83 | "status": 2
84 | }
85 | }
86 | }
87 | ],
88 | "configuration_version": "1"
89 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityAnalytics.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.os.Build;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.os.Bundle;
6 | import android.view.View;
7 |
8 | import com.google.firebase.analytics.FirebaseAnalytics;
9 | import com.melardev.tutorialsfirebase.R;
10 |
11 | import java.util.Random;
12 | import java.util.concurrent.ThreadLocalRandom;
13 |
14 | public class ActivityAnalytics extends AppCompatActivity {
15 |
16 | private static final String EVT_RANDOM_NUMBER = "random_number_generator";
17 | FirebaseAnalytics firebaseAnalytics;
18 | private Random random;
19 |
20 | @Override
21 | protected void onCreate(Bundle savedInstanceState) {
22 | super.onCreate(savedInstanceState);
23 | setContentView(R.layout.activity_analytics);
24 | firebaseAnalytics = FirebaseAnalytics.getInstance(this);
25 | firebaseAnalytics.logEvent(FirebaseAnalytics.Event.TUTORIAL_BEGIN, null);
26 | setupFirebaseAnalytics();
27 | random = new Random();
28 | }
29 |
30 | private void setupFirebaseAnalytics() {
31 | String osVersion = Build.VERSION.RELEASE;
32 | String model = Build.MANUFACTURER + " - " + Build.MODEL;
33 | firebaseAnalytics.setMinimumSessionDuration(10 * 1000); //10seconds in this app before starting a session and collecting data
34 | firebaseAnalytics.setSessionTimeoutDuration(30 * 60 * 1000); //30 minutes of inactivity will lead to termination of this session
35 | firebaseAnalytics.setUserProperty("os_version_melar", osVersion); //useless because the Firebase SDK already gives us this info.
36 | firebaseAnalytics.setUserProperty("device_model_lol", model); //useless because the Firebase SDK already gives us this info.
37 | firebaseAnalytics.setUserProperty("non_existing_property", "whatWillHappen????"); //useless because the Firebase SDK already gives us this info.
38 |
39 | }
40 |
41 | public void logEvent(View view) {
42 |
43 | Bundle bundle = new Bundle();
44 | bundle.putInt("randomAPI_1", random.nextInt(1000 + 1));
45 | bundle.putInt("randomAPI_2", random.nextInt(1000 + 1));
46 | bundle.putInt("randomAPI_3", random.nextInt(1000 + 1));
47 |
48 | //custom event
49 | firebaseAnalytics.logEvent(EVT_RANDOM_NUMBER, bundle);
50 |
51 | if (false) {
52 | Bundle bundle2 = new Bundle();
53 | firebaseAnalytics.logEvent(FirebaseAnalytics.Event.REMOVE_FROM_CART, bundle2);
54 | firebaseAnalytics.logEvent(FirebaseAnalytics.Param.LOCATION, bundle2);
55 | }
56 | }
57 |
58 | @Override
59 | protected void onStop() {
60 | firebaseAnalytics.logEvent(FirebaseAnalytics.Event.TUTORIAL_COMPLETE, null);
61 | super.onStop();
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityFacebookUser.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.content.Intent;
4 | import android.support.annotation.NonNull;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.os.Bundle;
7 | import android.util.Log;
8 | import android.view.View;
9 | import android.widget.Button;
10 | import android.widget.ImageView;
11 | import android.widget.TextView;
12 |
13 | import com.facebook.login.widget.LoginButton;
14 | import com.google.firebase.auth.FirebaseAuth;
15 | import com.google.firebase.auth.FirebaseUser;
16 | import com.google.firebase.auth.UserInfo;
17 | import com.melardev.tutorialsfirebase.R;
18 | import com.squareup.picasso.Picasso;
19 |
20 | public class ActivityFacebookUser extends AppCompatActivity {
21 |
22 | private FirebaseAuth.AuthStateListener mAuthListener;
23 | private FirebaseAuth mAuth;
24 | private Button btnOut;
25 | private TextView txtEmail, txtUser;
26 | private ImageView imgProfile;
27 |
28 | @Override
29 | protected void onStart() {
30 | super.onStart();
31 | mAuth.addAuthStateListener(mAuthListener);
32 | }
33 |
34 | @Override
35 | protected void onCreate(Bundle savedInstanceState) {
36 | super.onCreate(savedInstanceState);
37 | setContentView(R.layout.activity_facebook_user);
38 |
39 | mAuth = FirebaseAuth.getInstance();
40 | btnOut = (LoginButton) findViewById(R.id.btnOut);
41 | txtUser = (TextView) findViewById(R.id.txtUser);
42 | txtEmail = (TextView) findViewById(R.id.txtEmail);
43 | imgProfile = (ImageView) findViewById(R.id.imgProfile);
44 |
45 | btnOut.setOnClickListener(new View.OnClickListener() {
46 | @Override
47 | public void onClick(View v) {
48 | mAuth.signOut();
49 | }
50 | });
51 | mAuthListener = new FirebaseAuth.AuthStateListener() {
52 | @Override
53 | public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
54 | FirebaseUser user = firebaseAuth.getCurrentUser();
55 | if (user != null) {
56 |
57 | for (UserInfo userInfo : user.getProviderData()) {
58 | Log.d("TAG", userInfo.getProviderId());
59 | }
60 |
61 | txtUser.setText(user.getDisplayName());
62 | txtEmail.setText(user.getEmail());
63 | Picasso.with(ActivityFacebookUser.this).load(user.getPhotoUrl()).into(imgProfile);
64 | } else {
65 | Intent intent = new Intent(ActivityFacebookUser.this, ActivityLoginFacebook.class);
66 | intent.putExtra("logout", true);
67 | startActivity(intent);
68 | finish();
69 | }
70 |
71 | }
72 | };
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityGoogleLogged.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.content.Intent;
4 | import android.support.annotation.NonNull;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.os.Bundle;
7 | import android.util.Log;
8 | import android.view.View;
9 | import android.widget.ImageView;
10 | import android.widget.TextView;
11 |
12 | import com.google.android.gms.common.SignInButton;
13 | import com.google.firebase.auth.FirebaseAuth;
14 | import com.google.firebase.auth.FirebaseUser;
15 | import com.google.firebase.auth.UserInfo;
16 | import com.melardev.tutorialsfirebase.R;
17 | import com.squareup.picasso.Picasso;
18 |
19 | public class ActivityGoogleLogged extends AppCompatActivity {
20 |
21 | private FirebaseAuth.AuthStateListener mAuthListener;
22 | private FirebaseAuth mAuth;
23 | private SignInButton btnOut;
24 | private TextView txtEmail, txtUser;
25 | private ImageView imgProfile;
26 |
27 | @Override
28 | protected void onStart() {
29 | super.onStart();
30 | mAuth.addAuthStateListener(mAuthListener);
31 | }
32 |
33 | @Override
34 | protected void onCreate(Bundle savedInstanceState) {
35 | super.onCreate(savedInstanceState);
36 | setContentView(R.layout.activity_google_logged);
37 |
38 | mAuth = FirebaseAuth.getInstance();
39 | btnOut = (SignInButton) findViewById(R.id.btn_sign_google);
40 | txtUser = (TextView) findViewById(R.id.txtUser);
41 | txtEmail = (TextView) findViewById(R.id.txtEmail);
42 | imgProfile = (ImageView) findViewById(R.id.imgProfile);
43 |
44 | mAuthListener = new FirebaseAuth.AuthStateListener() {
45 | @Override
46 | public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
47 | FirebaseUser user = firebaseAuth.getCurrentUser();
48 | if (user != null) {
49 |
50 | for (UserInfo userInfo : user.getProviderData()) {
51 | Log.d("TAG", userInfo.getProviderId());
52 | }
53 |
54 | txtUser.setText(user.getDisplayName());
55 | txtEmail.setText(user.getEmail());
56 | Picasso.with(ActivityGoogleLogged.this).load(user.getPhotoUrl()).into(imgProfile);
57 |
58 | btnOut.setOnClickListener(new View.OnClickListener() {
59 | @Override
60 | public void onClick(View v) {
61 | mAuth.signOut();
62 | }
63 | });
64 | } else {
65 | Intent intent = new Intent(ActivityGoogleLogged.this, ActivityGoogleLogin.class);
66 | startActivity(intent);
67 | finish();
68 | }
69 |
70 | }
71 | };
72 |
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 | Android
36 |
37 |
38 | Android > Lint > Correctness
39 |
40 |
41 | Java
42 |
43 |
44 | Java language level migration aidsJava
45 |
46 |
47 |
48 |
49 | Android
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 | 1.8
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityVideoRewarded.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.os.Handler;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.os.Bundle;
6 | import android.widget.Toast;
7 |
8 | import com.google.android.gms.ads.AdRequest;
9 | import com.google.android.gms.ads.MobileAds;
10 | import com.google.android.gms.ads.reward.RewardItem;
11 | import com.google.android.gms.ads.reward.RewardedVideoAd;
12 | import com.google.android.gms.ads.reward.RewardedVideoAdListener;
13 | import com.melardev.tutorialsfirebase.R;
14 |
15 | public class ActivityVideoRewarded extends AppCompatActivity implements RewardedVideoAdListener {
16 |
17 | private RewardedVideoAd adReward;
18 |
19 | @Override
20 | protected void onCreate(Bundle savedInstanceState) {
21 | super.onCreate(savedInstanceState);
22 | setContentView(R.layout.activity_video_rewarded);
23 | /**
24 | * Does not work, the code is fine, but I have to make some setup, sorry
25 | */
26 | MobileAds.initialize(this, getString(R.string.app_id));
27 | adReward = MobileAds.getRewardedVideoAdInstance(this);
28 | adReward.setRewardedVideoAdListener(this);
29 |
30 |
31 | AdRequest adRequest = new AdRequest.Builder().build();
32 | adReward.loadAd(getResources().getString(R.string.rewarded_aui), adRequest);
33 |
34 | final Handler handler = new Handler();
35 | handler.postDelayed(new Runnable() {
36 | @Override
37 | public void run() {
38 | if (adReward.isLoaded())
39 | adReward.show();
40 | else
41 | handler.postDelayed(this, 300);
42 | }
43 | }, 300);
44 | }
45 |
46 | @Override
47 | public void onRewardedVideoAdLoaded() {
48 | Toast.makeText(this, "AdLoaded", Toast.LENGTH_SHORT).show();
49 | }
50 |
51 | @Override
52 | public void onRewardedVideoAdOpened() {
53 | Toast.makeText(this, "Started", Toast.LENGTH_SHORT).show();
54 | }
55 |
56 | @Override
57 | public void onRewardedVideoStarted() {
58 | Toast.makeText(this, "Started", Toast.LENGTH_SHORT).show();
59 | }
60 |
61 | @Override
62 | public void onRewardedVideoAdClosed() {
63 | Toast.makeText(this, "Closed", Toast.LENGTH_SHORT).show();
64 | }
65 |
66 | @Override
67 | public void onRewarded(RewardItem rewardItem) {
68 | Toast.makeText(this, rewardItem.getAmount(), Toast.LENGTH_SHORT).show();
69 | }
70 |
71 | @Override
72 | public void onRewardedVideoAdLeftApplication() {
73 | Toast.makeText(this, "onRewardedVideoAdLeftApplication", Toast.LENGTH_SHORT).show();
74 | }
75 |
76 | @Override
77 | public void onRewardedVideoAdFailedToLoad(int errorCode) {
78 | Toast.makeText(this, "onRewardedVideoAdFailedToLoad", Toast.LENGTH_SHORT).show();
79 | }
80 |
81 | @Override
82 | protected void onPause() {
83 | super.onPause();
84 | adReward.pause(this);
85 | }
86 |
87 | @Override
88 | protected void onResume() {
89 | super.onResume();
90 | adReward.resume(this);
91 | }
92 |
93 | }
94 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityUIListAdapter.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.content.Intent;
4 | import android.support.annotation.NonNull;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.os.Bundle;
7 | import android.view.View;
8 | import android.widget.ImageView;
9 | import android.widget.ListView;
10 | import android.widget.TextView;
11 |
12 | import com.firebase.ui.database.FirebaseListAdapter;
13 | import com.google.firebase.auth.FirebaseAuth;
14 | import com.google.firebase.database.DatabaseReference;
15 | import com.google.firebase.database.FirebaseDatabase;
16 | import com.melardev.tutorialsfirebase.R;
17 | import com.squareup.picasso.Picasso;
18 |
19 | public class ActivityUIListAdapter extends AppCompatActivity {
20 |
21 | private ListView listView;
22 | private DatabaseReference dbUsers;
23 | private FirebaseAuth.AuthStateListener mAuthListener;
24 | private FirebaseAuth mAuth;
25 |
26 | @Override
27 | protected void onStart() {
28 | super.onStart();
29 | mAuth.addAuthStateListener(mAuthListener);
30 | }
31 |
32 | @Override
33 | protected void onCreate(Bundle savedInstanceState) {
34 | super.onCreate(savedInstanceState);
35 | setContentView(R.layout.activity_uilist_adapter);
36 |
37 | listView = (ListView) findViewById(R.id.listView);
38 | mAuth = FirebaseAuth.getInstance();
39 | mAuthListener = new FirebaseAuth.AuthStateListener() {
40 | @Override
41 | public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
42 | if (firebaseAuth.getCurrentUser() == null) {
43 | Intent logIntent = new Intent(ActivityUIListAdapter.this, ActivityLoginEmailPass.class);
44 | logIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
45 | startActivity(logIntent);
46 | } else {
47 | dbUsers = FirebaseDatabase.getInstance().getReference().child("users");
48 | FirebaseListAdapter firebaseRecyclerAdapter = new FirebaseListAdapter(
49 | ActivityUIListAdapter.this,
50 | ActivityUsersUI.User.class,
51 | R.layout.user_row,
52 | dbUsers
53 | ) {
54 | TextView txtName;
55 | ImageView imgProfile;
56 |
57 | @Override
58 | protected void populateView(View v, ActivityUsersUI.User model, int position) {
59 | txtName = (TextView) v.findViewById(R.id.txtUser);
60 | imgProfile = (ImageView) v.findViewById(R.id.imageUser);
61 | txtName.setText(model.name);
62 | if (!model.image.equals("default"))
63 | Picasso.with(ActivityUIListAdapter.this).load(model.image).into(imgProfile);
64 | }
65 | };
66 | listView.setAdapter(firebaseRecyclerAdapter);
67 | }
68 | }
69 | };
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | TutorialsFirebase
3 | 298314332699-jlllv0f21b0fj9jjv4pt86t0n29jagtk.apps.googleusercontent.com
4 | 1034125140043072
5 | ca-app-pub-1424004185102767~8159572932
6 | ca-app-pub-1424004185102767/9636306133
7 | ca-app-pub-1424004185102767/2113039330
8 | ca-app-pub-1424004185102767/9496705333
9 | ca-app-pub-1424004185102767/6543238937
10 | 14e282be129295c3e68ce5913b111c78f7a67278
11 | When you click the button to verify your phone number an SMS will be sent to you, rates may be applied to you
12 | Sign Up
13 | Login with email and pass
14 | Login With Phone Number
15 | Login Anonymously
16 | Login With Github
17 | Manage Account
18 | ADS Demo
19 | Iterate Firebase Database
20 | Firebase UI RecyclerAdapter
21 | Push Notifications From Console
22 | Push Notifications from Server
23 | Login with Facebook
24 | Database as object and Map
25 | Manage User
26 | Performance Monitoring tool
27 | Firebase Analytics
28 | Dynamic Link
29 | Crashlytics
30 | sign In
31 | signOut
32 | signed In
33 | signed Out
34 | Firebase Crash
35 | signed in succesfully
36 | failed to sign in with credential
37 | Now you are logged In
38 | view my profile
39 | R7FUNs5Xht749L03tgACuD43H
40 | egWSgdBwfQr5n2duekArPcKyDsZmaxuLDOGaj0xDgpI6RcOkfQ
41 | Signed in succesfully to Firebase with twitter Session
42 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | repositories {
3 | maven { url 'https://maven.fabric.io/public' }
4 | }
5 |
6 | dependencies {
7 | classpath('io.fabric.tools:gradle:1.+'){
8 | exclude group: 'com.google.guava', module: 'guava-jdk5'
9 | }
10 | }
11 | }
12 | apply plugin: 'com.android.application'
13 |
14 | repositories {
15 | maven { url 'https://maven.fabric.io/public' }
16 |
17 | google()
18 | }
19 |
20 | apply plugin: 'com.google.firebase.firebase-perf' //remote monitoring tool
21 | apply plugin: 'io.fabric'
22 |
23 | android {
24 |
25 | compileSdkVersion 26
26 | buildToolsVersion '26.0.2'
27 | defaultConfig {
28 | applicationId "com.melardev.tutorialsfirebase"
29 | minSdkVersion 15
30 | targetSdkVersion 26
31 | versionCode 1
32 | versionName "1.0"
33 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
34 | }
35 | buildTypes {
36 | release {
37 | minifyEnabled false
38 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
39 | }
40 | debug {
41 | minifyEnabled true
42 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
43 | }
44 | }
45 |
46 | }
47 |
48 | dependencies {
49 | compile fileTree(include: ['*.jar'], dir: 'libs')
50 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
51 | exclude group: 'com.android.support', module: 'support-annotations'
52 | })
53 |
54 | compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
55 | transitive = true;
56 | }
57 | compile "com.android.support:appcompat-v7:$rootProject.ext.androidUiVersion"
58 | compile "com.android.support:customtabs:$rootProject.ext.androidUiVersion"
59 | compile "com.android.support:palette-v7:$rootProject.ext.androidUiVersion"
60 | compile "com.android.support:cardview-v7:$rootProject.ext.androidUiVersion"
61 | compile "com.android.support:design:$rootProject.ext.androidUiVersion"
62 | compile 'com.squareup.okhttp3:okhttp:3.8.1'
63 | compile 'com.squareup.picasso:picasso:2.5.2'
64 | compile 'com.google.firebase:firebase-core:11.4.2'
65 | compile 'com.google.firebase:firebase-auth:11.4.2'
66 | compile 'com.google.android.gms:play-services-auth:11.4.2'
67 | compile 'com.google.firebase:firebase-database:11.4.2'
68 | compile 'com.google.firebase:firebase-storage:11.4.2'
69 | compile 'com.facebook.android:facebook-android-sdk:[4,5)'
70 | compile 'com.twitter.sdk.android:twitter:3.1.1'
71 | compile 'com.google.firebase:firebase-messaging:11.4.2'
72 | compile 'com.google.firebase:firebase-ads:11.4.2'
73 | compile 'com.google.firebase:firebase-crash:11.4.2'
74 | compile 'com.google.firebase:firebase-config:11.4.2'
75 | compile 'com.google.firebase:firebase-invites:11.4.2'
76 | compile 'com.google.firebase:firebase-appindexing:11.4.2'
77 | compile 'com.firebaseui:firebase-ui-storage:1.1.0'
78 | compile 'com.firebaseui:firebase-ui-database:1.1.0'
79 | compile 'com.google.firebase:firebase-perf:11.4.2'
80 | compile "com.android.support:recyclerview-v7:$rootProject.ext.androidUiVersion"
81 | compile 'com.android.support.constraint:constraint-layout:1.1.0-beta3'
82 | compile 'com.github.yalantis:ucrop:2.2.1-native'
83 |
84 | testCompile 'junit:junit:4.12'
85 | }
86 | apply plugin: 'com.google.gms.google-services'
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.content.Intent;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.os.Bundle;
6 | import android.view.View;
7 |
8 | import com.melardev.tutorialsfirebase.R;
9 |
10 | public class MainActivity extends AppCompatActivity {
11 |
12 |
13 | @Override
14 | protected void onCreate(Bundle savedInstanceState) {
15 | super.onCreate(savedInstanceState);
16 | setContentView(R.layout.activity_main);
17 | /*new AlertDialog.Builder(this).setMessage("Please note that the demos may not work, because I have added a sha1 fingerprint in my firebase console," +
18 | " the code shown in my tutorials in youtube was tested and it doest work, take it as a template and copy it to your android studio project, " +
19 | "update the values in strings.xml accordingly, search me in youtube by searching Melar Dev").setPositiveButton(android.R.string.ok, null).setCancelable(false).show();*/
20 | }
21 |
22 |
23 | public void registerDemo(View view) {
24 | startDemo(ActivityRegister.class);
25 | }
26 |
27 | public void loginDemo(View view) {
28 | startDemo(ActivityLoginEmailPass.class);
29 | }
30 |
31 | public void viewProfile(View view) {
32 | startDemo(ActivityAccount.class);
33 | }
34 |
35 | public void adsDemo(View view) {
36 | startDemo(ActivityAds.class);
37 | }
38 |
39 | public void iterateDbDemo(View view) {
40 | startDemo(ActivityUsers.class);
41 | }
42 |
43 | public void firebaseUIRecyclerDemo(View view) {
44 | startDemo(ActivityUsersUI.class);
45 | }
46 |
47 | public void pushNotifConsoleDemo(View view) {
48 | startDemo(ActivityPushNotificationsConsole.class);
49 | }
50 |
51 | public void pushNotifServer(View view) {
52 | startDemo(ActivityPushNotificationsServer.class);
53 | }
54 |
55 | public void facebookDemo(View view) {
56 | startDemo(ActivityLoginFacebook.class);
57 | }
58 |
59 | public void loginAnonymously(View view) {
60 | startDemo(ActivityAnonymous.class);
61 | }
62 |
63 | public void startDemo(Class className) {
64 | startActivity(new Intent(this, className));
65 | }
66 |
67 | public void dbObjMap(View view) {
68 | startDemo(ActivityDBRetriever.class);
69 | }
70 |
71 | public void manageUser(View view) {
72 | startDemo(ActivityUpdateUser.class);
73 | }
74 |
75 | public void monitoringTool(View view) {
76 | startDemo(ActivityMonitoring.class);
77 | }
78 |
79 | public void firebaseAnalytics(View view) {
80 | startDemo(ActivityAnalytics.class);
81 | }
82 |
83 | public void dynamicLink(View view) {
84 | startDemo(ActivityDynamicLink.class);
85 | }
86 |
87 | public void fabricCrashlytics(View view) {
88 | startDemo(ActivityFabricCrashlytics.class);
89 | }
90 |
91 | public void phoneNumber(View view) {
92 | startDemo(ActivityPhoneAuth.class);
93 | }
94 |
95 | public void loginGithub(View view) {
96 | startDemo(ActivityGithub.class);
97 | }
98 |
99 | public void googleLogin(View view) {
100 | startDemo(ActivityGoogleLogin.class);
101 | }
102 |
103 | public void firebaseCrashReporter(View view) {
104 | startDemo(ActivityCrash.class);
105 | }
106 |
107 | public void twitterLogin(View view) {
108 | startDemo(ActivityTwitterAuth.class);
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_update_user.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
14 |
15 |
20 |
21 |
26 |
27 |
28 |
29 |
32 |
33 |
39 |
40 |
45 |
46 |
47 |
50 |
51 |
57 |
58 |
63 |
64 |
65 |
68 |
69 |
75 |
76 |
81 |
82 |
83 |
86 |
87 |
92 |
93 |
98 |
99 |
100 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityRemoteConfig.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.support.annotation.NonNull;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.os.Bundle;
6 | import android.support.v7.appcompat.BuildConfig;
7 | import android.widget.Toast;
8 |
9 | import com.google.android.gms.tasks.OnCompleteListener;
10 | import com.google.android.gms.tasks.Task;
11 | import com.google.firebase.perf.FirebasePerformance;
12 | import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
13 | import com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings;
14 | import com.melardev.tutorialsfirebase.R;
15 |
16 | public class ActivityRemoteConfig extends AppCompatActivity {
17 |
18 | private static final java.lang.String PERF_ENABLE = "performance_enabled";
19 | private static final java.lang.String MSG_DAILY = "msg_of_the_day";
20 | private FirebaseRemoteConfig remoteConfig;
21 |
22 | @Override
23 | protected void onCreate(Bundle savedInstanceState) {
24 | super.onCreate(savedInstanceState);
25 | setContentView(R.layout.activity_remote_config);
26 |
27 | remoteConfig = FirebaseRemoteConfig.getInstance();
28 |
29 | //Build a developer mode RemoteConfigSettings, increasing the number of requests we can make during development.
30 | //In the future class this will offer more features
31 | FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
32 | .setDeveloperModeEnabled(BuildConfig.DEBUG)
33 | .build();
34 |
35 | remoteConfig.setConfigSettings(configSettings);
36 |
37 | //first to be safe you set the defaults
38 | remoteConfig.setDefaults(R.xml.remote_config_defaults);
39 | //then override the settings with the remote values
40 | fetchConfigs();
41 | }
42 |
43 | private void fetchConfigs() {
44 | long expirationTime;
45 | if (remoteConfig.getInfo().getConfigSettings().isDeveloperModeEnabled())
46 | expirationTime = 0; //we do not have that limit of fetches per hour, so each time we are going to fetch
47 | else
48 | expirationTime = 60 * 60; //1 hour since we have some limitation in the number of fetches
49 |
50 | remoteConfig.fetch(expirationTime) //fetches configs either from local cache or remote config server (if LAST_FETCH_STATUS_SUCCESS > expirationTime)
51 | .addOnCompleteListener(this, new OnCompleteListener() {
52 | @Override
53 | public void onComplete(@NonNull Task task) {
54 | if (task.isSuccessful()) {
55 | Toast.makeText(ActivityRemoteConfig.this, "fetched succesfully", Toast.LENGTH_SHORT).show();
56 | remoteConfig.activateFetched(); //after a fetched success, we have to activate the fetched config so they can be used(active config)
57 |
58 | if (remoteConfig.getBoolean(PERF_ENABLE))
59 | FirebasePerformance.getInstance().setPerformanceCollectionEnabled(true);
60 | else
61 | FirebasePerformance.getInstance().setPerformanceCollectionEnabled(false);
62 |
63 | String tipOfDay = remoteConfig.getString(MSG_DAILY);
64 | Toast.makeText(ActivityRemoteConfig.this, tipOfDay, Toast.LENGTH_SHORT).show();
65 | } else
66 | Toast.makeText(ActivityRemoteConfig.this, "Failed to fetch remote config", Toast.LENGTH_SHORT).show();
67 | }
68 | });
69 |
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityLoginEmailPass.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.app.ProgressDialog;
4 | import android.content.Intent;
5 | import android.support.annotation.NonNull;
6 | import android.support.v7.app.AppCompatActivity;
7 | import android.os.Bundle;
8 | import android.text.TextUtils;
9 | import android.view.View;
10 | import android.widget.Button;
11 | import android.widget.EditText;
12 | import android.widget.Toast;
13 |
14 | import com.google.android.gms.tasks.OnCompleteListener;
15 | import com.google.android.gms.tasks.Task;
16 | import com.google.firebase.auth.AuthResult;
17 | import com.google.firebase.auth.FirebaseAuth;
18 | import com.melardev.tutorialsfirebase.R;
19 |
20 | public class ActivityLoginEmailPass extends AppCompatActivity {
21 |
22 | private FirebaseAuth mAuth;
23 | private EditText textEmail;
24 | private EditText textPass;
25 | private Button btnRegister;
26 | private ProgressDialog progressDialog;
27 | private FirebaseAuth.AuthStateListener mAuthListener;
28 |
29 | @Override
30 | protected void onCreate(Bundle savedInstanceState) {
31 | super.onCreate(savedInstanceState);
32 | setContentView(R.layout.activity_login_email_pass);
33 |
34 | progressDialog = new ProgressDialog(this);
35 | textEmail = (EditText) findViewById(R.id.etxt_email);
36 | textPass = (EditText) findViewById(R.id.etxt_password);
37 | btnRegister = (Button) findViewById(R.id.btn_login);
38 | mAuth = FirebaseAuth.getInstance();
39 |
40 | btnRegister.setOnClickListener(new View.OnClickListener() {
41 | @Override
42 | public void onClick(View v) {
43 | doLogin();
44 | }
45 | });
46 |
47 | mAuthListener = new FirebaseAuth.AuthStateListener() {
48 | @Override
49 | public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
50 | if (firebaseAuth.getCurrentUser() != null) {
51 | Toast.makeText(ActivityLoginEmailPass.this, "Now you are logged In " + firebaseAuth.getCurrentUser().getUid(), Toast.LENGTH_SHORT).show();
52 | Intent intent = new Intent(ActivityLoginEmailPass.this, ActivityAccount.class);
53 | startActivity(intent);
54 | finish();
55 | //mAuth.signOut();
56 | }
57 | }
58 | };
59 | }
60 |
61 | @Override
62 | protected void onStart() {
63 | super.onStart();
64 | mAuth.addAuthStateListener(mAuthListener);
65 | }
66 |
67 | private void doLogin() {
68 | String email = textEmail.getText().toString().trim();
69 | String password = textPass.getText().toString().trim();
70 |
71 | if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(password)) {
72 | progressDialog.setMessage("Loging , please wait");
73 | progressDialog.show();
74 | mAuth.signInWithEmailAndPassword(email, password)
75 | .addOnCompleteListener(new OnCompleteListener() {
76 | @Override
77 | public void onComplete(@NonNull Task task) {
78 | progressDialog.dismiss();
79 | if (task.isSuccessful()) {
80 | Toast.makeText(ActivityLoginEmailPass.this, "Login succesful", Toast.LENGTH_SHORT).show();
81 | } else
82 | Toast.makeText(ActivityLoginEmailPass.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
83 | }
84 | });
85 | }
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityUsersUI.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.content.Intent;
4 | import android.os.Bundle;
5 | import android.support.annotation.NonNull;
6 | import android.support.annotation.Nullable;
7 | import android.support.v7.app.AppCompatActivity;
8 | import android.support.v7.widget.LinearLayoutManager;
9 | import android.support.v7.widget.RecyclerView;
10 | import android.view.View;
11 | import android.widget.ImageView;
12 | import android.widget.TextView;
13 |
14 | import com.firebase.ui.database.FirebaseRecyclerAdapter;
15 | import com.google.firebase.auth.FirebaseAuth;
16 | import com.google.firebase.database.DatabaseReference;
17 | import com.google.firebase.database.FirebaseDatabase;
18 | import com.melardev.tutorialsfirebase.R;
19 | import com.squareup.picasso.Picasso;
20 |
21 | public class ActivityUsersUI extends AppCompatActivity {
22 |
23 | private RecyclerView recycler;
24 | private FirebaseAuth mAuth;
25 | private FirebaseAuth.AuthStateListener mAuthListener;
26 | private DatabaseReference databaseUsers;
27 |
28 | @Override
29 | protected void onCreate(@Nullable Bundle savedInstanceState) {
30 | super.onCreate(savedInstanceState);
31 | setContentView(R.layout.activity_users_ui);
32 | databaseUsers = FirebaseDatabase.getInstance().getReference().child("users");
33 | mAuth = FirebaseAuth.getInstance();
34 | recycler = (RecyclerView) findViewById(R.id.recyclerView);
35 | recycler.setLayoutManager(new LinearLayoutManager(this));
36 |
37 | mAuthListener = new FirebaseAuth.AuthStateListener() {
38 | @Override
39 | public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
40 | if (firebaseAuth.getCurrentUser() == null) {
41 | Intent logIntent = new Intent(ActivityUsersUI.this, ActivityLoginEmailPass.class);
42 | logIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
43 | startActivity(logIntent);
44 | finish();
45 | } else {
46 | FirebaseRecyclerAdapter firebaseRecyclerAdapter = new FirebaseRecyclerAdapter(
47 | User.class,
48 | R.layout.user_row,
49 | UserViewHolder.class,
50 | databaseUsers
51 | ) {
52 | @Override
53 | protected void populateViewHolder(final UserViewHolder holder, User model, int position) {
54 | holder.txtName.setText(model.name);
55 | if (!model.image.equals("default"))
56 | Picasso.with(ActivityUsersUI.this).load(model.image).into(holder.imgProfile);
57 | }
58 | };
59 | recycler.setAdapter(firebaseRecyclerAdapter);
60 | }
61 | }
62 | };
63 | }
64 |
65 | public static class User {
66 | String name;
67 | String image;
68 | }
69 |
70 | @Override
71 | protected void onStart() {
72 | super.onStart();
73 |
74 | if (mAuth.getCurrentUser() == null)
75 | return;
76 |
77 | mAuth.addAuthStateListener(mAuthListener);
78 | }
79 |
80 | public static class UserViewHolder extends RecyclerView.ViewHolder {
81 | TextView txtName;
82 | ImageView imgProfile;
83 |
84 | public UserViewHolder(View itemView) {
85 | super(itemView);
86 | txtName = (TextView) itemView.findViewById(R.id.txtUser);
87 | imgProfile = (ImageView) itemView.findViewById(R.id.imageUser);
88 | }
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityAnonymous.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.support.annotation.NonNull;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.os.Bundle;
6 | import android.view.View;
7 | import android.widget.Button;
8 | import android.widget.Toast;
9 |
10 | import com.google.android.gms.tasks.OnSuccessListener;
11 | import com.google.android.gms.tasks.Task;
12 | import com.google.firebase.auth.AuthCredential;
13 | import com.google.firebase.auth.AuthResult;
14 | import com.google.firebase.auth.EmailAuthProvider;
15 | import com.google.firebase.auth.FirebaseAuth;
16 | import com.melardev.tutorialsfirebase.R;
17 |
18 | public class ActivityAnonymous extends AppCompatActivity {
19 |
20 | private FirebaseAuth mAuth;
21 | private FirebaseAuth.AuthStateListener authListener;
22 | private Button btnLogIn;
23 | private Button btnLogOut;
24 | private Button btnPermanent;
25 |
26 | @Override
27 | protected void onStart() {
28 | super.onStart();
29 | mAuth.addAuthStateListener(authListener);
30 | }
31 |
32 | @Override
33 | protected void onCreate(Bundle savedInstanceState) {
34 | super.onCreate(savedInstanceState);
35 | setContentView(R.layout.activity_anonymous);
36 | btnLogIn = (Button) findViewById(R.id.btn_login);
37 | btnLogOut = (Button) findViewById(R.id.btn_sign_out);
38 | btnPermanent = (Button) findViewById(R.id.btn_permanent);
39 | mAuth = FirebaseAuth.getInstance();
40 |
41 | btnLogIn.setOnClickListener(new View.OnClickListener() {
42 | @Override
43 | public void onClick(View v) {
44 | Task resultTask = mAuth.signInAnonymously();
45 | resultTask.addOnSuccessListener(new OnSuccessListener() {
46 | @Override
47 | public void onSuccess(AuthResult authResult) {
48 | }
49 | });
50 | }
51 | });
52 |
53 | btnLogOut.setOnClickListener(new View.OnClickListener() {
54 | @Override
55 | public void onClick(View v) {
56 | mAuth.signOut();
57 | }
58 | });
59 |
60 | btnPermanent.setOnClickListener(new View.OnClickListener() {
61 | @Override
62 | public void onClick(View v) {
63 | String password = "password";
64 | String email = "malo@malo.com";
65 |
66 | AuthCredential credential = EmailAuthProvider.getCredential(email, password);
67 | mAuth.getCurrentUser().linkWithCredential(credential).addOnSuccessListener(new OnSuccessListener() {
68 | @Override
69 | public void onSuccess(AuthResult authResult) {
70 | btnPermanent.setVisibility(View.GONE);
71 | Toast.makeText(ActivityAnonymous.this, "done!", Toast.LENGTH_SHORT).show();
72 | }
73 | });
74 | }
75 | });
76 |
77 | authListener = new FirebaseAuth.AuthStateListener() {
78 | @Override
79 | public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
80 | if (firebaseAuth.getCurrentUser() != null) {
81 | // Toast.makeText(ActivityAnonymous.this, "SignedIn", Toast.LENGTH_SHORT).show();
82 | btnLogIn.setVisibility(View.GONE);
83 | btnLogOut.setVisibility(View.VISIBLE);
84 | btnPermanent.setVisibility(View.VISIBLE);
85 | //Toast.makeText(ActivityAnonymous.this, mAuth.getCurrentUser().getProviderId(), Toast.LENGTH_SHORT).show();
86 | } else {
87 | //Toast.makeText(ActivityAnonymous.this, "SignedOut", Toast.LENGTH_SHORT).show();
88 | btnLogOut.setVisibility(View.GONE);
89 | btnLogIn.setVisibility(View.VISIBLE);
90 | btnPermanent.setVisibility(View.GONE);
91 | }
92 | }
93 | };
94 | }
95 |
96 | }
97 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityRegister.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.app.ProgressDialog;
4 | import android.content.Intent;
5 | import android.os.Bundle;
6 | import android.support.annotation.NonNull;
7 | import android.support.v7.app.AppCompatActivity;
8 | import android.text.TextUtils;
9 | import android.view.View;
10 | import android.widget.Button;
11 | import android.widget.EditText;
12 | import android.widget.TextView;
13 | import android.widget.Toast;
14 |
15 | import com.google.android.gms.tasks.OnCompleteListener;
16 | import com.google.android.gms.tasks.Task;
17 | import com.google.firebase.auth.AuthResult;
18 | import com.google.firebase.auth.FirebaseAuth;
19 | import com.google.firebase.database.DatabaseReference;
20 | import com.google.firebase.database.FirebaseDatabase;
21 | import com.melardev.tutorialsfirebase.R;
22 |
23 | public class ActivityRegister extends AppCompatActivity {
24 |
25 | private EditText mNameField;
26 | private EditText mEmailFiedl;
27 | private EditText mPasswordField;
28 |
29 | private Button mRegisterButton;
30 |
31 | private FirebaseAuth mAuth;
32 | private ProgressDialog mProgress;
33 | private TextView mTextLogin;
34 | private FirebaseAuth.AuthStateListener mAuthListener;
35 |
36 | @Override
37 | protected void onStart() {
38 | super.onStart();
39 | mAuth.addAuthStateListener(mAuthListener);
40 | }
41 |
42 |
43 | @Override
44 | protected void onCreate(Bundle savedInstanceState) {
45 | super.onCreate(savedInstanceState);
46 | setContentView(R.layout.activity_register);
47 |
48 | mAuth = FirebaseAuth.getInstance();
49 | mNameField = (EditText) findViewById(R.id.etxt_name);
50 | mEmailFiedl = (EditText) findViewById(R.id.etxt_email);
51 | mPasswordField = (EditText) findViewById(R.id.etxt_password);
52 | mRegisterButton = (Button) findViewById(R.id.btn_register);
53 | mTextLogin = (TextView) findViewById(R.id.txt_login);
54 | mTextLogin.setOnClickListener(new View.OnClickListener() {
55 | @Override
56 | public void onClick(View v) {
57 | Intent intent = new Intent(ActivityRegister.this, ActivityLoginEmailPass.class);
58 | startActivity(intent);
59 | }
60 | });
61 |
62 | mProgress = new ProgressDialog(this);
63 | mRegisterButton.setOnClickListener(new View.OnClickListener() {
64 | @Override
65 | public void onClick(View view) {
66 | startRegister();
67 | }
68 | });
69 | mAuthListener = new FirebaseAuth.AuthStateListener() {
70 | @Override
71 | public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
72 | if (firebaseAuth.getCurrentUser() != null) {
73 | Intent intent = new Intent(ActivityRegister.this, ActivityLoginEmailPass.class);
74 | startActivity(intent);
75 | finish();
76 | }
77 | }
78 | };
79 |
80 | }
81 |
82 | private void startRegister() {
83 | final String name = mNameField.getText().toString().trim();
84 | final String email = mEmailFiedl.getText().toString().trim();
85 | final String password = mPasswordField.getText().toString().trim();
86 |
87 | if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(email) && !TextUtils.isEmpty(password)) {
88 | mProgress.setMessage("Registering, please wait...");
89 | mProgress.show();
90 | mAuth.createUserWithEmailAndPassword(email, password)
91 | .addOnCompleteListener(new OnCompleteListener() {
92 | @Override
93 | public void onComplete(@NonNull Task task) {
94 | mProgress.dismiss();
95 | if (task.isSuccessful()) {
96 | mAuth.signInWithEmailAndPassword(email, password);
97 | //Toast.makeText(ActivityRegister.this, user_id, Toast.LENGTH_SHORT).show();
98 |
99 | DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("users");
100 | DatabaseReference currentUserDB = mDatabase.child(mAuth.getCurrentUser().getUid());
101 | currentUserDB.child("name").setValue(name);
102 | currentUserDB.child("image").setValue("default");
103 | } else
104 | Toast.makeText(ActivityRegister.this, "error registering user", Toast.LENGTH_SHORT).show();
105 |
106 | }
107 | });
108 | }
109 |
110 | }
111 |
112 | }
113 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityGoogleLogin.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.content.Intent;
4 | import android.support.annotation.NonNull;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.os.Bundle;
7 | import android.util.Log;
8 | import android.view.View;
9 | import android.widget.Toast;
10 |
11 | import com.google.android.gms.auth.api.Auth;
12 | import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
13 | import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
14 | import com.google.android.gms.auth.api.signin.GoogleSignInResult;
15 | import com.google.android.gms.common.ConnectionResult;
16 | import com.google.android.gms.common.SignInButton;
17 | import com.google.android.gms.common.api.GoogleApiClient;
18 | import com.google.android.gms.tasks.OnCompleteListener;
19 | import com.google.android.gms.tasks.Task;
20 | import com.google.firebase.auth.AuthCredential;
21 | import com.google.firebase.auth.AuthResult;
22 | import com.google.firebase.auth.FirebaseAuth;
23 | import com.google.firebase.auth.GoogleAuthProvider;
24 | import com.melardev.tutorialsfirebase.R;
25 |
26 | public class ActivityGoogleLogin extends AppCompatActivity {
27 |
28 | private SignInButton googleBtn;
29 | private GoogleApiClient googleApiClient;
30 | private int CODE_GOOGLE_LOGIN = 0;
31 | private static final String TAG = "TAG";
32 | private FirebaseAuth mAuth;
33 |
34 | @Override
35 | protected void onCreate(Bundle savedInstanceState) {
36 |
37 | super.onCreate(savedInstanceState);
38 | setContentView(R.layout.activity_google_login);
39 |
40 | googleBtn = (SignInButton) findViewById(R.id.btn_sign_google);
41 | mAuth = FirebaseAuth.getInstance();
42 |
43 | GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
44 | // YOUR_API_KEY
45 | .requestIdToken(getResources().getString(R.string.web_client_id))
46 | .requestEmail()
47 | .build();
48 |
49 | googleApiClient = new GoogleApiClient.Builder(getApplicationContext())
50 | .enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
51 | @Override
52 | public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
53 | Toast.makeText(ActivityGoogleLogin.this, "You have an error", Toast.LENGTH_SHORT).show();
54 | }
55 | })
56 | .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
57 | .build();
58 |
59 | googleBtn.setOnClickListener(new View.OnClickListener() {
60 | @Override
61 | public void onClick(View view) {
62 | signIn();
63 | }
64 | });
65 |
66 | }
67 |
68 | private void signIn() {
69 | Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
70 | startActivityForResult(signInIntent, CODE_GOOGLE_LOGIN);
71 | }
72 |
73 | @Override
74 | public void onActivityResult(int requestCode, int resultCode, Intent data) {
75 | super.onActivityResult(requestCode, resultCode, data);
76 |
77 | if (requestCode == CODE_GOOGLE_LOGIN) {
78 | GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
79 | if (result.isSuccess()) {
80 | GoogleSignInAccount account = result.getSignInAccount();
81 | firebaseAuthWithGoogle(account);
82 | } else {
83 | Toast.makeText(this, "Login Failed " + result.getStatus().getStatusMessage(), Toast.LENGTH_SHORT).show();
84 |
85 | }
86 | }
87 | }
88 |
89 | private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
90 | Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
91 |
92 | AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
93 | mAuth.signInWithCredential(credential)
94 | .addOnCompleteListener(this, new OnCompleteListener() {
95 | @Override
96 | public void onComplete(@NonNull Task task) {
97 | Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
98 |
99 | if (!task.isSuccessful()) {
100 | Log.w(TAG, "signInWithCredential", task.getException());
101 | Toast.makeText(ActivityGoogleLogin.this, "Authentication failed.",
102 | Toast.LENGTH_SHORT).show();
103 | } else {
104 | startActivity(new Intent(ActivityGoogleLogin.this, ActivityGoogleLogged.class));
105 | Toast.makeText(ActivityGoogleLogin.this, "Logged Succesfully", Toast.LENGTH_SHORT).show();
106 | }
107 | }
108 | });
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityLoginFacebook.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.content.Intent;
4 | import android.support.annotation.NonNull;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.os.Bundle;
7 | import android.util.Log;
8 | import android.widget.Toast;
9 |
10 | import com.facebook.AccessToken;
11 | import com.facebook.CallbackManager;
12 | import com.facebook.FacebookCallback;
13 | import com.facebook.FacebookException;
14 | import com.facebook.FacebookSdk;
15 | import com.facebook.login.LoginManager;
16 | import com.facebook.login.LoginResult;
17 | import com.facebook.login.widget.LoginButton;
18 | import com.google.android.gms.tasks.OnCompleteListener;
19 | import com.google.android.gms.tasks.Task;
20 | import com.google.firebase.auth.AuthCredential;
21 | import com.google.firebase.auth.AuthResult;
22 | import com.google.firebase.auth.FacebookAuthProvider;
23 | import com.google.firebase.auth.FirebaseAuth;
24 | import com.google.firebase.auth.FirebaseUser;
25 | import com.melardev.tutorialsfirebase.R;
26 |
27 | public class ActivityLoginFacebook extends AppCompatActivity {
28 |
29 | private CallbackManager mCallbackManager;
30 | private FirebaseAuth mAuth;
31 | private FirebaseAuth.AuthStateListener mAuthListener;
32 |
33 | @Override
34 | protected void onCreate(Bundle savedInstanceState) {
35 | super.onCreate(savedInstanceState);
36 | FacebookSdk.sdkInitialize(getApplicationContext());
37 | //AppEventsLogger.activateApp(this);
38 | setContentView(R.layout.activity_login_facebook);
39 |
40 | if (getIntent().hasExtra("logout")) {
41 | LoginManager.getInstance().logOut();
42 | }
43 | mAuth = FirebaseAuth.getInstance();
44 | mCallbackManager = CallbackManager.Factory.create();
45 | LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
46 | loginButton.setReadPermissions("email", "public_profile");
47 | loginButton.registerCallback(mCallbackManager, new FacebookCallback() {
48 | @Override
49 | public void onSuccess(LoginResult loginResult) {
50 | handleFacebookAccessToken(loginResult.getAccessToken());
51 | Log.d("", "facebook:onSuccess:" + loginResult);
52 | }
53 |
54 | @Override
55 | public void onCancel() {
56 | Log.d("TAG", "facebook:onCancel");
57 | }
58 |
59 | @Override
60 | public void onError(FacebookException error) {
61 | Log.d("TAG", "facebook:onError", error);
62 | }
63 | });
64 |
65 | mAuthListener = new FirebaseAuth.AuthStateListener() {
66 | @Override
67 | public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
68 | FirebaseUser user = firebaseAuth.getCurrentUser();
69 | if (user != null) {
70 |
71 | Log.d("", "onAuthStateChanged:signed_in:" + user.getUid());
72 |
73 | Intent intent = new Intent(ActivityLoginFacebook.this, ActivityFacebookUser.class);
74 | String email = user.getEmail();
75 | String name = user.getDisplayName();
76 | startActivity(intent);
77 | finish();
78 | } else {
79 | Log.d("TG", "SIGNED OUT");
80 | }
81 | }
82 | };
83 | }
84 |
85 |
86 | @Override
87 | public void onStart() {
88 | super.onStart();
89 | mAuth.addAuthStateListener(mAuthListener);
90 | }
91 |
92 | @Override
93 | public void onStop() {
94 | super.onStop();
95 | if (mAuthListener != null) {
96 | mAuth.removeAuthStateListener(mAuthListener);
97 | }
98 | }
99 |
100 | private void handleFacebookAccessToken(AccessToken token) {
101 | Log.d("", "handleFacebookAccessToken:" + token);
102 |
103 | AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
104 | mAuth.signInWithCredential(credential)
105 | .addOnCompleteListener(this, new OnCompleteListener() {
106 | @Override
107 | public void onComplete(@NonNull Task task) {
108 | Log.d("", "signInWithCredential:onComplete:" + task.isSuccessful());
109 | if (!task.isSuccessful()) {
110 | Log.w("", "signInWithCredential", task.getException());
111 | Toast.makeText(ActivityLoginFacebook.this, "Authentication failed.",
112 | Toast.LENGTH_SHORT).show();
113 | }
114 |
115 | }
116 | });
117 | }
118 |
119 | @Override
120 | public void onActivityResult(int requestCode, int resultCode, Intent data) {
121 | super.onActivityResult(requestCode, resultCode, data);
122 | mCallbackManager.onActivityResult(requestCode,
123 | resultCode, data);
124 | }
125 | }
126 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityPhoneAuth.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.content.Intent;
4 | import android.support.annotation.NonNull;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.os.Bundle;
7 | import android.text.TextUtils;
8 | import android.view.View;
9 | import android.widget.EditText;
10 | import android.widget.Toast;
11 |
12 | import com.google.android.gms.tasks.OnCompleteListener;
13 | import com.google.android.gms.tasks.Task;
14 | import com.google.firebase.FirebaseException;
15 | import com.google.firebase.auth.AuthResult;
16 | import com.google.firebase.auth.FirebaseAuth;
17 | import com.google.firebase.auth.PhoneAuthCredential;
18 | import com.google.firebase.auth.PhoneAuthProvider;
19 | import com.melardev.tutorialsfirebase.R;
20 |
21 | import java.util.concurrent.TimeUnit;
22 |
23 | public class ActivityPhoneAuth extends AppCompatActivity {
24 |
25 | private EditText etxtPhone;
26 | private FirebaseAuth mAuth;
27 | private FirebaseAuth.AuthStateListener mAuthListener;
28 | private EditText etxtPhoneCode;
29 | private String mVerificationId;
30 |
31 | @Override
32 | protected void onStart() {
33 | super.onStart();
34 | mAuth.addAuthStateListener(mAuthListener);
35 | }
36 |
37 | @Override
38 | protected void onCreate(Bundle savedInstanceState) {
39 | super.onCreate(savedInstanceState);
40 | setContentView(R.layout.activity_phone_auth);
41 | //Note that this will not work on emulator, this requires a real device
42 | etxtPhone = (EditText) findViewById(R.id.etxtPhone);
43 | etxtPhoneCode = (EditText) findViewById(R.id.etxtPhoneCode);
44 | mAuth = FirebaseAuth.getInstance();
45 | mAuthListener = new FirebaseAuth.AuthStateListener() {
46 | @Override
47 | public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
48 | if (firebaseAuth.getCurrentUser() != null) {
49 | Toast.makeText(ActivityPhoneAuth.this, getString(R.string.now_logged_in) + firebaseAuth.getCurrentUser().getProviderId(), Toast.LENGTH_SHORT).show();
50 | Intent intent = new Intent(ActivityPhoneAuth.this, ActivityAccount.class);
51 | startActivity(intent);
52 | finish();
53 | }
54 | }
55 | };
56 | }
57 |
58 | public void requestCode(View view) {
59 | String phoneNumber = etxtPhone.getText().toString();
60 | if (TextUtils.isEmpty(phoneNumber))
61 | return;
62 | PhoneAuthProvider.getInstance().verifyPhoneNumber(
63 | phoneNumber, 60, TimeUnit.SECONDS, ActivityPhoneAuth.this, new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
64 | @Override
65 | public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
66 | //Called if it is not needed to enter verification code
67 | signInWithCredential(phoneAuthCredential);
68 | }
69 |
70 | @Override
71 | public void onVerificationFailed(FirebaseException e) {
72 | //incorrect phone number, verification code, emulator, etc.
73 | Toast.makeText(ActivityPhoneAuth.this, "onVerificationFailed " + e.getMessage(), Toast.LENGTH_SHORT).show();
74 | }
75 |
76 | @Override
77 | public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
78 | //now the code has been sent, save the verificationId we may need it
79 | super.onCodeSent(verificationId, forceResendingToken);
80 |
81 | mVerificationId = verificationId;
82 | }
83 |
84 | @Override
85 | public void onCodeAutoRetrievalTimeOut(String verificationId) {
86 | //called after timeout if onVerificationCompleted has not been called
87 | super.onCodeAutoRetrievalTimeOut(verificationId);
88 | Toast.makeText(ActivityPhoneAuth.this, "onCodeAutoRetrievalTimeOut :" + verificationId, Toast.LENGTH_SHORT).show();
89 | }
90 | }
91 | );
92 | }
93 |
94 | private void signInWithCredential(PhoneAuthCredential phoneAuthCredential) {
95 | mAuth.signInWithCredential(phoneAuthCredential)
96 | .addOnCompleteListener(this, new OnCompleteListener() {
97 | @Override
98 | public void onComplete(@NonNull Task task) {
99 | if (task.isSuccessful()) {
100 | Toast.makeText(ActivityPhoneAuth.this, R.string.signed_success, Toast.LENGTH_SHORT).show();
101 | } else {
102 | Toast.makeText(ActivityPhoneAuth.this, getString(R.string.sign_credential_fail) + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
103 | }
104 | }
105 | });
106 | }
107 |
108 | public void signIn(View view) {
109 | String code = etxtPhoneCode.getText().toString();
110 | if (TextUtils.isEmpty(code))
111 | return;
112 |
113 | signInWithCredential(PhoneAuthProvider.getCredential(mVerificationId, code));
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
24 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
50 |
51 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivitySort.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.content.Context;
4 | import android.content.Intent;
5 | import android.support.annotation.NonNull;
6 | import android.support.v7.app.AppCompatActivity;
7 | import android.os.Bundle;
8 | import android.support.v7.widget.LinearLayoutManager;
9 | import android.support.v7.widget.RecyclerView;
10 | import android.view.LayoutInflater;
11 | import android.view.View;
12 | import android.view.ViewGroup;
13 | import android.widget.ImageView;
14 | import android.widget.TextView;
15 | import android.widget.Toast;
16 |
17 | import com.google.firebase.auth.FirebaseAuth;
18 | import com.google.firebase.database.DataSnapshot;
19 | import com.google.firebase.database.DatabaseError;
20 | import com.google.firebase.database.DatabaseReference;
21 | import com.google.firebase.database.FirebaseDatabase;
22 | import com.google.firebase.database.ValueEventListener;
23 | import com.melardev.tutorialsfirebase.R;
24 | import com.squareup.picasso.Picasso;
25 |
26 | import java.util.ArrayList;
27 | import java.util.Iterator;
28 |
29 | public class ActivitySort extends AppCompatActivity {
30 |
31 | private DatabaseReference databasePost;
32 | private FirebaseAuth.AuthStateListener mAuthListener;
33 |
34 | private FirebaseAuth mAuth;
35 | private RecyclerView recyclerview;
36 | private DatabaseReference mDatabase;
37 |
38 | @Override
39 | protected void onStart() {
40 | super.onStart();
41 | mAuth.addAuthStateListener(mAuthListener);
42 | }
43 |
44 | @Override
45 | protected void onCreate(Bundle savedInstanceState) {
46 | super.onCreate(savedInstanceState);
47 | setContentView(R.layout.activity_sort);
48 |
49 | mAuth = FirebaseAuth.getInstance();
50 | recyclerview = (RecyclerView) findViewById(R.id.recyclerView);
51 | recyclerview.setLayoutManager(new LinearLayoutManager(this));
52 |
53 | mDatabase = FirebaseDatabase.getInstance().getReference();
54 | mAuthListener = new FirebaseAuth.AuthStateListener() {
55 | @Override
56 | public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
57 | if (firebaseAuth.getCurrentUser() == null) {
58 | Intent intent = new Intent(ActivitySort.this, ActivityLoginEmailPass.class);
59 | intent.putExtra("goToActivityUsers", true);
60 | startActivity(intent);
61 | finish();
62 | } else {
63 | getUsers();
64 | }
65 | }
66 | };
67 | }
68 |
69 | private static class UserDB {
70 | public String name, image;
71 |
72 | public UserDB(String name, String image) {
73 | this.name = name;
74 | this.image = image;
75 | }
76 | }
77 | private ArrayList entries;
78 | private void getUsers() {
79 | mDatabase.child("users").addValueEventListener(new ValueEventListener() {
80 | @Override
81 | public void onDataChange(DataSnapshot dataSnapshot) {
82 | Iterator items = dataSnapshot.getChildren().iterator();
83 | Toast.makeText(ActivitySort.this, "Total Users : " + dataSnapshot.getChildrenCount(), Toast.LENGTH_SHORT).show();
84 | entries.clear();
85 | while (items.hasNext()) {
86 | DataSnapshot item = items.next();
87 | String name, image;
88 | name = item.child("name").getValue().toString();
89 | image = item.child("image").getValue().toString();
90 | UserDB entry = new UserDB(name, image);
91 | entries.add(entry);
92 | }
93 |
94 | recyclerview.setAdapter(new RecUsersAdapter(ActivitySort.this, entries));
95 | recyclerview.getAdapter().notifyDataSetChanged();
96 | mDatabase.child("users").removeEventListener(this);
97 | }
98 |
99 | @Override
100 | public void onCancelled(DatabaseError databaseError) {
101 |
102 | }
103 | });
104 | }
105 |
106 | private class RecUsersAdapter extends RecyclerView.Adapter {
107 |
108 |
109 | private Context context;
110 | private ArrayList entries;
111 |
112 | public RecUsersAdapter(Context context, ArrayList entries) {
113 | this.context = context;
114 | this.entries = entries;
115 | }
116 |
117 | @Override
118 | public RecUsersAdapter.RecViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
119 | View v = LayoutInflater.from(context).inflate(R.layout.user_row, null);
120 | return new RecUsersAdapter.RecViewHolder(v);
121 | }
122 |
123 | @Override
124 | public void onBindViewHolder(RecUsersAdapter.RecViewHolder holder, int position) {
125 | UserDB user = entries.get(position);
126 | if (!user.image.equals("default"))
127 | Picasso.with(context).load(user.image).into(holder.imageView);
128 | holder.textView.setText(user.name);
129 | }
130 |
131 |
132 | @Override
133 | public int getItemCount() {
134 | return entries.size();
135 | }
136 |
137 | public class RecViewHolder extends RecyclerView.ViewHolder {
138 |
139 | public ImageView imageView;
140 | public TextView textView;
141 |
142 | public RecViewHolder(View itemView) {
143 | super(itemView);
144 |
145 | imageView = (ImageView) itemView.findViewById(R.id.imageUser);
146 | textView = (TextView) itemView.findViewById(R.id.txtUser);
147 | }
148 | }
149 | }
150 | }
151 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityDownloadFile.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.net.Uri;
4 | import android.support.annotation.NonNull;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.os.Bundle;
7 |
8 | import com.bumptech.glide.Glide;
9 | import com.firebase.ui.storage.images.FirebaseImageLoader;
10 | import com.google.android.gms.tasks.OnFailureListener;
11 | import com.google.android.gms.tasks.OnSuccessListener;
12 | import com.google.firebase.storage.FileDownloadTask;
13 | import com.google.firebase.storage.FirebaseStorage;
14 | import com.google.firebase.storage.StorageReference;
15 |
16 | import java.io.File;
17 | import java.io.IOException;
18 | import java.util.List;
19 |
20 | public class ActivityDownloadFile extends AppCompatActivity {
21 | /*
22 | @Override
23 | protected void onCreate(Bundle savedInstanceState) {
24 | super.onCreate(savedInstanceState);
25 | setContentView(R.layout.activity_download_file);
26 |
27 | FirebaseStorage mStorage = FirebaseStorage.getInstance();
28 | // Create a storage reference from our app
29 | StorageReference storageRef = mStorage.getReferenceFromUrl("gs://");
30 |
31 | // Create a reference with an initial file path and name
32 | StorageReference pathReference = storageRef.child("images/stars.jpg");
33 |
34 | // Create a reference to a file from a Google Cloud Storage URI
35 | StorageReference gsReference = mStorage.getReferenceFromUrl("gs://bucket/images/stars.jpg");
36 |
37 | // Create a reference from an HTTPS URL
38 | // Note that in the URL, characters are URL escaped!
39 | StorageReference httpsReference = mStorage.getReferenceFromUrl("https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg");
40 |
41 |
42 | StorageReference islandRef = storageRef.child("images/island.jpg");
43 |
44 | final long ONE_MEGABYTE = 1024 * 1024;
45 | islandRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener() {
46 | @Override
47 | public void onSuccess(byte[] bytes) {
48 | // Data for "images/island.jpg" is returns, use this as needed
49 | }
50 | }).addOnFailureListener(new OnFailureListener() {
51 | @Override
52 | public void onFailure(@NonNull Exception exception) {
53 | // Handle any errors
54 | }
55 | });
56 |
57 | islandRef = storageRef.child("images/island.jpg");
58 |
59 | File localFile = null;
60 | try {
61 | localFile = File.createTempFile("images", "jpg");
62 | } catch (IOException e) {
63 | e.printStackTrace();
64 | }
65 |
66 | islandRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener() {
67 | @Override
68 | public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
69 | // Local temp file has been created
70 | }
71 | }).addOnFailureListener(new OnFailureListener() {
72 | @Override
73 | public void onFailure(@NonNull Exception exception) {
74 | // Handle any errors
75 | }
76 | });
77 |
78 | storageRef.child("users/me/profile.png").getDownloadUrl().addOnSuccessListener(new OnSuccessListener() {
79 | @Override
80 | public void onSuccess(Uri uri) {
81 | // Got the download URL for 'users/me/profile.png'
82 | }
83 | }).addOnFailureListener(new OnFailureListener() {
84 | @Override
85 | public void onFailure(@NonNull Exception exception) {
86 | // Handle any errors
87 | }
88 | });
89 |
90 |
91 | Glide.with(this)
92 | .using(new FirebaseImageLoader())
93 | .load(storageRef)
94 | .into(imageView);
95 |
96 | StorageReference mStorageRef; //mStorageRef was previously used to transfer data.
97 |
98 |
99 | storageRef.child("users/me/profile.png").getBytes(Long.MAX_VALUE).addOnSuccessListener(new OnSuccessListener() {
100 | @Override
101 | public void onSuccess(byte[] bytes) {
102 |
103 | }
104 | }).addOnFailureListener(new OnFailureListener() {
105 | @Override
106 | public void onFailure(@NonNull Exception exception) {
107 |
108 | }
109 | });
110 | }
111 | @Override
112 | protected void onSaveInstanceState(Bundle outState) {
113 | super.onSaveInstanceState(outState);
114 |
115 | // If there's a download in progress, save the reference so you can query it later
116 | if (mStorageRef != null) {
117 | outState.putString("reference", mStorageRef.toString());
118 | }
119 | }
120 |
121 | @Override
122 | protected void onRestoreInstanceState(Bundle savedInstanceState) {
123 | super.onRestoreInstanceState(savedInstanceState);
124 |
125 | // If there was a download in progress, get its reference and create a new StorageReference
126 | final String stringRef = savedInstanceState.getString("reference");
127 | if (stringRef == null) {
128 | return;
129 | }
130 | mStorageRef = FirebaseStorage.getInstance().getReferenceFromUrl(stringRef);
131 |
132 | // Find all DownloadTasks under this StorageReference (in this example, there should be one)
133 | List tasks = mStorageRef.getActiveDownloadTasks();
134 | if (tasks.size() > 0) {
135 | // Get the task monitoring the download
136 | DownloadTask task = tasks.get(0);
137 |
138 | // Add new listeners to the task using an Activity scope
139 | task.addOnSuccessListener(this, new OnSuccessListener() {
140 | @Override
141 | public void onSuccess(DownloadTask.TaskSnapshot state) {
142 | handleSuccess(state); //call a user defined function to handle the event.
143 | }
144 | });
145 | }
146 | }
147 | */
148 | }
149 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityUsers.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.content.Context;
4 | import android.content.Intent;
5 | import android.support.annotation.NonNull;
6 | import android.support.v7.app.AppCompatActivity;
7 | import android.os.Bundle;
8 | import android.support.v7.widget.LinearLayoutManager;
9 | import android.support.v7.widget.RecyclerView;
10 | import android.view.LayoutInflater;
11 | import android.view.View;
12 | import android.view.ViewGroup;
13 | import android.widget.ImageView;
14 | import android.widget.TextView;
15 | import android.widget.Toast;
16 |
17 | import com.google.firebase.auth.FirebaseAuth;
18 | import com.google.firebase.database.DataSnapshot;
19 | import com.google.firebase.database.DatabaseError;
20 | import com.google.firebase.database.DatabaseReference;
21 | import com.google.firebase.database.FirebaseDatabase;
22 | import com.google.firebase.database.ValueEventListener;
23 | import com.melardev.tutorialsfirebase.R;
24 | import com.squareup.picasso.Picasso;
25 |
26 | import java.util.ArrayList;
27 | import java.util.Iterator;
28 |
29 | public class ActivityUsers extends AppCompatActivity {
30 |
31 | private RecyclerView recyclerview;
32 | private FirebaseAuth mAuth;
33 | private FirebaseAuth.AuthStateListener mAuthListener;
34 | private DatabaseReference mDatabase;
35 | ArrayList entries = new ArrayList<>();
36 |
37 | @Override
38 | protected void onStart() {
39 | super.onStart();
40 | mAuth.addAuthStateListener(mAuthListener);
41 | }
42 |
43 | @Override
44 | protected void onCreate(Bundle savedInstanceState) {
45 | super.onCreate(savedInstanceState);
46 | setContentView(R.layout.activity_users);
47 | mAuth = FirebaseAuth.getInstance();
48 | recyclerview = (RecyclerView) findViewById(R.id.recyclerView);
49 | recyclerview.setLayoutManager(new LinearLayoutManager(this));
50 |
51 | mDatabase = FirebaseDatabase.getInstance().getReference();
52 | mAuthListener = new FirebaseAuth.AuthStateListener() {
53 | @Override
54 | public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
55 | if (firebaseAuth.getCurrentUser() == null) {
56 | Intent intent = new Intent(ActivityUsers.this, ActivityLoginEmailPass.class);
57 | intent.putExtra("goToActivityUsers", true);
58 | startActivity(intent);
59 | finish();
60 | } else {
61 | getUsers();
62 | }
63 | }
64 | };
65 | }
66 |
67 |
68 | private static class UserDB {
69 | public String name, image;
70 |
71 | public UserDB(String name, String image) {
72 | this.name = name;
73 | this.image = image;
74 | }
75 | }
76 |
77 | private void getUsers() {
78 |
79 | //mDatabase.child("users").limitToFirst(2).addValueEventListener(new ValueEventListener() {
80 | //mDatabase.child("users").orderByChild("name").addValueEventListener(new ValueEventListener() {
81 | mDatabase.child("users").orderByChild("name").equalTo("melardev").addValueEventListener(
82 | new ValueEventListener() {
83 | //mDatabase.child("users").addValueEventListener(new ValueEventListener() {
84 | @Override
85 | public void onDataChange(DataSnapshot dataSnapshot) {
86 | Iterator items = dataSnapshot.getChildren().iterator();
87 | Toast.makeText(ActivityUsers.this, "Total Users : " + dataSnapshot.getChildrenCount(), Toast.LENGTH_SHORT).show();
88 | entries.clear();
89 | while (items.hasNext()) {
90 | DataSnapshot item = items.next();
91 |
92 | String name, image;
93 | name = item.child("name").getValue().toString();
94 | image = item.child("image").getValue().toString();
95 | UserDB entry = new UserDB(name, image);
96 | entries.add(entry);
97 | }
98 |
99 | recyclerview.setAdapter(new RecUsersAdapter(ActivityUsers.this, entries));
100 | recyclerview.getAdapter().notifyDataSetChanged();
101 | mDatabase.child("users").removeEventListener(this);
102 | }
103 |
104 | @Override
105 | public void onCancelled(DatabaseError databaseError) {
106 |
107 | }
108 | }
109 |
110 | );
111 | }
112 |
113 | private class RecUsersAdapter extends RecyclerView.Adapter {
114 |
115 |
116 | private Context context;
117 | private ArrayList entries;
118 |
119 | public RecUsersAdapter(Context context, ArrayList entries) {
120 | this.context = context;
121 | this.entries = entries;
122 | }
123 |
124 | @Override
125 | public RecUsersAdapter.RecViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
126 | View v = LayoutInflater.from(context).inflate(R.layout.user_row, null);
127 | return new RecViewHolder(v);
128 | }
129 |
130 | @Override
131 | public void onBindViewHolder(RecViewHolder holder, int position) {
132 | UserDB user = entries.get(position);
133 | if (!user.image.equals("default"))
134 | Picasso.with(context).load(user.image).into(holder.imageView);
135 | holder.textView.setText(user.name);
136 | }
137 |
138 |
139 | @Override
140 | public int getItemCount() {
141 | return entries.size();
142 | }
143 |
144 | public class RecViewHolder extends RecyclerView.ViewHolder {
145 |
146 | public ImageView imageView;
147 | public TextView textView;
148 |
149 | public RecViewHolder(View itemView) {
150 | super(itemView);
151 |
152 | imageView = (ImageView) itemView.findViewById(R.id.imageUser);
153 | textView = (TextView) itemView.findViewById(R.id.txtUser);
154 | }
155 | }
156 | }
157 | }
158 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityDynamicLink.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.content.Intent;
4 | import android.net.Uri;
5 | import android.support.annotation.NonNull;
6 | import android.support.v7.app.AppCompatActivity;
7 | import android.os.Bundle;
8 | import android.text.TextUtils;
9 | import android.util.Log;
10 | import android.view.View;
11 | import android.widget.TextView;
12 | import android.widget.Toast;
13 |
14 | import com.google.android.gms.tasks.OnCompleteListener;
15 | import com.google.android.gms.tasks.OnFailureListener;
16 | import com.google.android.gms.tasks.OnSuccessListener;
17 | import com.google.android.gms.tasks.Task;
18 | import com.google.firebase.analytics.FirebaseAnalytics;
19 | import com.google.firebase.appinvite.FirebaseAppInvite;
20 | import com.google.firebase.dynamiclinks.DynamicLink;
21 | import com.google.firebase.dynamiclinks.FirebaseDynamicLinks;
22 | import com.google.firebase.dynamiclinks.PendingDynamicLinkData;
23 | import com.google.firebase.dynamiclinks.ShortDynamicLink;
24 | import com.melardev.tutorialsfirebase.R;
25 |
26 | public class ActivityDynamicLink extends AppCompatActivity {
27 |
28 | private final String TAG = getClass().getName();
29 | private FirebaseAnalytics analytics;
30 | private TextView txtResult;
31 |
32 | @Override
33 | protected void onCreate(Bundle savedInstanceState) {
34 | super.onCreate(savedInstanceState);
35 | setContentView(R.layout.activity_dynamic_link);
36 |
37 | txtResult = (TextView) findViewById(R.id.txtDynamicLinkResult);
38 | FirebaseDynamicLinks.getInstance()
39 | .getDynamicLink(getIntent())
40 | .addOnSuccessListener(this, new OnSuccessListener() {
41 | @Override
42 | public void onSuccess(PendingDynamicLinkData pendingDynamicLinkData) {
43 | if (pendingDynamicLinkData != null) {
44 | //init analytics if you want to get analytics from your dynamic links
45 | analytics = FirebaseAnalytics.getInstance(ActivityDynamicLink.this);
46 |
47 | Uri deepLink = pendingDynamicLinkData.getLink();
48 | txtResult.append("\nonSuccess called " + deepLink.toString());
49 | //logic here, redeem code or whatever
50 |
51 | FirebaseAppInvite invite = FirebaseAppInvite.getInvitation(pendingDynamicLinkData);
52 | if (invite != null) {
53 | String invitationId = invite.getInvitationId();
54 | if (!TextUtils.isEmpty(invitationId))
55 | txtResult.append("\ninvitation Id " + invitationId);
56 | }
57 | }
58 | }
59 | })
60 | .addOnFailureListener(this, new OnFailureListener() {
61 | @Override
62 | public void onFailure(@NonNull Exception e) {
63 | txtResult.append("\nonFailure");
64 | }
65 | });
66 | }
67 |
68 | public void shareLongDynamicLink(View view) {
69 | Intent intent = new Intent();
70 | String msg = "visit my awesome website: " + buildDynamicLink();
71 | intent.setAction(Intent.ACTION_SEND);
72 | intent.putExtra(Intent.EXTRA_TEXT, msg);
73 | intent.setType("text/plain");
74 | startActivity(intent);
75 | }
76 |
77 | private String buildDynamicLink(/*String link, String description, String titleSocial, String source*/) {
78 | //more info at https://firebase.google.com/docs/dynamic-links/create-manually
79 |
80 | /*String path = FirebaseDynamicLinks.getInstance().createDynamicLink()
81 | .setDynamicLinkDomain("m9guj.app.goo.gl")
82 | .setLink(Uri.parse("https://youtube.com/c/Melardev"))
83 | .setAndroidParameters(new DynamicLink.AndroidParameters.Builder().build()) //com.melardev.tutorialsfirebase
84 | .setSocialMetaTagParameters(new DynamicLink.SocialMetaTagParameters.Builder().setTitle("Share this App").setDescription("blabla").build())
85 | .setGoogleAnalyticsParameters(new DynamicLink.GoogleAnalyticsParameters.Builder().setSource("AndroidApp").build())
86 | .buildDynamicLink().getUri().toString();*/
87 |
88 | return "https://m9guj.app.goo.gl/?" +
89 | "link=" + /*link*/
90 | "https://youtube.com/c/Melardev" +
91 | "&apn=" + /*getPackageName()*/
92 | "com.melardev.tutorialsfirebase" +
93 | "&st=" + /*titleSocial*/
94 | "Share+this+App" +
95 | "&sd=" + /*description*/
96 | "looking+to+learn+how+to+use+Firebase+in+Android?+this+app+is+what+you+are+looking+for." +
97 | "&utm_source=" + /*source*/
98 | "AndroidApp";
99 | }
100 |
101 | public void shareShortDynamicLink(View view) {
102 | Task createLinkTask = FirebaseDynamicLinks.getInstance().createDynamicLink()
103 | .setLongLink(Uri.parse(buildDynamicLink()))
104 | .buildShortDynamicLink()
105 | .addOnCompleteListener(this, new OnCompleteListener() {
106 | @Override
107 | public void onComplete(@NonNull Task task) {
108 | if (task.isSuccessful()) {
109 | // Short link created
110 | Uri shortLink = task.getResult().getShortLink();
111 | Uri flowchartLink = task.getResult().getPreviewLink(); //flowchart link is a debugging URL
112 |
113 | Log.d(TAG, shortLink.toString());
114 | Log.d(TAG, flowchartLink.toString());
115 | Intent intent = new Intent();
116 | String msg = "visit my awesome website: " + shortLink.toString();
117 | intent.setAction(Intent.ACTION_SEND);
118 | intent.putExtra(Intent.EXTRA_TEXT, msg);
119 | intent.setType("text/plain");
120 | startActivity(intent);
121 |
122 | } else {
123 | // Error
124 | txtResult.append("\nError building short link");
125 | }
126 | }
127 | });
128 | }
129 | }
130 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityTwitterAuth.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.content.Intent;
4 | import android.support.annotation.NonNull;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.os.Bundle;
7 | import android.view.View;
8 | import android.widget.Button;
9 | import android.widget.ImageView;
10 | import android.widget.TextView;
11 | import android.widget.Toast;
12 |
13 | import com.google.android.gms.tasks.OnCompleteListener;
14 | import com.google.android.gms.tasks.Task;
15 | import com.google.firebase.auth.AuthCredential;
16 | import com.google.firebase.auth.AuthResult;
17 | import com.google.firebase.auth.FirebaseAuth;
18 | import com.google.firebase.auth.FirebaseUser;
19 | import com.google.firebase.auth.TwitterAuthProvider;
20 | import com.melardev.tutorialsfirebase.R;
21 | import com.squareup.picasso.Picasso;
22 | import com.twitter.sdk.android.core.Callback;
23 | import com.twitter.sdk.android.core.Result;
24 | import com.twitter.sdk.android.core.SessionManager;
25 | import com.twitter.sdk.android.core.Twitter;
26 | import com.twitter.sdk.android.core.TwitterAuthConfig;
27 | import com.twitter.sdk.android.core.TwitterConfig;
28 | import com.twitter.sdk.android.core.TwitterCore;
29 | import com.twitter.sdk.android.core.TwitterException;
30 | import com.twitter.sdk.android.core.TwitterSession;
31 | import com.twitter.sdk.android.core.identity.TwitterLoginButton;
32 |
33 | public class ActivityTwitterAuth extends AppCompatActivity {
34 |
35 | private static final String TAG = "";
36 | private TwitterLoginButton btnTwitter;
37 | private FirebaseAuth mAuth;
38 | private FirebaseAuth.AuthStateListener mAuthListener;
39 | private TextView txtTwitter;
40 | private ImageView imgTwitter;
41 | private Button btnSignOut;
42 |
43 |
44 | @Override
45 | public void onCreate(Bundle savedInstanceState) {
46 | super.onCreate(savedInstanceState);
47 | // https://dev.twitter.com/twitterkit/android/overview
48 | // Configure Twitter SDK
49 | TwitterAuthConfig authConfig = new TwitterAuthConfig(
50 | getString(R.string.consumer_key),
51 | getString(R.string.consumer_secret));
52 | TwitterConfig twitterConfig = new TwitterConfig.Builder(this)
53 | .twitterAuthConfig(authConfig)
54 | .build();
55 |
56 | Twitter.initialize(twitterConfig);
57 |
58 | setContentView(R.layout.activity_twitter_auth);
59 |
60 | txtTwitter = (TextView) findViewById(R.id.txtTwitter);
61 | imgTwitter = (ImageView) findViewById(R.id.img_twitter);
62 | btnTwitter = (TwitterLoginButton) findViewById(R.id.twitter_login_button);
63 | btnSignOut = (Button) findViewById(R.id.btn_twitter_signout);
64 |
65 | updateButtons();
66 | btnSignOut.setOnClickListener(new View.OnClickListener() {
67 | @Override
68 | public void onClick(View v) {
69 | //https://stackoverflow.com/a/35350301/6393636
70 | SessionManager sessionManager = TwitterCore.getInstance().getSessionManager();
71 | if (sessionManager.getActiveSession() != null) {
72 | sessionManager.clearActiveSession();
73 | mAuth.signOut();
74 | updateButtons();
75 | }
76 | }
77 | });
78 |
79 | btnTwitter.setCallback(new Callback() {
80 | @Override
81 | public void success(Result result) {
82 | Toast.makeText(ActivityTwitterAuth.this, "Signed in to twitter succesfully " + result.data, Toast.LENGTH_SHORT).show();
83 | signToFirebaseWithTwitterSession(result.data);
84 | updateButtons();
85 | }
86 |
87 | @Override
88 | public void failure(TwitterException exception) {
89 | Toast.makeText(ActivityTwitterAuth.this, "Failure to login to Twitter", Toast.LENGTH_SHORT).show();
90 | }
91 | });
92 |
93 | mAuth = FirebaseAuth.getInstance();
94 | mAuthListener = new FirebaseAuth.AuthStateListener() {
95 | @Override
96 | public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
97 | FirebaseUser user = firebaseAuth.getCurrentUser();
98 | if (user != null) {
99 | Toast.makeText(ActivityTwitterAuth.this, "signed in", Toast.LENGTH_SHORT).show();
100 | txtTwitter.setText(user.getDisplayName());
101 | Picasso.with(ActivityTwitterAuth.this).load(user.getPhotoUrl()).into(imgTwitter);
102 | } else {
103 | Toast.makeText(ActivityTwitterAuth.this, "signed out from Firebase", Toast.LENGTH_SHORT).show();
104 | txtTwitter.setText("");
105 | imgTwitter.setImageBitmap(null);
106 | }
107 | // ...
108 | }
109 | };
110 | }
111 |
112 | private void updateButtons() {
113 | if (TwitterCore.getInstance().getSessionManager().getActiveSession() == null) {
114 | btnTwitter.setVisibility(View.VISIBLE);
115 | btnSignOut.setVisibility(View.GONE);
116 | } else {
117 | btnSignOut.setVisibility(View.VISIBLE);
118 | btnTwitter.setVisibility(View.GONE);
119 | }
120 | }
121 |
122 | @Override
123 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
124 | super.onActivityResult(requestCode, resultCode, data);
125 |
126 | btnTwitter.onActivityResult(requestCode, resultCode, data);
127 | }
128 |
129 | @Override
130 | public void onStart() {
131 | super.onStart();
132 | mAuth.addAuthStateListener(mAuthListener);
133 | }
134 |
135 | @Override
136 | protected void onDestroy() {
137 | super.onDestroy();
138 | mAuth.removeAuthStateListener(mAuthListener);
139 | }
140 |
141 | private void signToFirebaseWithTwitterSession(TwitterSession session) {
142 | AuthCredential credential = TwitterAuthProvider.getCredential(session.getAuthToken().token,
143 | session.getAuthToken().secret);
144 |
145 | mAuth.signInWithCredential(credential)
146 | .addOnCompleteListener(this, new OnCompleteListener() {
147 | @Override
148 | public void onComplete(@NonNull Task task) {
149 | Toast.makeText(ActivityTwitterAuth.this,
150 | R.string.login_ok_twitter, Toast.LENGTH_SHORT).show();
151 |
152 | if (!task.isSuccessful()) {
153 | Toast.makeText(ActivityTwitterAuth.this, "Authentication failed.",
154 | Toast.LENGTH_SHORT).show();
155 | }
156 | }
157 | });
158 | }
159 | }
160 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
14 |
15 |
19 |
20 |
26 |
27 |
33 |
34 |
40 |
41 |
47 |
48 |
54 |
55 |
61 |
62 |
68 |
69 |
75 |
76 |
82 |
83 |
89 |
90 |
96 |
97 |
103 |
104 |
109 |
110 |
116 |
117 |
123 |
124 |
129 |
130 |
131 |
137 |
138 |
144 |
145 |
151 |
152 |
158 |
159 |
165 |
166 |
167 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityUpdateUser.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.content.Intent;
4 | import android.net.Uri;
5 | import android.support.annotation.NonNull;
6 | import android.support.v7.app.AppCompatActivity;
7 | import android.os.Bundle;
8 | import android.text.TextUtils;
9 | import android.view.View;
10 | import android.widget.EditText;
11 | import android.widget.Toast;
12 |
13 | import com.google.android.gms.tasks.OnCompleteListener;
14 | import com.google.android.gms.tasks.Task;
15 | import com.google.firebase.auth.FirebaseAuth;
16 | import com.google.firebase.auth.FirebaseUser;
17 | import com.google.firebase.auth.UserInfo;
18 | import com.google.firebase.auth.UserProfileChangeRequest;
19 | import com.melardev.tutorialsfirebase.R;
20 |
21 | public class ActivityUpdateUser extends AppCompatActivity {
22 |
23 | private static final String TAG = "";
24 | FirebaseAuth mAuth;
25 | private FirebaseAuth.AuthStateListener mAuthListener;
26 | private EditText etxtNewEmail;
27 | private EditText etxtNewPassword;
28 | private EditText etxtNewName;
29 |
30 | @Override
31 | protected void onStart() {
32 | super.onStart();
33 | mAuth.addAuthStateListener(mAuthListener);
34 | }
35 |
36 | @Override
37 | protected void onCreate(Bundle savedInstanceState) {
38 | super.onCreate(savedInstanceState);
39 | setContentView(R.layout.activity_update_user);
40 |
41 | etxtNewName = (EditText) findViewById(R.id.etxtNewName);
42 | etxtNewEmail = (EditText) findViewById(R.id.etxtNewEmail);
43 | etxtNewPassword = (EditText) findViewById(R.id.etxtNewPassword);
44 |
45 | mAuth = FirebaseAuth.getInstance();
46 |
47 | mAuthListener = new FirebaseAuth.AuthStateListener() {
48 | @Override
49 | public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
50 | FirebaseUser user = firebaseAuth.getCurrentUser();
51 | if (user == null) {
52 | Intent intent = new Intent(ActivityUpdateUser.this, ActivityLoginEmailPass.class);
53 | intent.putExtra("goToActivityUsers", true);
54 | startActivity(intent);
55 | finish();
56 | } else {
57 | etxtNewName.setText(user.getDisplayName());
58 | etxtNewEmail.setText(user.getEmail());
59 | }
60 | }
61 | };
62 | }
63 |
64 | public void sendPasswordResetEmail(View view) {
65 | String emailAddress = "melardev_email@email.com";
66 | mAuth.sendPasswordResetEmail(emailAddress).addOnCompleteListener(new OnCompleteListener() {
67 | @Override
68 | public void onComplete(@NonNull Task task) {
69 | if (task.isSuccessful()) {
70 | Toast.makeText(ActivityUpdateUser.this, "password reset email sent", Toast.LENGTH_SHORT).show();
71 | }
72 | }
73 | });
74 | }
75 |
76 | public void getUserProviderProfileInfo(View view) {
77 | FirebaseUser user = mAuth.getCurrentUser();
78 | if (user != null) {
79 | for (UserInfo profile : user.getProviderData()) {
80 | // Id of the provider (ex: google.com)
81 | String providerId = profile.getProviderId();
82 |
83 | // UID specific to the provider
84 | String uid = profile.getUid();
85 |
86 | // Name, email address, and profile photo Url
87 | String name = profile.getDisplayName();
88 | String email = profile.getEmail();
89 | Uri photoUrl = profile.getPhotoUrl();
90 |
91 | Toast.makeText(this, "id : " + providerId + ", uid : " + uid + " name: " + name
92 | + " email : " + email + " " + photoUrl, Toast.LENGTH_SHORT).show();
93 | };
94 | }
95 | }
96 |
97 | public void updateUserProfile(View view) {
98 | FirebaseUser user = mAuth.getCurrentUser();
99 |
100 | String newName = etxtNewName.getText().toString();
101 | if (TextUtils.isEmpty(newName))
102 | return;
103 |
104 | UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
105 | .setDisplayName(newName)
106 | //.setPhotoUri(Uri.parse("https://www.famouslogos.net/images/android-logo.jpg"))
107 | .build();
108 |
109 | user.updateProfile(profileUpdates)
110 | .addOnCompleteListener(new OnCompleteListener() {
111 | @Override
112 | public void onComplete(@NonNull Task task) {
113 | if (task.isSuccessful()) {
114 | Toast.makeText(ActivityUpdateUser.this, "User updated", Toast.LENGTH_SHORT).show();
115 | }
116 | }
117 | });
118 | }
119 |
120 | public void setUserEmailAddr(View view) {
121 | String newEmail = etxtNewEmail.getText().toString();
122 | if (TextUtils.isEmpty(newEmail))
123 | return;
124 |
125 | FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
126 |
127 | user.updateEmail(newEmail).addOnCompleteListener(new OnCompleteListener() {
128 | @Override
129 | public void onComplete(@NonNull Task task) {
130 | if (task.isSuccessful())
131 | Toast.makeText(ActivityUpdateUser.this, "email updated", Toast.LENGTH_SHORT).show();
132 |
133 | }
134 | });
135 | }
136 |
137 | public void setUserPassword(View view) {
138 | FirebaseUser user = mAuth.getCurrentUser();
139 | String newPassword = etxtNewPassword.getText().toString();
140 | if (TextUtils.isEmpty(newPassword))
141 | return;
142 |
143 | user.updatePassword(newPassword)
144 | .addOnCompleteListener(new OnCompleteListener() {
145 | @Override
146 | public void onComplete(@NonNull Task task) {
147 | if (task.isSuccessful())
148 | Toast.makeText(ActivityUpdateUser.this, "password updated", Toast.LENGTH_SHORT).show();
149 | }
150 | });
151 | }
152 |
153 | public void userVerification(View view) {
154 | FirebaseUser user = mAuth.getCurrentUser();
155 |
156 | user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener() {
157 | @Override
158 | public void onComplete(@NonNull Task task) {
159 | if (task.isSuccessful()) {
160 | Toast.makeText(ActivityUpdateUser.this, "Email sent", Toast.LENGTH_SHORT).show();
161 | }
162 | }
163 | });
164 | }
165 |
166 | public void deleteUser(View view) {
167 | FirebaseUser user = mAuth.getCurrentUser();
168 | user.delete().addOnCompleteListener(new OnCompleteListener() {
169 | @Override
170 | public void onComplete(@NonNull Task task) {
171 | if (task.isSuccessful())
172 | Toast.makeText(ActivityUpdateUser.this, "User deleted", Toast.LENGTH_SHORT).show();
173 | }
174 | });
175 | }
176 |
177 | public void signOut(View view) {
178 | mAuth.signOut();
179 | }
180 | }
181 |
--------------------------------------------------------------------------------
/app/src/main/java/com/melardev/tutorialsfirebase/activities/ActivityDBRetriever.java:
--------------------------------------------------------------------------------
1 | package com.melardev.tutorialsfirebase.activities;
2 |
3 | import android.content.Context;
4 | import android.content.Intent;
5 | import android.support.annotation.NonNull;
6 | import android.support.v7.app.AppCompatActivity;
7 | import android.os.Bundle;
8 | import android.support.v7.widget.LinearLayoutManager;
9 | import android.support.v7.widget.RecyclerView;
10 | import android.view.LayoutInflater;
11 | import android.view.View;
12 | import android.view.ViewGroup;
13 | import android.widget.ImageView;
14 | import android.widget.TextView;
15 | import android.widget.Toast;
16 |
17 | import com.google.firebase.auth.FirebaseAuth;
18 | import com.google.firebase.database.DataSnapshot;
19 | import com.google.firebase.database.DatabaseError;
20 | import com.google.firebase.database.DatabaseReference;
21 | import com.google.firebase.database.FirebaseDatabase;
22 | import com.google.firebase.database.ValueEventListener;
23 | import com.melardev.tutorialsfirebase.R;
24 | import com.melardev.tutorialsfirebase.model.User;
25 | import com.squareup.picasso.Picasso;
26 |
27 | import java.util.ArrayList;
28 | import java.util.HashMap;
29 | import java.util.Iterator;
30 |
31 | public class ActivityDBRetriever extends AppCompatActivity {
32 |
33 | private RecyclerView recyclerview;
34 | private FirebaseAuth mAuth;
35 | private FirebaseAuth.AuthStateListener mAuthListener;
36 | private DatabaseReference mDatabase;
37 | ArrayList entries = new ArrayList<>();
38 |
39 | @Override
40 | protected void onStart() {
41 | super.onStart();
42 | mAuth.addAuthStateListener(mAuthListener);
43 | }
44 |
45 | @Override
46 | protected void onCreate(Bundle savedInstanceState) {
47 | super.onCreate(savedInstanceState);
48 | setContentView(R.layout.activity_dbretriever);
49 |
50 | mAuth = FirebaseAuth.getInstance();
51 | recyclerview = (RecyclerView) findViewById(R.id.recyclerView);
52 | recyclerview.setLayoutManager(new LinearLayoutManager(this));
53 |
54 | mDatabase = FirebaseDatabase.getInstance().getReference();
55 | mAuthListener = new FirebaseAuth.AuthStateListener() {
56 | @Override
57 | public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
58 | if (firebaseAuth.getCurrentUser() == null) {
59 | Intent intent = new Intent(ActivityDBRetriever.this, ActivityLoginEmailPass.class);
60 | intent.putExtra("goToActivityUsers", true);
61 | startActivity(intent);
62 | finish();
63 | }
64 | }
65 | };
66 | }
67 |
68 |
69 | private void getUsersObjects() {
70 |
71 | //mDatabase.child("users").limitToFirst(2).addValueEventListener(new ValueEventListener() {
72 | //mDatabase.child("users").orderByChild("name").addValueEventListener(new ValueEventListener() {
73 | mDatabase.child("users")
74 | .addValueEventListener(new ValueEventListener() {
75 | //mDatabase.child("users").addValueEventListener(new ValueEventListener() {
76 | @Override
77 | public void onDataChange(DataSnapshot dataSnapshot) {
78 | Iterator items = dataSnapshot.getChildren().iterator();
79 | Toast.makeText(ActivityDBRetriever.this, "Total Users : " + dataSnapshot.getChildrenCount(), Toast.LENGTH_SHORT).show();
80 | entries.clear();
81 | while (items.hasNext()) {
82 | DataSnapshot item = items.next();
83 | User user = item.getValue(User.class);
84 | entries.add(user);
85 | }
86 |
87 | recyclerview.setAdapter(new RecUsersAdapter(ActivityDBRetriever.this, entries));
88 | recyclerview.getAdapter().notifyDataSetChanged();
89 | mDatabase.child("users").removeEventListener(this);
90 | }
91 |
92 | @Override
93 | public void onCancelled(DatabaseError databaseError) {
94 | Toast.makeText(ActivityDBRetriever.this, "onCancelled called", Toast.LENGTH_SHORT).show();
95 | }
96 | }
97 |
98 | );
99 | }
100 |
101 | public void getDBObjects(View view) {
102 | if (mAuth.getCurrentUser() == null)
103 | return;
104 | getUsersObjects();
105 | }
106 |
107 | public void getDBMap(View view) {
108 | if (mAuth.getCurrentUser() == null)
109 | return;
110 | getUsersMap();
111 | }
112 |
113 | private void getUsersMap() {
114 | //mDatabase.child("users").limitToFirst(2).addValueEventListener(new ValueEventListener() {
115 | //mDatabase.child("users").orderByChild("name").addValueEventListener(new ValueEventListener() {
116 | mDatabase.child("users")
117 | .addValueEventListener(new ValueEventListener() {
118 | //mDatabase.child("users").addValueEventListener(new ValueEventListener() {
119 | @Override
120 | public void onDataChange(DataSnapshot dataSnapshot) {
121 | Iterator items = dataSnapshot.getChildren().iterator();
122 | Toast.makeText(ActivityDBRetriever.this, "Total Users : " + dataSnapshot.getChildrenCount(), Toast.LENGTH_SHORT).show();
123 | entries.clear();
124 | HashMap user = null;
125 | while (items.hasNext()) {
126 | DataSnapshot item = items.next();
127 | user = (HashMap) item.getValue();
128 | entries.add(new User(user.get("name").toString(), user.get("image").toString()));
129 | }
130 |
131 | recyclerview.setAdapter(new RecUsersAdapter(ActivityDBRetriever.this, entries));
132 | recyclerview.getAdapter().notifyDataSetChanged();
133 | mDatabase.child("users").removeEventListener(this);
134 | }
135 |
136 | @Override
137 | public void onCancelled(DatabaseError databaseError) {
138 |
139 | }
140 | }
141 |
142 | );
143 | }
144 |
145 |
146 | private class RecUsersAdapter extends RecyclerView.Adapter {
147 |
148 |
149 | private Context context;
150 | private ArrayList entries;
151 |
152 | public RecUsersAdapter(ActivityDBRetriever context, ArrayList entries) {
153 | this.context = context;
154 | this.entries = entries;
155 | }
156 |
157 | @Override
158 | public RecUsersAdapter.RecViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
159 | View v = LayoutInflater.from(context).inflate(R.layout.user_row, null);
160 | return new RecViewHolder(v);
161 | }
162 |
163 | @Override
164 | public void onBindViewHolder(RecViewHolder holder, int position) {
165 | User user = entries.get(position);
166 | if (!user.image.equals("default"))
167 | Picasso.with(context).load(user.image).into(holder.imageView);
168 | holder.textView.setText(user.name);
169 | }
170 |
171 |
172 | @Override
173 | public int getItemCount() {
174 | return entries.size();
175 | }
176 |
177 | public class RecViewHolder extends RecyclerView.ViewHolder {
178 |
179 | public ImageView imageView;
180 | public TextView textView;
181 |
182 | public RecViewHolder(View itemView) {
183 | super(itemView);
184 |
185 | imageView = (ImageView) itemView.findViewById(R.id.imageUser);
186 | textView = (TextView) itemView.findViewById(R.id.txtUser);
187 | }
188 | }
189 | }
190 | }
191 |
--------------------------------------------------------------------------------