com.firebase.client.DataSnapshot Java Examples

The following examples show how to use com.firebase.client.DataSnapshot. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DrawingActivity.java    From AndroidDrawing with MIT License 6 votes vote down vote up
@Override
public void onStart() {
    super.onStart();
    // Set up a notification to let us know when we're connected or disconnected from the Firebase servers
    mConnectedListener = mFirebaseRef.getRoot().child(".info/connected").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            boolean connected = (Boolean) dataSnapshot.getValue();
            if (connected) {
                Toast.makeText(DrawingActivity.this, "Connected to Firebase", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(DrawingActivity.this, "Disconnected from Firebase", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            // No-op
        }
    });
}
 
Example #2
Source File: DataPresenter.java    From animation-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a data presenter.
 *
 * @param dataView The view which will display the data.
 * @param configUrl The firebase endpoint url.
 */
DataPresenter(@NonNull DataView<T> dataView, @NonNull String configUrl) {
    mFirebase = new Firebase(configUrl);
    mData = new ArrayList<>();
    mDataView = dataView;

    mValueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            mData.clear();
            for (DataSnapshot data : dataSnapshot.getChildren()) {
                // Data parsing is being done within the extending classes.
                mData.add(parseData(data));
            }
            mDataView.showData(mData);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            Log.d(TAG, "onCancelled: " + firebaseError.getMessage());
            // Deliberately swallow the firebase error here.
            mDataView.showError();
        }
    };
}
 
Example #3
Source File: MapsActivity.java    From io2015-codelabs with Apache License 2.0 6 votes vote down vote up
/**
 * Act upon new check-outs when they appear.
 */
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
    String placeId = dataSnapshot.getKey();
    if (placeId != null) {
        Places.GeoDataApi
                .getPlaceById(mGoogleApiClient, placeId)
                .setResultCallback(new ResultCallback<PlaceBuffer>() {
                           @Override
                           public void onResult(PlaceBuffer places) {
                               LatLng location = places.get(0).getLatLng();
                               addPointToViewPort(location);
                               mMap.addMarker(new MarkerOptions().position(location));
                               places.release();
                           }
                       }
                );
    }
}
 
Example #4
Source File: MainActivity.java    From AndroidChat with MIT License 5 votes vote down vote up
@Override
public void onStart() {
    super.onStart();
    // Setup our view and list adapter. Ensure it scrolls to the bottom as data changes
    final ListView listView = getListView();
    // Tell our list adapter that we only want 50 messages at a time
    mChatListAdapter = new ChatListAdapter(mFirebaseRef.limit(50), this, R.layout.chat_message, mUsername);
    listView.setAdapter(mChatListAdapter);
    mChatListAdapter.registerDataSetObserver(new DataSetObserver() {
        @Override
        public void onChanged() {
            super.onChanged();
            listView.setSelection(mChatListAdapter.getCount() - 1);
        }
    });

    // Finally, a little indication of connection status
    mConnectedListener = mFirebaseRef.getRoot().child(".info/connected").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            boolean connected = (Boolean) dataSnapshot.getValue();
            if (connected) {
                Toast.makeText(MainActivity.this, "Connected to Firebase", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MainActivity.this, "Disconnected from Firebase", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            // No-op
        }
    });
}
 
Example #5
Source File: DetailPresenter.java    From animation-samples with Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
protected Detail parseData(DataSnapshot data) {
        String title = data.child(JsonKeys.TITLE).getValue(String.class);
        String description = data.child(JsonKeys.DESCRIPTION).getValue(String.class);
        LatLng latLng = DataUtils.readLatLng(data);
        DataSnapshot location = data.child(JsonKeys.LOCATION);
        Float tilt = location.child(JsonKeys.TILT).getValue(Float.class);
        Float bearing = location.child(JsonKeys.BEARING).getValue(Float.class);
    return new Detail(title, description, latLng, tilt, bearing);
}
 
Example #6
Source File: GalleryPresenter.java    From animation-samples with Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
protected Gallery parseData(DataSnapshot data) {
    String title = data.child(JsonKeys.TITLE).getValue(String.class);
    String description = data.child(JsonKeys.DESCRIPTION).getValue(String.class);
    String galleryId = data.child(JsonKeys.GALLERY_ID).getValue(String.class);
    LatLng latLng = DataUtils.readLatLng(data);
    return new Gallery(title, description, galleryId, latLng);
}
 
Example #7
Source File: forum.java    From Krishi-Seva with MIT License 5 votes vote down vote up
public void read()
{

    final Firebase ref = new Firebase("https://adaa-45b17.firebaseio.com/FORUMS/");
    //Value event listener for realtime data update

    ref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot usersSnapshot) {

            for (DataSnapshot userSnapshot : usersSnapshot.getChildren()) {
                foru user = userSnapshot.getValue(foru.class);

               String post = user.getPost().toString();
                chatView.addMessage(new ChatMessage(post, System.currentTimeMillis(), ChatMessage.Type.RECEIVED));

            }

        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            System.out.println("The read failed: " + firebaseError.getMessage());
        }
    });

}
 
Example #8
Source File: orders.java    From Krishi-Seva with MIT License 5 votes vote down vote up
public void read()
{
    final Firebase ref = new Firebase("https://adaa-45b17.firebaseio.com/ORDERS");
    //Value event listener for realtime data update


    ref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot usersSnapshot) {

            for (DataSnapshot userSnapshot : usersSnapshot.getChildren()) {
                ordering forums = userSnapshot.getValue(ordering.class);
                String amount = forums.getAmount().toString();
                String crop = forums.getCrop().toString();
                String lat = forums.getLat();
                String longg = forums.getLongg();
                String kgs= forums.getKgs();
                String l= forums.getLoc();
                location.add(l);
                amountt.add(amount);
                cropp.add(crop);
                latt.add(lat);
                longgg.add(longg);
                kg.add(kgs);

            }
            cardpop();
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            System.out.println("The read failed: " + firebaseError.getMessage());
        }
    });

}
 
Example #9
Source File: DrawingActivity.java    From AndroidDrawing with MIT License 5 votes vote down vote up
/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent = getIntent();
    final String url = intent.getStringExtra("FIREBASE_URL");
    final String boardId = intent.getStringExtra("BOARD_ID");
    Log.i(TAG, "Adding DrawingView on "+url+" for boardId "+boardId);
    mFirebaseRef = new Firebase(url);
    mBoardId = boardId;
    mMetadataRef = mFirebaseRef.child("boardmetas").child(boardId);
    mSegmentsRef = mFirebaseRef.child("boardsegments").child(mBoardId);
    mMetadataRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (mDrawingView != null) {
                ((ViewGroup) mDrawingView.getParent()).removeView(mDrawingView);
                mDrawingView.cleanup();
                mDrawingView = null;
            }
            Map<String, Object> boardValues = (Map<String, Object>) dataSnapshot.getValue();
            if (boardValues != null && boardValues.get("width") != null && boardValues.get("height") != null) {
                mBoardWidth = ((Long) boardValues.get("width")).intValue();
                mBoardHeight = ((Long) boardValues.get("height")).intValue();

                mDrawingView = new DrawingView(DrawingActivity.this, mFirebaseRef.child("boardsegments").child(boardId), mBoardWidth, mBoardHeight);
                setContentView(mDrawingView);
            }
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            // No-op
        }
    });
}
 
Example #10
Source File: FirebaseListFragment.java    From MangoBloggerAndroidApp with Mozilla Public License 2.0 5 votes vote down vote up
private void downloadTermsViaFirebase() {
    mProgressBar.setVisibility(View.VISIBLE);
    mProgressBar.setEnabled(true);
    mFirebaseRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            mBlogList.clear();
            for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {

                BlogModel blogModel = dataSnapshot1.getValue(BlogModel.class);
                mBlogList.add(blogModel);

            }

            setupAdapter();
            mProgressBar.setEnabled(false);
            mProgressBar.setVisibility(View.GONE);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });

}
 
Example #11
Source File: MainActivity.java    From io16experiment-master with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new user in Firebase from the Java POJO
 */
private void createUserInFirebaseHelper(final String authUid) {
    final Firebase userLocation = new Firebase(Constants.FIREBASE_URL_USERS).child(authUid);

    // See if there is already a user (for example, if they already logged in with an associated Google account.
    userLocation.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // If there is no user, make one
            LogUtils.LOGE("***> userLocation", "single value event - " + dataSnapshot.getValue());
            if (dataSnapshot.getValue() == null) {
                // Set raw version of date to the ServerValue.TIMESTAMP value and save into dateCreatedMap
                HashMap<String, Object> timestampJoined = new HashMap<>();
                timestampJoined.put(Constants.FIREBASE_PROPERTY_TIMESTAMP, ServerValue.TIMESTAMP);

                User newUser = new User(authUid, timestampJoined);
                userLocation.setValue(newUser);

                LogUtils.LOGE("***> add new user", authUid);
                PreferencesUtils.setInt(mActivity, R.string.key_device_number, 1);
            }
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            LogUtils.LOGE(MainActivity.class.getSimpleName(), getString(R.string.log_error_occurred) + firebaseError.getMessage());
        }
    });
}
 
Example #12
Source File: MessageFragment.java    From io16experiment-master with Apache License 2.0 4 votes vote down vote up
/**
 * Retrieve the next device from Firebase and generate the appropriate message
 */
private void getNextDeviceFirebase() {
    // Retrieve next deviceId from Firebase
    Firebase nextDeviceRef = new Firebase(Constants.FIREBASE_URL_DEVICES).child(mFirebaseUid);
    Query queryRef = nextDeviceRef.orderByChild(Constants.FIREBASE_PROPERTY_DEVICE_NUMBER).equalTo(mDeviceNum + 1);
    queryRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot item : dataSnapshot.getChildren()) {
                Device d = item.getValue(Device.class);
                if (d != null) {
                    LogUtils.LOGE("***> child updated", "device connected: " + d.isConnected());
                    // If the device has connected to the parent uid, handle the message display based on whether
                    // the message has been received by the child device
                    if (d.isConnected()) {
                        if (!PreferencesUtils.getBoolean(mActivity, R.string.key_message_received, false)){
                            PreferencesUtils.setBoolean(mActivity, R.string.key_message_received, true);

                            // Once the message has been received by the child device, unpublish the message so the
                            // next device can begin broadcasting
                            unpublish();
                            mDiscover.setVisibility(View.GONE);
                            mIntroConnectDevice.setText(mActivity.getString(R.string.text_message_received));
                        }
                    } else {
                        // The device has not been connected yet, so generate the message to be sent and prepare
                        // to publish
                        LogUtils.LOGE("***> child updated", "device: " + d.getDeviceId());

                        // Update message
                        String message = mActivity.getString(R.string.message_body, mFirebaseUid, mDeviceNum + 1,
                                mTotalDevices, d.getDeviceId());
                        LogUtils.LOGE("***> child message", message);
                        mDeviceInfoMessage = DeviceMessage.newNearbyMessage(
                                InstanceID.getInstance(mActivity.getApplicationContext()).getId(), message);
                    }
                }
            }
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
        }
    });
}
 
Example #13
Source File: MapsActivity.java    From io2015-codelabs with Apache License 2.0 4 votes vote down vote up
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
    // TODO
}
 
Example #14
Source File: MapsActivity.java    From io2015-codelabs with Apache License 2.0 4 votes vote down vote up
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
    // TODO
}
 
Example #15
Source File: MapsActivity.java    From io2015-codelabs with Apache License 2.0 4 votes vote down vote up
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
    // TODO
}
 
Example #16
Source File: HelloAndroidActivity.java    From android-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Called when the activity is first created.
 * 
 * @param savedInstanceState
 *            If the activity is being re-initialized after previously being
 *            shut down then this Bundle contains the data it most recently
 *            supplied in onSaveInstanceState(Bundle). <b>Note: Otherwise it
 *            is null.</b>
 */
@Override
public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	
	// Retrieve components
	final ListView listView = (ListView)findViewById(R.id.messagesListView);
	ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
	listView.setAdapter(adapter);

	final EditText msgText = (EditText)findViewById(R.id.msgEditText);
	Button sendButton = (Button)findViewById(R.id.sendButton);
	
	// setting context to firebase
	Firebase.setAndroidContext(this);
    myFirebaseRef = new Firebase("https://anaware.firebaseio.com/");
    myFirebaseRef.child("message").addValueEventListener(new ValueEventListener() {
	        public void onDataChange(DataSnapshot snapshot) {
	        	if (snapshot.getValue() != null) {
	        		Map<String, Object> newPost = (Map<String, Object>) snapshot.getValue();
	        		list.clear();
	        		for (String post : newPost.keySet())
	        		{
	        			list.add(post + "\r\n" + newPost.get(post));
	        		}
	        		((BaseAdapter) listView.getAdapter()).notifyDataSetChanged(); 
	        	}
	        }
	        
        	public void onCancelled(FirebaseError error) {
        		// TODO
        	}
        });
    
	// Add events
	sendButton.setOnClickListener(new OnClickListener() {
		public void onClick(View v) {
			if (!msgText.getText().toString().equals("")) {
			    myFirebaseRef.child("message").child((new Date()).toString()).setValue(msgText.getText().toString());
			    msgText.setText("");
			}
		}
	});
}
 
Example #17
Source File: EndOfGameActivity.java    From cloud-cup-android with Apache License 2.0 4 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    state = GameState.DONE;
    Log.d(LOG_TAG, "End of game!!");

    super.onCreate(savedInstanceState);
    setContentView(R.layout.end_of_game);

    winnerNameView = (TextView) findViewById(R.id.winner_name);
    winnerImage = (ImageView) findViewById(R.id.winner_image);

    playersRef = new Firebase(Consts.FIREBASE_URL + "/room/" + code + "/players");
    playersRef.addValueEventListener(new ValueEventListener() {
        int maxScore = 0;
        String winnerName = "";
        String winnerImageUrl = "";
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.d(LOG_TAG, dataSnapshot.getValue().toString());
            for (final DataSnapshot player: dataSnapshot.getChildren()) {
                int score = Integer.parseInt(player.child("score").getValue().toString());
                if (score > maxScore) {
                    maxScore = score;
                    winnerName = player.child("name").getValue().toString();
                    winnerImageUrl = player.child("imageUrl").getValue().toString();
                }
            }
            Log.d(LOG_TAG, "winner is " + winnerName + "with score " + maxScore);
            winnerNameView.setText(winnerName + " won!");
            if (!winnerImageUrl.isEmpty()) {
                new DownloadImageAsyncTask().execute(Uri.parse(winnerImageUrl));
            }
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
        }
    });


    stateRef = new Firebase(Consts.FIREBASE_URL + "/room/" + code + "/state");
    currentGameRef = new Firebase(Consts.FIREBASE_URL + "/room/" + code + "/currentGame");


    final ImageButton button = (ImageButton) findViewById(R.id.startButton);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            stateRef.setValue("restarted");
        }
    });

}
 
Example #18
Source File: MessageFragment.java    From io16experiment-master with Apache License 2.0 4 votes vote down vote up
/**
 * Setup Firebase for the user and connected devices
 *
 * Update the existing user data with the number of devices selected on the previous screen
 * Add the devices based on the selection
 * Generate the message for the next device
 */
private void setupFirebase() {
    // Update Firebase to include the total number of devices
    if (!TextUtils.isEmpty(mFirebaseUid)) {
        Map<String, Object> profile = new HashMap<>();
        profile.put(Constants.FIREBASE_PROPERTY_NUMBER_DEVICES, mTotalDevices);

        Firebase userRef = new Firebase(Constants.FIREBASE_URL_USERS).child(mFirebaseUid);
        userRef.updateChildren(profile);
        LogUtils.LOGE("***> setupFirebase", "update firebase uid:" + mFirebaseUid);

        // Add device ids to Firebase
        for (int i = 0; i < PreferencesUtils.getInt(mActivity, R.string.key_total_devices, 1); i++) {
            // If the challengeCode is empty, then push a new value to the database
            Firebase deviceRef = new Firebase(Constants.FIREBASE_URL_DEVICES).child(mFirebaseUid);
            final Firebase newDeviceRef = deviceRef.push();

            mDeviceIds[i] = newDeviceRef.getKey();
            final int currentDeviceNumber = i + 1;

            LogUtils.LOGE("***> new device #" + currentDeviceNumber, mDeviceIds[i]);

            Device device = new Device(mDeviceIds[i], i + 1, mDeviceNum == currentDeviceNumber);
            newDeviceRef.setValue(device);
            newDeviceRef.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    Device d = dataSnapshot.getValue(Device.class);
                    if (d != null) {
                        LogUtils.LOGE("***> child updated", "id: " + d.getDeviceId());
                        LogUtils.LOGE("***> child updated", "number: " + d.getDeviceNumber());
                        LogUtils.LOGE("***> child updated", "connected: " + d.isConnected());
                        LogUtils.LOGE("***> child updated", "next: " + currentDeviceNumber);

                        // Hide the button and show the message for the first device
                        if (d.isConnected() && d.getDeviceNumber() > 1) {
                            PreferencesUtils.setBoolean(mActivity, R.string.key_message_received, true);

                            LogUtils.LOGE("***> child updated", "unpublished: " + currentDeviceNumber);
                            unpublish();
                            mDiscover.setVisibility(View.GONE);
                            mIntroConnectDevice.setText(mActivity.getString(R.string.text_message_received));
                        }
                    } else {
                        if (!PreferencesUtils.getBoolean(mActivity, R.string.key_device_reset_done, false)) {
                            LogUtils.LOGE("***> setupFirebase", "reset device");
                            MainActivity.resetDevice();
                        }
                    }
                }

                @Override
                public void onCancelled(FirebaseError firebaseError) {

                }
            });

            // Create the message for the next device
            if (i == mDeviceNum) {
                LogUtils.LOGE("***> device", "message created");
                String message = mActivity.getString(R.string.message_body, mFirebaseUid, mDeviceNum + 1,
                        mTotalDevices, newDeviceRef.getKey());
                mDeviceInfoMessage = DeviceMessage.newNearbyMessage(
                        InstanceID.getInstance(mActivity.getApplicationContext()).getId(), message);
            }
        }
    }
}
 
Example #19
Source File: MessageFragment.java    From io16experiment-master with Apache License 2.0 4 votes vote down vote up
/**
 * Handle the incoming message from the nearby device. Parse the message to retrieve the appropriate data.
 */
private void handleIncomingMessage(Message message) {
    LogUtils.LOGE("***> message", DeviceMessage.fromNearbyMessage(message).getMessageBody());

    String[] messageParts = DeviceMessage.fromNearbyMessage(message).getMessageBody().split(Pattern.quote("|"));

    if (messageParts.length == 0) {
        LogUtils.LOGE("***> error", "error parsing message");
        return;
    }

    mFirebaseUid = messageParts[0];
    mDeviceNum = Integer.valueOf(messageParts[1]);
    mTotalDevices = Integer.valueOf(messageParts[2]);
    String deviceId = messageParts[3];

    if (!PreferencesUtils.getBoolean(mActivity, R.string.key_is_connected, false)) {
        // Update Firebase and remove the old FirebaseUid
        String currentFirebaseUid = PreferencesUtils.getString(mActivity, R.string.key_firebase_uid, "");
        LogUtils.LOGE("***> handleIncomingMessage", "remove firebase uid:" + currentFirebaseUid);
        Firebase userChallengeRef = new Firebase(Constants.FIREBASE_URL_USERS).child(currentFirebaseUid);
        userChallengeRef.removeValue();
    }

    // Update the shared preferences
    PreferencesUtils.setString(mActivity, R.string.key_firebase_uid, mFirebaseUid);
    PreferencesUtils.setInt(mActivity, R.string.key_total_devices, mTotalDevices);
    PreferencesUtils.setInt(mActivity, R.string.key_device_number, mDeviceNum);
    PreferencesUtils.setBoolean(mActivity, R.string.key_is_connected, true);

    // Display the message
    displayMessage();

    // Update the background color
    setInitialValues();

    // Generate next message, based on Firebase
    getNextDeviceFirebase();

    // Update connected status on Firebase
    Map<String, Object> device = new HashMap<>();
    device.put(Constants.FIREBASE_PROPERTY_CONNECTED, true);

    Firebase deviceRef = new Firebase(Constants.FIREBASE_URL_DEVICES).child(mFirebaseUid).child(deviceId);
    deviceRef.updateChildren(device);
    deviceRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Device d = dataSnapshot.getValue(Device.class);
            LogUtils.LOGE("***> deviceRef", "here");
            if (d == null) {
                LogUtils.LOGE("***> setupFirebase", "reset device");
                MainActivity.resetDevice();
            }
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });

    if (mDeviceNum < mTotalDevices) {
        // Change the display text
        mIntroConnectDevice.setText(mActivity.getString(R.string.text_connect_device, mDeviceNum + 1));

        // Change text/button action
        mDiscover.setOnClickListener(mConnectedClickListener);
    } else {
        mIntroConnectDevice.setVisibility(View.GONE);
        mDiscover.setVisibility(View.GONE);
    }

    unsubscribe();
}
 
Example #20
Source File: CloudManager.java    From thunderboard-android with Apache License 2.0 4 votes vote down vote up
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
    isRootDataSessionsAvailable = dataSnapshot.getValue(Boolean.class);
    firebaseMonitor.onNext(isRootDataSessionsAvailable);
    Timber.d("Firebase available: %s", isRootDataSessionsAvailable);
}
 
Example #21
Source File: FirebaseDB.java    From appinventor-extensions with Apache License 2.0 4 votes vote down vote up
/**
 * GetValue asks Firebase to get the value stored under the given tag.
 * It will pass valueIfTagNotThere to GotValue if there is no value stored
 * under the tag.
 *
 * @param tag The tag whose value is to be retrieved.
 * @param valueIfTagNotThere The value to pass to the event if the tag does
 *                           not exist.
 */
@SimpleFunction
public void GetValue(final String tag, final Object valueIfTagNotThere) {
  this.myFirebase.child(tag).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(final DataSnapshot snapshot) {
      final AtomicReference<Object> value = new AtomicReference<Object>();

      // Set value to either the JSON from the Firebase
      // or the JSON representation of valueIfTagNotThere
      try {
        if (snapshot.exists()) {
          value.set(snapshot.getValue());
        } else {
          value.set(JsonUtil.getJsonRepresentation(valueIfTagNotThere));
        }
      } catch(JSONException e) {
        throw new YailRuntimeError("Value failed to convert to JSON.", "JSON Creation Error.");
      }

      androidUIHandler.post(new Runnable() {
        public void run() {
          // Signal an event to indicate that the value was
          // received.  We post this to run in the Application's main
          // UI thread.
          GotValue(tag, value.get());
        }
      });
    }

    @Override
    public void onCancelled(final FirebaseError error) {
      androidUIHandler.post(new Runnable() {
        public void run() {
          // Signal an event to indicate that an error occurred.
          // We post this to run in the Application's main
          // UI thread.
          FirebaseError(error.getMessage());
        }
      });
    }
  });
}
 
Example #22
Source File: DataUtils.java    From animation-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Read latitude and longitude data from a snapshot's child called {@link JsonKeys#LOCATION}.
 */
public static @NonNull LatLng readLatLng(@NonNull DataSnapshot snapshot) {
    final DataSnapshot location = snapshot.child(JsonKeys.LOCATION);
    double lat = location.child(JsonKeys.LATITUDE).getValue(Double.class);
    double lng = location.child(JsonKeys.LONGITUDE).getValue(Double.class);
    return new LatLng(lat, lng);
}
 
Example #23
Source File: DataPresenter.java    From animation-samples with Apache License 2.0 4 votes vote down vote up
@NonNull
protected abstract T parseData(DataSnapshot data);