Skip to content

Latest commit

 

History

History
349 lines (314 loc) · 9.92 KB

20160502_firebase.md

File metadata and controls

349 lines (314 loc) · 9.92 KB

Firebase

prototype TasteEmAll

  • ref = someUrlWithTasteEmAll
TasteEmAll/
	producers/
	
	drinks/type/
	OR
	drinks/
		drink
			drinkType=$generic
			
	reviews/
		$userName/
			$review1
	
	users/
		user1
			name=frank
  • on first start: getSharedPref(userName) => UserNameActivity / SettingsActivity
    • want to share your reviews? - yes => insert username in firebase
    • want to search friends? - registered users view
  • in reviews: name prefilled with getSharedPref(userName), other name possible...?
    • multiple logins?
  • on save (if activated in settings) => update in firebase
    • small pics? (later)
  • integrate other users...
    • query all users anywhere in settings? vs local pairing with shared secret...
    • abonnement per user possible = friend
    • onStart
      • 5 new users are registered - show them
        • registered users view
      • 3 new reviews from friends - show them (complicated query...?)
        • recent activities view

creation

class based

Firebase alanRef = ref.child("users").child("alanisawesome");
User alan = new User("Alan Turing", 1912);
alanRef.setValue(alan);

dynamic

//Referencing the child node using a .child() on it's parent node
alansRef.child("fullName").setValue("Alan Turing");
alansRef.child("birthYear").setValue(1912);

result

{
  "users": {
	"alanisawesome": {
	  "birthYear": "1912",
	  "fullName": "Alan Turing"
	}
  }
}

Map and updates

map usage

Firebase usersRef = ref.child("users");
Map<String, String> alanisawesomeMap = new HashMap<String, String>();
alanisawesomeMap.put("birthYear", "1912");
alanisawesomeMap.put("fullName", "Alan Turing");
Map<String, Map<String, String>> users = new HashMap<String, Map<String, String>>();
users.put("alanisawesome", alanisawesomeMap);
usersRef.setValue(users);

updateChildren

Firebase alanRef = usersRef.child("alanisawesome");
Map<String, Object> nickname = new HashMap<String, Object>();
nickname.put("nickname", "Alan The Machine");
alanRef.updateChildren(nickname);

completion callback

ref.setValue("I'm writing data", new Firebase.CompletionListener() {
	@Override
	public void onComplete(FirebaseError firebaseError, Firebase firebase) {
		if (firebaseError != null) {
			System.out.println("Data could not be saved. " + firebaseError.getMessage());
		} else {
			System.out.println("Data saved successfully.");
		}
	}
});

multi user simultaniously

use push (timestamp-based)

Firebase postRef = ref.child("posts");
Map<String, String> post1 = new HashMap<String, String>();
post1.put("author", "gracehop");
post1.put("title", "Announcing COBOL, a New Programming Language");
postRef.push().setValue(post1);
Map<String, String> post2 = new HashMap<String, String>();
post2.put("author", "alanisawesome");
post2.put("title", "The Turing Machine");
postRef.push().setValue(post2);

result

{
  "posts": {
	"-JRHTHaIs-jNPLXOQivY": {
	  "author": "gracehop",
	  "title": "Announcing COBOL, a New Programming Language"
	},
	"-JRHTHaKuITFIhnj02kE": {
	  "author": "alanisawesome",
	  "title": "The Turing Machine"
	}
  }
}

getting unique generated ids

// Generate a reference to a new location and add some data using push()
Firebase postRef = ref.child("posts");
Firebase newPostRef = postRef.push();
// Add some data to the new location
Map<String, String> post1 = new HashMap<String, String>();
post1.put("author", "gracehop");
post1.put("title", "Announcing COBOL, a New Programming Language");
newPostRef.setValue(post1);
// Get the unique ID generated by push()
String postId = newPostRef.getKey();

reading / handle changes from firebase

with PoJo-classes

Value

read a static snapshot of the contents - triggered once with initial data and every time the data changes

// Get a reference to our posts
Firebase ref = new Firebase("https://docs-examples.firebaseio.com/web/saving-data/fireblog/posts");
// Attach an listener to read the data at our posts reference
ref.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot snapshot) {
	  System.out.println("There are " + snapshot.getChildrenCount() + " blog posts");
	  for (DataSnapshot postSnapshot: snapshot.getChildren()) {
		BlogPost post = postSnapshot.getValue(BlogPost.class);
		System.out.println(post.getAuthor() + " - " + post.getTitle());
	  }
  }
  @Override
  public void onCancelled(FirebaseError firebaseError) {
	  System.out.println("The read failed: " + firebaseError.getMessage());
  }
});

Child manipulated

// Get a reference to our posts
Firebase ref = new Firebase("https://docs-examples.firebaseio.com/web/saving-data/fireblog/posts");
ref.addChildEventListener(new ChildEventListener() {
	// Retrieve new posts as they are added to the database
	@Override
	public void onChildAdded(DataSnapshot snapshot, String previousChildKey) {
		BlogPost newPost = snapshot.getValue(BlogPost.class);
		System.out.println("Author: " + newPost.getAuthor());
		System.out.println("Title: " + newPost.getTitle());
	}
	//... ChildEventListener also defines onChildChanged, onChildRemoved,
	//    onChildMoved and onCanceled, covered in later sections.
	
	// Get the data on a post that has changed
	@Override
	public void onChildChanged(DataSnapshot snapshot, String previousChildKey) {
		String title = (String) snapshot.child("title").getValue();
		System.out.println("The updated post title is " + title);
	}
	
	// Get the data on a post that has been removed
	@Override
	public void onChildRemoved(DataSnapshot snapshot) {
		String title = (String) snapshot.child("title").getValue();
		System.out.println("The blog post titled " + title + " has been deleted");
	}
	
});

Detaching Callbacks

ref.removeEventListener(originalListener);

Reading Data Once (and immediately remove)

ref.addListenerForSingleValueEvent(new ValueEventListener() {
	@Override
	public void onDataChange(DataSnapshot snapshot) {
		// do some stuff once
	}
	@Override
	public void onCancelled(FirebaseError firebaseError) {
	}
});

Querying

4 Ordering functions

  • by child key
  • by key name
  • by value
  • by priority

5 methods to conduct complex queries

  • limitToFirst()
  • limitToLast()
  • startAt()
  • endAt()
  • equalTo()

sampleData

{
  "lambeosaurus": {
	"height" : 2.1,
	"length" : 12.5,
	"weight": 5000
  },
  "stegosaurus": {
	"height" : 4,
	"length" : 9,
	"weight" : 2500
  }
}

ordering by a specified child key

  • if child-key does not exist: value = null - comes first in the ordering
  • Queries can only order by one key at a time.
Firebase ref = new Firebase("https://dinosaur-facts.firebaseio.com/dinosaurs");
Query queryRef = ref.orderByChild("height");
// Query queryRef = ref.orderByChild("weight").limitToLast(2); // heaviest 2 dinosaurs
// Query queryRef = ref.orderByChild("height").limitToFirst(2); // smallest 2 dinosaurs
queryRef.addChildEventListener(new ChildEventListener() {
	@Override
	public void onChildAdded(DataSnapshot snapshot, String previousChild) {
		DinosaurFacts facts = snapshot.getValue(DinosaurFacts.class);
		System.out.println(snapshot.getKey() + " was " + facts.getHeight() + " meters tall");
	}
});

ordering by key name

  • reads all dinosaurs in alphabetical order
Firebase ref = new Firebase("https://dinosaur-facts.firebaseio.com/dinosaurs");
Query queryRef = ref.orderByKey();
queryRef.addChildEventListener(new ChildEventListener() {
	@Override
	public void onChildAdded(DataSnapshot snapshot, String previousChild) {
		System.out.println(snapshot.getKey());
	}
});

ordering by value

{
  "scores": {
	"bruhathkayosaurus" : 55,
	"lambeosaurus" : 21,
	"linhenykus" : 80,
	"pterodactyl" : 93,
	"stegosaurus" : 5,
	"triceratops" : 22
  }
}

java:
Query queryRef = scoresRef.orderByValue();
...
      System.out.println("The " + snapshot.getKey() + " dinosaur's score is " + snapshot.getValue());

range queries

  • startAt(), endAt() are inclusive and can be combined...
Firebase ref = new Firebase("https://dinosaur-facts.firebaseio.com/dinosaurs");
Query queryRef = ref.orderByChild("height").startAt(3);
queryRef.addChildEventListener(new ChildEventListener() {
	@Override
	public void onChildAdded(DataSnapshot snapshot, String previousChild) {
		System.out.println(snapshot.getKey());
	}
});

complicated example

  • find the name of the dinosaur that is just shorter than Stegosaurus:
final Firebase ref = new Firebase("https://dinosaur-facts.firebaseio.com/dinosaurs");
ref.child("stegosaurus").child("height").addListenerForSingleValueEvent(new ValueEventListener() {
	@Override
	public void onDataChange(DataSnapshot stegosaurusHeightSnapshot) {
		Long favoriteDinoHeight = stegosaurusHeightSnapshot.getValue(Long.class);
		Query queryRef = ref.orderByChild("height").endAt(favoriteDinoHeight).limitToLast(2);
		queryRef.addListenerForSingleValueEvent(new ValueEventListener() {
			@Override
			public void onDataChange(DataSnapshot querySnapshot) {
				if (querySnapshot.getChildrenCount() == 2) {
					// Data is ordered by increasing height, so we want the first entry
					DataSnapshot dinosaur = querySnapshot.getChildren().iterator().next();
					System.out.println("The dinosaur just shorter than the stegasaurus is " + dinosaur.getKey());
				} else {
					System.out.println("The stegosaurus is the shortest dino");
				}
			}
			@Override
			public void onCancelled(FirebaseError error) {
			}
		});
	}
	@Override
	public void onCancelled(FirebaseError error) {
	}
});

real ordering in firebase