Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Firebaseを利用したAndroidアプリ開発実践入門

 Firebaseを利用したAndroidアプリ開発実践入門

Firebaseを利用したAndroidアプリ開発実践入門

Fumihiko Shiroyama

October 09, 2016
Tweet

More Decks by Fumihiko Shiroyama

Other Decks in Programming

Transcript

  1. رٌ،فٔ稱➜ ׻ְ׻ְثٍحز IUUQTQMBZHPPHMFDPNTUPSFBQQT EFUBJMT JEVTTIJSPZBNBBOESPJEGJSFCBTFSFBMUJNFDIBU ˖ ٔ،ٕة؎يثٍحز ˖ 5XJUUFS钠鏾 ˖

    ًحإ٦آך鷏⥋ ˖ 歗⫷ך،حفٗ٦س ˖ 荈ⴓך鷏׏׋ًحإ٦آך⵴ꤐ ˖ 荈ⴓך鷏׏׋歗⫷ך⵴ꤐ IUUQTHJUIVCDPNTSZN'JSFCBTF3FBM5JNF$IBU
  2. // Top-level build file
 
 buildscript {
 repositories {
 jcenter()


    mavenCentral()
 }
 dependencies {
 classpath 'com.google.gms:google-services:3.0.0'
 }
 } فٗآؙؑزךCVJMEHSBEMF
  3. def firebase_lib_version = '9.6.1'
 
 dependencies {
 compile fileTree(dir: 'libs',

    include: ['*.jar'])
 
 compile "com.google.firebase:firebase-core:${firebase_lib_version}"
 }
 
 // THIS MUST BE AT THE BOTTOM
 apply plugin: 'com.google.gms.google-services' ،فٌٔآُ٦ٕךCVJMEHSBEMF
  4. def firebase_lib_version = '9.6.1'
 
 dependencies {
 compile fileTree(dir: 'libs',

    include: ['*.jar'])
 
 compile "com.google.firebase:firebase-core:${firebase_lib_version}"
 }
 
 // THIS MUST BE AT THE BOTTOM
 apply plugin: 'com.google.gms.google-services' ،فٌٔآُ٦ٕךCVJMEHSBEMF
  5. "VUIFOUJDBUJPO ˖ 'JSFCBTFך钠鏾㛇湍 ˖ 'JSFCBTF荈魦ָ*%1"44ח״׷钠鏾堣圓׾䭯׏ג ְ׷➭ծ(PPHMF 'BDFCPPL 5XJUUFS (JU)VCזו ך،ؕؐٝزד钠鏾דֹ׷

    ˖ ⼡せךٙٝة؎ي钠鏾 ˖ 醱侧钠鏾فٗغ؎تך钠鏾䞔㜠ך窟さ ˖ ׻ְ׻ְثٍحزדכ5XJUUFS钠鏾׾ⵃ欽׃תׅ
  6. def firebase_lib_version = '9.6.1'
 
 dependencies {
 compile "com.google.firebase:firebase-core:${firebase_lib_version}" compile

    "com.google.firebase:firebase-auth:${firebase_lib_version}"
 }
 
 // THIS MUST BE AT THE BOTTOM
 apply plugin: 'com.google.gms.google-services' ،فٌٔآُ٦ٕךCVJMEHSBEMF
  7. public class MyApplication extends Application {
 public ApplicationComponent applicationComponent;
 


    @Override
 public void onCreate() {
 super.onCreate();
 
 TwitterAuthConfig authConfig = new TwitterAuthConfig(BuildConfig.TWITTER_KEY, BuildConfig.TWITTER_SECRET);
 Fabric.with(this, new Twitter(authConfig), new Crashlytics());
 }
 
 }
  8. public class MyApplication extends Application {
 public ApplicationComponent applicationComponent;
 


    @Override
 public void onCreate() {
 super.onCreate();
 
 TwitterAuthConfig authConfig = new TwitterAuthConfig(BuildConfig.TWITTER_KEY, BuildConfig.TWITTER_SECRET);
 Fabric.with(this, new Twitter(authConfig), new Crashlytics());
 }
 
 } "1*,FZ 4FDSFU
  9. @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {


    twitterLoginButton.onActivityResult(requestCode, resultCode, data);
 }
  10. @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {


    twitterLoginButton.onActivityResult(requestCode, resultCode, data);
 } 钠鏾䖓؝٦ٕغحؙ
  11. twitterLoginButton.setCallback(new Callback<TwitterSession>() {
 @Override
 public void success(Result<TwitterSession> result) {
 TwitterSession

    session = result.data;
 TwitterAuthToken token = session.getAuthToken();
 AuthCredential credential = TwitterAuthProvider.getCredential(token.token, token.secret);
 
 FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
 firebaseAuth.signInWithCredential(credential)
 .addOnSuccessListener(authResult -> {
 FirebaseUser firebaseUser = authResult.getUser();
 String uid = firebaseUser.getUid();
 UserInfo twitterUser = firebaseUser.getProviderData().get(1);
 String name = twitterUser.getDisplayName();
 String thumbnail = twitterUser.getPhotoUrl().toString();
 })
 .addOnFailureListener(e -> Log.e(TAG, e.getMessage(), e));
 }
 
 @Override
 public void failure(TwitterException exception) {
 }
 });
  12. twitterLoginButton.setCallback(new Callback<TwitterSession>() {
 @Override
 public void success(Result<TwitterSession> result) {
 TwitterSession

    session = result.data;
 TwitterAuthToken token = session.getAuthToken();
 AuthCredential credential = TwitterAuthProvider.getCredential(token.token, token.secret);
 
 FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
 firebaseAuth.signInWithCredential(credential)
 .addOnSuccessListener(authResult -> {
 FirebaseUser firebaseUser = authResult.getUser();
 String uid = firebaseUser.getUid();
 UserInfo twitterUser = firebaseUser.getProviderData().get(1);
 String name = twitterUser.getDisplayName();
 String thumbnail = twitterUser.getPhotoUrl().toString();
 })
 .addOnFailureListener(e -> Log.e(TAG, e.getMessage(), e));
 }
 
 @Override
 public void failure(TwitterException exception) {
 }
 }); ؙٔحؙ
  13. twitterLoginButton.setCallback(new Callback<TwitterSession>() {
 @Override
 public void success(Result<TwitterSession> result) {
 TwitterSession

    session = result.data;
 TwitterAuthToken token = session.getAuthToken();
 AuthCredential credential = TwitterAuthProvider.getCredential(token.token, token.secret);
 
 FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
 firebaseAuth.signInWithCredential(credential)
 .addOnSuccessListener(authResult -> {
 FirebaseUser firebaseUser = authResult.getUser();
 String uid = firebaseUser.getUid();
 UserInfo twitterUser = firebaseUser.getProviderData().get(1);
 String name = twitterUser.getDisplayName();
 String thumbnail = twitterUser.getPhotoUrl().toString();
 })
 .addOnFailureListener(e -> Log.e(TAG, e.getMessage(), e));
 }
 
 @Override
 public void failure(TwitterException exception) {
 }
 }); 5XJUUFSךز٦ؙٝ
  14. twitterLoginButton.setCallback(new Callback<TwitterSession>() {
 @Override
 public void success(Result<TwitterSession> result) {
 TwitterSession

    session = result.data;
 TwitterAuthToken token = session.getAuthToken();
 AuthCredential credential = TwitterAuthProvider.getCredential(token.token, token.secret);
 
 FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
 firebaseAuth.signInWithCredential(credential)
 .addOnSuccessListener(authResult -> {
 FirebaseUser firebaseUser = authResult.getUser();
 String uid = firebaseUser.getUid();
 UserInfo twitterUser = firebaseUser.getProviderData().get(1);
 String name = twitterUser.getDisplayName();
 String thumbnail = twitterUser.getPhotoUrl().toString();
 })
 .addOnFailureListener(e -> Log.e(TAG, e.getMessage(), e));
 }
 
 @Override
 public void failure(TwitterException exception) {
 }
 }); 'JSFCBTFך钠鏾彊⪒
  15. twitterLoginButton.setCallback(new Callback<TwitterSession>() {
 @Override
 public void success(Result<TwitterSession> result) {
 TwitterSession

    session = result.data;
 TwitterAuthToken token = session.getAuthToken();
 AuthCredential credential = TwitterAuthProvider.getCredential(token.token, token.secret);
 
 FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
 firebaseAuth.signInWithCredential(credential)
 .addOnSuccessListener(authResult -> {
 FirebaseUser firebaseUser = authResult.getUser();
 String uid = firebaseUser.getUid();
 UserInfo twitterUser = firebaseUser.getProviderData().get(1);
 String name = twitterUser.getDisplayName();
 String thumbnail = twitterUser.getPhotoUrl().toString();
 })
 .addOnFailureListener(e -> Log.e(TAG, e.getMessage(), e));
 }
 
 @Override
 public void failure(TwitterException exception) {
 }
 }); 'JSFCBTFחؚٗ؎ٝ
  16. twitterLoginButton.setCallback(new Callback<TwitterSession>() {
 @Override
 public void success(Result<TwitterSession> result) {
 TwitterSession

    session = result.data;
 TwitterAuthToken token = session.getAuthToken();
 AuthCredential credential = TwitterAuthProvider.getCredential(token.token, token.secret);
 
 FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
 firebaseAuth.signInWithCredential(credential)
 .addOnSuccessListener(authResult -> {
 FirebaseUser firebaseUser = authResult.getUser();
 String uid = firebaseUser.getUid();
 UserInfo twitterUser = firebaseUser.getProviderData().get(1);
 String name = twitterUser.getDisplayName();
 String thumbnail = twitterUser.getPhotoUrl().toString();
 })
 .addOnFailureListener(e -> Log.e(TAG, e.getMessage(), e));
 }
 
 @Override
 public void failure(TwitterException exception) {
 }
 }); 'JSFCBTFⰻךِ٦ؠ
  17. twitterLoginButton.setCallback(new Callback<TwitterSession>() {
 @Override
 public void success(Result<TwitterSession> result) {
 TwitterSession

    session = result.data;
 TwitterAuthToken token = session.getAuthToken();
 AuthCredential credential = TwitterAuthProvider.getCredential(token.token, token.secret);
 
 FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
 firebaseAuth.signInWithCredential(credential)
 .addOnSuccessListener(authResult -> {
 FirebaseUser firebaseUser = authResult.getUser();
 String uid = firebaseUser.getUid();
 UserInfo twitterUser = firebaseUser.getProviderData().get(1);
 String name = twitterUser.getDisplayName();
 String thumbnail = twitterUser.getPhotoUrl().toString();
 })
 .addOnFailureListener(e -> Log.e(TAG, e.getMessage(), e));
 }
 
 @Override
 public void failure(TwitterException exception) {
 }
 }); ♧䠐ז*%
  18. @Override
 public boolean onOptionsItemSelected(MenuItem item) {
 switch (item.getItemId()) {
 case

    R.id.action_logout:
 firebaseAuth.signOut();
 return true;
 default:
 return super.onOptionsItemSelected(item);
 }
 }
  19. @Override
 public boolean onOptionsItemSelected(MenuItem item) {
 switch (item.getItemId()) {
 case

    R.id.action_logout:
 firebaseAuth.signOut();
 return true;
 default:
 return super.onOptionsItemSelected(item);
 }
 } ؚٗ،ؐز
  20. ر٦ة圓鸡 { "users": { "alovelace": { "name": "Ada Lovelace", "contacts":

    { "ghopper": true }, }, "ghopper": { ... }, "eclarke": { ... } } } +40/ד邌植דֹ׷⟣䠐ךر٦ة圓鸡
  21. ر٦ة圓鸡 劤傈䪔ֲر٦ة圓鸡 { "messages" : { "message01" : { "body"

    : "hello!", "senderUid" : "user0001", "type" : 0 }, ..... }, "users" : { "user01" : { "name" : "Steve", "thumbnail" : "http://example.com/img/user01.jpg" }, .... } }
  22. ر٦ة圓鸡 ط؎ذ؍ـדٔأزכ؟ه٦زׁ׸זְ { "messages" : { "message01" : { "body"

    : "hello!", "senderUid" : "user0001", "type" : 0 }, ..... }, "users" : { "user01" : { "name" : "Steve", "thumbnail" : "http://example.com/img/user01.jpg" }, .... } }
  23. ر٦ة圓鸡 { "messages" : { "message01" : { "body" :

    "hello!", "senderUid" : "user0001", "type" : 0 }, "message02" : { "body" : "how are you!", "senderUid" : "user0002", "type" : 0 }, .... } }
  24. ر٦ة圓鸡 { "messages" : { "message01" : { "body" :

    "hello!", "senderUid" : "user0001", "type" : 0 }, "message02" : { "body" : "how are you!", "senderUid" : "user0002", "type" : 0 }, .... } }
  25. ؎كٝزٔأشך珏겲 ٔأش ؎كٝز 欽鷿 7BMVF&WFOU-JTUFOFS PO%BUB$IBOHF ػأך؝ٝذٝخח㼎ׅ׷ 㢌刿儗חㄎל׸׷ $IJME&WFOU-JTUFOFS PO$IJME"EEFE

    ٔأزח㶨銲稆ָ鷄⸇ׁ׸ ׋儗חㄎל׸׷ $IJME&WFOU-JTUFOFS PO$IJME$IBOHFE ٔأزך㶨銲稆ח㢌刿ָ֮ ׏׋儗חㄎל׸׷ $IJME&WFOU-JTUFOFS PO$IJME3FNPWFE ٔأزך㶨銲稆ָ⵴ꤐׁ׸ ׋儗חㄎל׸׷ $IJME&WFOU-JTUFOFS PO$IJME.PWFE ٔأزך㶨銲稆ך갫䎷ָ㢌 ׻׏׋儗חㄎל׸׷
  26. def firebase_lib_version = '9.6.1'
 
 dependencies {
 compile "com.google.firebase:firebase-core:${firebase_lib_version}" compile

    "com.google.firebase:firebase-auth:${firebase_lib_version}" compile "com.google.firebase:firebase-database:${firebase_lib_version}"
 }
 
 // THIS MUST BE AT THE BOTTOM
 apply plugin: 'com.google.gms.google-services' ،فٌٔآُ٦ٕךCVJMEHSBEMF
  27. ر٦ةך知⽃ז铣׫剅ֹ // Write a message to the database FirebaseDatabase database

    = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference("message"); myRef.setValue("Hello, World!");
  28. ر٦ةך知⽃ז剅ֹ鴥׫ // Write a message to the database FirebaseDatabase database

    = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference("message"); myRef.setValue("Hello, World!"); ر٦ةك٦أפ،ؙإأׅ׷彊⪒
  29. ر٦ةך知⽃ז剅ֹ鴥׫ // Write a message to the database FirebaseDatabase database

    = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference("message"); myRef.setValue("Hello, World!"); NFTTBHFפך⿫撑
  30. ر٦ةך知⽃ז剅ֹ鴥׫ // Write a message to the database FirebaseDatabase database

    = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference("message"); myRef.setValue("Hello, World!"); NFTTBHF)FMMP 8PSMEה剅ֹ鴥׫
  31. ر٦ةך知⽃ז铣׫⳿׃ FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference messageRef = database.getReference("message"); ValueEventListener

    messageListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String message = dataSnapshot.getValue(String.class); } @Override public void onCancelled(DatabaseError databaseError) { } }; messageRef.addValueEventListener(messageListener); NFTTBHFפך⿫撑
  32. ر٦ةך知⽃ז铣׫⳿׃ FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference messageRef = database.getReference("message"); ValueEventListener

    messageListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String message = dataSnapshot.getValue(String.class); } @Override public void onCancelled(DatabaseError databaseError) { } }; messageRef.addValueEventListener(messageListener); 7BMVF&WFOU-JTUFOFSך⡲䧭
  33. ر٦ةך知⽃ז铣׫⳿׃ FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference messageRef = database.getReference("message"); ValueEventListener

    messageListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String message = dataSnapshot.getValue(String.class); } @Override public void onCancelled(DatabaseError databaseError) { } }; messageRef.addValueEventListener(messageListener); ر٦ةך《׶⳿׃
  34. ر٦ةך知⽃ז铣׫⳿׃ FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference messageRef = database.getReference("message"); ValueEventListener

    messageListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String message = dataSnapshot.getValue(String.class); } @Override public void onCancelled(DatabaseError databaseError) { } }; messageRef.addValueEventListener(messageListener); ٔأشך鏣㹀
  35. ׍ז׫ח˘ ٔؿ؋ٖٝأכDIJME ד⟣䠐ך 帾ׁתד䱠׏גְֻֿהָדֹ׷ private void writeNewUser(String userId, String name,

    String email) { User user = new User(name, email); mDatabase.child("users").child(userId).setValue(user); }
  36. 7BMVF&WFOU-JTUFOFS ValueEventListener postListener = new ValueEventListener() { @Override public void

    onDataChange(DataSnapshot dataSnapshot) { // Get Post object and use the values to update the UI Post post = dataSnapshot.getValue(Post.class); // ... } @Override public void onCancelled(DatabaseError databaseError) { // Getting Post failed, log a message Log.w(TAG, "loadPost:onCancelled", databaseError.toException()); // ... } }; mPostReference.addValueEventListener(postListener);
  37. 7BMVF&WFOU-JTUFOFS ValueEventListener postListener = new ValueEventListener() { @Override public void

    onDataChange(DataSnapshot dataSnapshot) { // Get Post object and use the values to update the UI Post post = dataSnapshot.getValue(Post.class); // ... } @Override public void onCancelled(DatabaseError databaseError) { // Getting Post failed, log a message Log.w(TAG, "loadPost:onCancelled", databaseError.toException()); // ... } }; mPostReference.addValueEventListener(postListener);
  38. 7BMVF&WFOU-JTUFOFS ValueEventListener postListener = new ValueEventListener() { @Override public void

    onDataChange(DataSnapshot dataSnapshot) { // Get Post object and use the values to update the UI Post post = dataSnapshot.getValue(Post.class); // ... } @Override public void onCancelled(DatabaseError databaseError) { // Getting Post failed, log a message Log.w(TAG, "loadPost:onCancelled", databaseError.toException()); // ... } }; mPostReference.addValueEventListener(postListener);
  39. 7BMVF&WFOU-JTUFOFS ValueEventListener postListener = new ValueEventListener() { @Override public void

    onDataChange(DataSnapshot dataSnapshot) { // Get Post object and use the values to update the UI Post post = dataSnapshot.getValue(Post.class); // ... } @Override public void onCancelled(DatabaseError databaseError) { // Getting Post failed, log a message Log.w(TAG, "loadPost:onCancelled", databaseError.toException()); // ... } }; mPostReference.addValueEventListener(postListener);
  40. 7BMVF&WFOU-JTUFOFS ValueEventListener postListener = new ValueEventListener() { @Override public void

    onDataChange(DataSnapshot dataSnapshot) { // Get Post object and use the values to update the UI Post post = dataSnapshot.getValue(Post.class); // ... } @Override public void onCancelled(DatabaseError databaseError) { // Getting Post failed, log a message Log.w(TAG, "loadPost:onCancelled", databaseError.toException()); // ... } }; mPostReference.addValueEventListener(postListener); ⥂㶷׮铣׫⳿׃׮⟣䠐ך10+0ָ⢪欽〳腉
  41. $IJME&WFOU-JTUFOFS ChildEventListener childEventListener = new ChildEventListener() { @Override public void

    onChildAdded(DataSnapshot dataSnapshot, String previousChildName) { Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey()); // A new comment has been added, add it to the displayed list Comment comment = dataSnapshot.getValue(Comment.class); // ... }
  42. $IJME&WFOU-JTUFOFS ChildEventListener childEventListener = new ChildEventListener() { @Override public void

    onChildAdded(DataSnapshot dataSnapshot, String previousChildName) { Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey()); // A new comment has been added, add it to the displayed list Comment comment = dataSnapshot.getValue(Comment.class); // ... } PO$IJME"EEFE כ㶨銲稆ך鷄⸇
  43. $IJME&WFOU-JTUFOFS @Override public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) { Log.d(TAG,

    "onChildChanged:" + dataSnapshot.getKey()); // A comment has changed, use the key to determine if we are displaying this // comment and if so displayed the changed comment. Comment newComment = dataSnapshot.getValue(Comment.class); String commentKey = dataSnapshot.getKey(); // ... }
  44. $IJME&WFOU-JTUFOFS @Override public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) { Log.d(TAG,

    "onChildChanged:" + dataSnapshot.getKey()); // A comment has changed, use the key to determine if we are displaying this // comment and if so displayed the changed comment. Comment newComment = dataSnapshot.getValue(Comment.class); String commentKey = dataSnapshot.getKey(); // ... } PO$IJME$IBOHFE כ㶨銲稆ך㢌⻉
  45. $IJME&WFOU-JTUFOFS @Override public void onChildRemoved(DataSnapshot dataSnapshot) { Log.d(TAG, "onChildRemoved:" +

    dataSnapshot.getKey()); // A comment has changed, use the key to determine if we are displaying this // comment and if so remove it. String commentKey = dataSnapshot.getKey(); // ... }
  46. $IJME&WFOU-JTUFOFS @Override public void onChildRemoved(DataSnapshot dataSnapshot) { Log.d(TAG, "onChildRemoved:" +

    dataSnapshot.getKey()); // A comment has changed, use the key to determine if we are displaying this // comment and if so remove it. String commentKey = dataSnapshot.getKey(); // ... } PO$IJME3FNPWFE כ㶨銲稆ך⵴ꤐ
  47. $IJME&WFOU-JTUFOFS @Override public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) { Log.d(TAG,

    "onChildMoved:" + dataSnapshot.getKey()); // A comment has changed position, use the key to determine if we are // displaying this comment and if so move it. Comment movedComment = dataSnapshot.getValue(Comment.class); String commentKey = dataSnapshot.getKey(); // ... }
  48. $IJME&WFOU-JTUFOFS @Override public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) { Log.d(TAG,

    "onChildMoved:" + dataSnapshot.getKey()); // A comment has changed position, use the key to determine if we are // displaying this comment and if so move it. Comment movedComment = dataSnapshot.getValue(Comment.class); String commentKey = dataSnapshot.getKey(); // ... } PO$IJME.PWFE כ㶨銲稆ך갫殢Ⰵ剏
  49. $IJME&WFOU-JTUFOFS @Override public void onCancelled(DatabaseError databaseError) { Log.w(TAG, "postComments:onCancelled", databaseError.toException());

    Toast.makeText(mContext, "Failed to load comments.", Toast.LENGTH_SHORT).show(); } }; ref.addChildEventListener(childEventListener);
  50. $IJME&WFOU-JTUFOFS @Override public void onCancelled(DatabaseError databaseError) { Log.w(TAG, "postComments:onCancelled", databaseError.toException());

    Toast.makeText(mContext, "Failed to load comments.", Toast.LENGTH_SHORT).show(); } }; ref.addChildEventListener(childEventListener); BEE$IJME&WFOU-JTUFOFSחإحز 埄ꣲךؒٓ٦瘝
  51. ٔأزח㶨銲稆׾鷄⸇ DatabaseReference newMessageRef = databaseReference.child("/messages").push();
 
 newMessageRef
 .setValue(message)
 .addOnSuccessListener(result ->

    Log.d(TAG, "try message send."))
 .addOnFailureListener(error -> handleError(error, R.string.message_sent_error)); QVTI דة؎يأةٝفח㛇בֻLFZָ荈⹛涪遤ׁ׸׷
  52. ٔأزח㶨銲稆׾鷄⸇ DatabaseReference newMessageRef = databaseReference.child("/messages").push();
 
 newMessageRef
 .setValue(message)
 .addOnSuccessListener(result ->

    Log.d(TAG, "try message send."))
 .addOnFailureListener(error -> handleError(error, R.string.message_sent_error)); ֮הכֿ׸תדず圫TFU7BMVFׅ׷׌ֽ
  53. 銲稆ך⚛ן剏ִ String myUserId = getUid(); Query myTopPostsQuery = databaseReference.child("user-posts").child(myUserId) .orderByChild("starCount");

    myTopPostsQuery.addChildEventListener(new ChildEventListener() { // TODO: implement the ChildEventListener methods as documented above // ... });
  54. 銲稆ך⚛ן剏ִ String myUserId = getUid(); Query myTopPostsQuery = databaseReference.child("user-posts").child(myUserId) .orderByChild("starCount");

    myTopPostsQuery.addChildEventListener(new ChildEventListener() { // TODO: implement the ChildEventListener methods as documented above // ... }); ⟣䠐ךٔؿ؋ٖٝأ׾⿫撑
  55. 銲稆ך⚛ן剏ִ String myUserId = getUid(); Query myTopPostsQuery = databaseReference.child("user-posts").child(myUserId) .orderByChild("starCount");

    myTopPostsQuery.addChildEventListener(new ChildEventListener() { // TODO: implement the ChildEventListener methods as documented above // ... }); ا٦ز勴⟝׾䭷㹀
  56. 銲稆ך⚛ן剏ִ String myUserId = getUid(); Query myTopPostsQuery = databaseReference.child("user-posts").child(myUserId) .orderByChild("starCount");

    myTopPostsQuery.addChildEventListener(new ChildEventListener() { // TODO: implement the ChildEventListener methods as documented above // ... }); ֿ׸תד鸐׶ٔأش׾إحز
  57. def firebase_lib_version = '9.6.1'
 
 dependencies {
 compile "com.google.firebase:firebase-core:${firebase_lib_version}" compile

    "com.google.firebase:firebase-auth:${firebase_lib_version}" compile "com.google.firebase:firebase-storage:${firebase_lib_version}"
 }
 
 // THIS MUST BE AT THE BOTTOM
 apply plugin: 'com.google.gms.google-services' ،فٌٔآُ٦ٕךCVJMEHSBEMF
  58. 4UPSBHF FirebaseStorage storage = FirebaseStorage.getInstance(); StorageReference storageRef = storage.getReferenceFromUrl("gs://<your-bucket-name>"); StorageReference

    imagesRef = storageRef.child("images"); StorageReference spaceRef = storageRef.child("images/space.jpg"); spaceRef.getPath(); spaceRef.getName(); spaceRef.getBucket();
  59. 4UPSBHF FirebaseStorage storage = FirebaseStorage.getInstance(); StorageReference storageRef = storage.getReferenceFromUrl("gs://<your-bucket-name>"); StorageReference

    imagesRef = storageRef.child("images"); StorageReference spaceRef = storageRef.child("images/space.jpg"); spaceRef.getPath(); spaceRef.getName(); spaceRef.getBucket();
  60. 4UPSBHF FirebaseStorage storage = FirebaseStorage.getInstance(); StorageReference storageRef = storage.getReferenceFromUrl("gs://<your-bucket-name>"); StorageReference

    imagesRef = storageRef.child("images"); StorageReference spaceRef = storageRef.child("images/space.jpg"); spaceRef.getPath(); spaceRef.getName(); spaceRef.getBucket();
  61. 4UPSBHF FirebaseStorage storage = FirebaseStorage.getInstance(); StorageReference storageRef = storage.getReferenceFromUrl("gs://<your-bucket-name>"); StorageReference

    imagesRef = storageRef.child("images"); StorageReference spaceRef = storageRef.child("images/space.jpg"); spaceRef.getPath(); spaceRef.getName(); spaceRef.getBucket();
  62. 4UPSBHF FirebaseStorage storage = FirebaseStorage.getInstance(); StorageReference storageRef = storage.getReferenceFromUrl("gs://<your-bucket-name>"); StorageReference

    imagesRef = storageRef.child("images"); StorageReference spaceRef = storageRef.child("images/space.jpg"); spaceRef.getPath(); spaceRef.getName(); spaceRef.getBucket();
  63. 4UPSBHFח،حفٗ٦س public void uploadImage(String filePath, boolean deletePath) {
 String fileName

    = UUID.randomUUID().toString();
 StorageReference target = storageReference
 .child(IMG_DIR)
 .child(fileName);
 
 try {
 InputStream inputStream = new BufferedInputStream(new FileInputStream(filePath));
 target.putStream(inputStream)
 .addOnSuccessListener(taskSnapshot -> {
 Log.d(TAG, "upload succeeded.");
 long totalBytes = taskSnapshot.getTotalByteCount();
 Uri downloadUri = taskSnapshot.getDownloadUrl();
 })
 .addOnFailureListener(e -> Log.e(TAG, e.getMessage(), e));
 } catch (FileNotFoundException e) {
 Log.e(TAG, e.getMessage(), e);
 }
 }
  64. 4UPSBHFח،حفٗ٦س public void uploadImage(String filePath, boolean deletePath) {
 String fileName

    = UUID.randomUUID().toString();
 StorageReference target = storageReference
 .child(IMG_DIR)
 .child(fileName);
 
 try {
 InputStream inputStream = new BufferedInputStream(new FileInputStream(filePath));
 target.putStream(inputStream)
 .addOnSuccessListener(taskSnapshot -> {
 Log.d(TAG, "upload succeeded.");
 long totalBytes = taskSnapshot.getTotalByteCount();
 Uri downloadUri = taskSnapshot.getDownloadUrl();
 })
 .addOnFailureListener(e -> Log.e(TAG, e.getMessage(), e));
 } catch (FileNotFoundException e) {
 Log.e(TAG, e.getMessage(), e);
 }
 }
  65. 4UPSBHFח،حفٗ٦س public void uploadImage(String filePath, boolean deletePath) {
 String fileName

    = UUID.randomUUID().toString();
 StorageReference target = storageReference
 .child(IMG_DIR)
 .child(fileName);
 
 try {
 InputStream inputStream = new BufferedInputStream(new FileInputStream(filePath));
 target.putStream(inputStream)
 .addOnSuccessListener(taskSnapshot -> {
 Log.d(TAG, "upload succeeded.");
 long totalBytes = taskSnapshot.getTotalByteCount();
 Uri downloadUri = taskSnapshot.getDownloadUrl();
 })
 .addOnFailureListener(e -> Log.e(TAG, e.getMessage(), e));
 } catch (FileNotFoundException e) {
 Log.e(TAG, e.getMessage(), e);
 }
 }
  66. 4UPSBHFח،حفٗ٦س public void uploadImage(String filePath, boolean deletePath) {
 String fileName

    = UUID.randomUUID().toString();
 StorageReference target = storageReference
 .child(IMG_DIR)
 .child(fileName);
 
 try {
 InputStream inputStream = new BufferedInputStream(new FileInputStream(filePath));
 target.putStream(inputStream)
 .addOnSuccessListener(taskSnapshot -> {
 Log.d(TAG, "upload succeeded.");
 long totalBytes = taskSnapshot.getTotalByteCount();
 Uri downloadUri = taskSnapshot.getDownloadUrl();
 })
 .addOnFailureListener(e -> Log.e(TAG, e.getMessage(), e));
 } catch (FileNotFoundException e) {
 Log.e(TAG, e.getMessage(), e);
 }
 }
  67. 4UPSBHFח،حفٗ٦س public void uploadImage(String filePath, boolean deletePath) {
 String fileName

    = UUID.randomUUID().toString();
 StorageReference target = storageReference
 .child(IMG_DIR)
 .child(fileName);
 
 try {
 InputStream inputStream = new BufferedInputStream(new FileInputStream(filePath));
 target.putStream(inputStream)
 .addOnSuccessListener(taskSnapshot -> {
 Log.d(TAG, "upload succeeded.");
 long totalBytes = taskSnapshot.getTotalByteCount();
 Uri downloadUri = taskSnapshot.getDownloadUrl();
 })
 .addOnFailureListener(e -> Log.e(TAG, e.getMessage(), e));
 } catch (FileNotFoundException e) {
 Log.e(TAG, e.getMessage(), e);
 }
 }
  68. 4UPSBHFח،حفٗ٦س public void uploadImage(String filePath, boolean deletePath) {
 String fileName

    = UUID.randomUUID().toString();
 StorageReference target = storageReference
 .child(IMG_DIR)
 .child(fileName);
 
 try {
 InputStream inputStream = new BufferedInputStream(new FileInputStream(filePath));
 target.putStream(inputStream)
 .addOnSuccessListener(taskSnapshot -> {
 Log.d(TAG, "upload succeeded.");
 long totalBytes = taskSnapshot.getTotalByteCount();
 Uri downloadUri = taskSnapshot.getDownloadUrl();
 })
 .addOnFailureListener(e -> Log.e(TAG, e.getMessage(), e));
 } catch (FileNotFoundException e) {
 Log.e(TAG, e.getMessage(), e);
 }
 } ؙٓ؎،ٝزכֿ׸׾تؐٝٗ٦س
  69. 4UPSBHFַ׵⵴ꤐ public void deleteImage(String fileName) {
 StorageReference target = storageReference


    .child(IMG_DIR)
 .child(fileName);
 target.delete()
 .addOnSuccessListener(result -> Log.d(TAG, "image delete ok."))
 .addOnFailureListener(error -> Log.e(TAG, error.getMessage(), error));
 }
  70. 4UPSBHFַ׵⵴ꤐ public void deleteImage(String fileName) {
 StorageReference target = storageReference


    .child(IMG_DIR)
 .child(fileName);
 target.delete()
 .addOnSuccessListener(result -> Log.d(TAG, "image delete ok."))
 .addOnFailureListener(error -> Log.e(TAG, error.getMessage(), error));
 }
  71. 4UPSBHFַ׵⵴ꤐ public void deleteImage(String fileName) {
 StorageReference target = storageReference


    .child(IMG_DIR)
 .child(fileName);
 target.delete()
 .addOnSuccessListener(result -> Log.d(TAG, "image delete ok."))
 .addOnFailureListener(error -> Log.e(TAG, error.getMessage(), error));
 }
  72. 4UPSBHFַ׵⵴ꤐ public void deleteImage(String fileName) {
 StorageReference target = storageReference


    .child(IMG_DIR)
 .child(fileName);
 target.delete()
 .addOnSuccessListener(result -> Log.d(TAG, "image delete ok."))
 .addOnFailureListener(error -> Log.e(TAG, error.getMessage(), error));
 }
  73. def firebase_lib_version = '9.6.1'
 
 dependencies {
 compile "com.google.firebase:firebase-core:${firebase_lib_version}" compile

    "com.google.firebase:firebase-auth:${firebase_lib_version}" compile "com.google.firebase:firebase-storage:${firebase_lib_version}" compile "com.google.firebase:firebase-config:${firebase_lib_version}"
 }
 
 // THIS MUST BE AT THE BOTTOM
 apply plugin: 'com.google.gms.google-services' ،فٌٔآُ٦ٕךCVJMEHSBEMF
  74. 3FNPUF$POGJH FirebaseRemoteConfigSettings remoteConfigSettings = new FirebaseRemoteConfigSettings.Builder()
 .setDeveloperModeEnabled(BuildConfig.DEBUG)
 .build();
 
 FirebaseRemoteConfig

    firebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
 firebaseRemoteConfig.setConfigSettings(remoteConfigSettings);
 firebaseRemoteConfig.setDefaults(R.xml.remote_config_defaults);
 
 if (firebaseRemoteConfig.getInfo().getConfigSettings().isDeveloperModeEnabled()) {
 cacheExpiration = 0;
 }
 
 firebaseRemoteConfig.fetch(cacheExpiration)
 .addOnSuccessListener(result -> Log.d(TAG, "Fetch succeeded."))
 .addOnFailureListener(e -> Log.e(TAG, "Fetch failed.", e));
  75. 3FNPUF$POGJH FirebaseRemoteConfigSettings remoteConfigSettings = new FirebaseRemoteConfigSettings.Builder()
 .setDeveloperModeEnabled(BuildConfig.DEBUG)
 .build();
 
 FirebaseRemoteConfig

    firebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
 firebaseRemoteConfig.setConfigSettings(remoteConfigSettings);
 firebaseRemoteConfig.setDefaults(R.xml.remote_config_defaults);
 
 if (firebaseRemoteConfig.getInfo().getConfigSettings().isDeveloperModeEnabled()) {
 cacheExpiration = 0;
 }
 
 firebaseRemoteConfig.fetch(cacheExpiration)
 .addOnSuccessListener(result -> Log.d(TAG, "Fetch succeeded."))
 .addOnFailureListener(e -> Log.e(TAG, "Fetch failed.", e));
  76. 3FNPUF$POGJH FirebaseRemoteConfigSettings remoteConfigSettings = new FirebaseRemoteConfigSettings.Builder()
 .setDeveloperModeEnabled(BuildConfig.DEBUG)
 .build();
 
 FirebaseRemoteConfig

    firebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
 firebaseRemoteConfig.setConfigSettings(remoteConfigSettings);
 firebaseRemoteConfig.setDefaults(R.xml.remote_config_defaults);
 
 if (firebaseRemoteConfig.getInfo().getConfigSettings().isDeveloperModeEnabled()) {
 cacheExpiration = 0;
 }
 
 firebaseRemoteConfig.fetch(cacheExpiration)
 .addOnSuccessListener(result -> Log.d(TAG, "Fetch succeeded."))
 .addOnFailureListener(e -> Log.e(TAG, "Fetch failed.", e));
  77. 3FNPUF$POGJH FirebaseRemoteConfigSettings remoteConfigSettings = new FirebaseRemoteConfigSettings.Builder()
 .setDeveloperModeEnabled(BuildConfig.DEBUG)
 .build();
 
 FirebaseRemoteConfig

    firebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
 firebaseRemoteConfig.setConfigSettings(remoteConfigSettings);
 firebaseRemoteConfig.setDefaults(R.xml.remote_config_defaults);
 
 if (firebaseRemoteConfig.getInfo().getConfigSettings().isDeveloperModeEnabled()) {
 cacheExpiration = 0;
 }
 
 firebaseRemoteConfig.fetch(cacheExpiration)
 .addOnSuccessListener(result -> Log.d(TAG, "Fetch succeeded."))
 .addOnFailureListener(e -> Log.e(TAG, "Fetch failed.", e));
  78. 3FNPUF$POGJH FirebaseRemoteConfigSettings remoteConfigSettings = new FirebaseRemoteConfigSettings.Builder()
 .setDeveloperModeEnabled(BuildConfig.DEBUG)
 .build();
 
 FirebaseRemoteConfig

    firebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
 firebaseRemoteConfig.setConfigSettings(remoteConfigSettings);
 firebaseRemoteConfig.setDefaults(R.xml.remote_config_defaults);
 
 if (firebaseRemoteConfig.getInfo().getConfigSettings().isDeveloperModeEnabled()) {
 cacheExpiration = 0;
 }
 
 firebaseRemoteConfig.fetch(cacheExpiration)
 .addOnSuccessListener(result -> Log.d(TAG, "Fetch succeeded."))
 .addOnFailureListener(e -> Log.e(TAG, "Fetch failed.", e));
  79. 3FNPUF$POGJH public void setBackgroundColor(View target) {
 String colorHex = firebaseRemoteConfig.getString("chat_bg_color");


    Log.d(TAG, "colorHex: " + colorHex);
 int color = Color.parseColor(colorHex);
 target.setBackgroundColor(color);
 }
  80. 3FNPUF$POGJH public void setBackgroundColor(View target) {
 String colorHex = firebaseRemoteConfig.getString("chat_bg_color");


    Log.d(TAG, "colorHex: " + colorHex);
 int color = Color.parseColor(colorHex);
 target.setBackgroundColor(color);
 }
  81. ׉ך➭5JQT private ValueEventListener singleShotListener = new ValueEventListener() {
 @Override
 public

    void onDataChange(DataSnapshot dataSnapshot) {
 for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
 Message message = getMessageWithId(snapshot); // தུ
 updateTimestamp(message.getTimestamp());
 } ɹɹɹɹɹ// தུ
 
 databaseReference.child(Message.PATH) .orderByChild(Message.KEY_TIMESTAMP) .startAt(lastTimestamp + 1) .addChildEventListener(childAddListener);
 }
 
 @Override
 public void onCancelled(DatabaseError databaseError) { }
 };
  82. ׉ך➭5JQT private ValueEventListener singleShotListener = new ValueEventListener() {
 @Override
 public

    void onDataChange(DataSnapshot dataSnapshot) {
 for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
 Message message = getMessageWithId(snapshot); // தུ
 updateTimestamp(message.getTimestamp());
 } ɹɹɹɹɹ// தུ
 
 databaseReference.child(Message.PATH) .orderByChild(Message.KEY_TIMESTAMP) .startAt(lastTimestamp + 1) .addChildEventListener(childAddListener);
 }
 
 @Override
 public void onCancelled(DatabaseError databaseError) { }
 };
  83. ׉ך➭5JQT private ValueEventListener singleShotListener = new ValueEventListener() {
 @Override
 public

    void onDataChange(DataSnapshot dataSnapshot) {
 for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
 Message message = getMessageWithId(snapshot); // தུ
 updateTimestamp(message.getTimestamp());
 } ɹɹɹɹɹ// தུ
 
 databaseReference.child(Message.PATH) .orderByChild(Message.KEY_TIMESTAMP) .startAt(lastTimestamp + 1) .addChildEventListener(childAddListener);
 }
 
 @Override
 public void onCancelled(DatabaseError databaseError) { }
 };
  84. ׉ך➭5JQT private ValueEventListener singleShotListener = new ValueEventListener() {
 @Override
 public

    void onDataChange(DataSnapshot dataSnapshot) {
 for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
 Message message = getMessageWithId(snapshot); // தུ
 updateTimestamp(message.getTimestamp());
 } ɹɹɹɹɹ// தུ
 
 databaseReference.child(Message.PATH) .orderByChild(Message.KEY_TIMESTAMP) .startAt(lastTimestamp + 1) .addChildEventListener(childAddListener);
 }
 
 @Override
 public void onCancelled(DatabaseError databaseError) { }
 };
  85. ׉ך➭5JQT private ValueEventListener singleShotListener = new ValueEventListener() {
 @Override
 public

    void onDataChange(DataSnapshot dataSnapshot) {
 for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
 Message message = getMessageWithId(snapshot); // தུ
 updateTimestamp(message.getTimestamp());
 } ɹɹɹɹɹ// தུ
 
 databaseReference.child(Message.PATH) .orderByChild(Message.KEY_TIMESTAMP) .startAt(lastTimestamp + 1) .addChildEventListener(childAddListener);
 }
 
 @Override
 public void onCancelled(DatabaseError databaseError) { }
 };
  86. ׉ך➭5JQT { "rules": { ".read": false, ".write": false, "users": {

    ".read": "auth != null", "$user_id": { ".write": "auth != null && auth.uid === $user_id" } }, "messages": { ".read": "auth != null", ".indexOn": ["timestamp"], "$message_id": { ".write": "(auth != null && auth.uid === newData.child('senderUid').val()) || (auth != null && auth.uid === data.child('senderUid').val())" } } }, }
  87. ׉ך➭5JQT { "rules": { ".read": false, ".write": false, "users": {

    ".read": "auth != null", "$user_id": { ".write": "auth != null && auth.uid === $user_id" } }, "messages": { ".read": "auth != null", ".indexOn": ["timestamp"], "$message_id": { ".write": "(auth != null && auth.uid === newData.child('senderUid').val()) || (auth != null && auth.uid === data.child('senderUid').val())" } } }, } 钠鏾幥׫
  88. ׉ך➭5JQT { "rules": { ".read": false, ".write": false, "users": {

    ".read": "auth != null", "$user_id": { ".write": "auth != null && auth.uid === $user_id" } }, "messages": { ".read": "auth != null", ".indexOn": ["timestamp"], "$message_id": { ".write": "(auth != null && auth.uid === newData.child('senderUid').val()) || (auth != null && auth.uid === data.child('senderUid').val())" } } }, } 倜׃ֻ剅ֹ鴥ת׸׷ر٦ة
  89. ׉ך➭5JQT { "rules": { ".read": false, ".write": false, "users": {

    ".read": "auth != null", "$user_id": { ".write": "auth != null && auth.uid === $user_id" } }, "messages": { ".read": "auth != null", ".indexOn": ["timestamp"], "$message_id": { ".write": "(auth != null && auth.uid === newData.child('senderUid').val()) || (auth != null && auth.uid === data.child('senderUid').val())" } } }, } ֿ׸ַ׵⵴ꤐׅ׷ر٦ة