Search in sources :

Example 51 with DatabaseReference

use of com.google.firebase.database.DatabaseReference in project Lets-Chat by kshitiz1007.

the class ChatActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_chat);
    mChatAddButton = (ImageButton) findViewById(R.id.chatAddButton);
    mChatSendButton = (ImageButton) findViewById(R.id.chatSendButton);
    mMessageView = (EditText) findViewById(R.id.chatMessageView);
    // -----GETING FROM INTENT----
    mChatUser = getIntent().getStringExtra("user_id");
    String userName = getIntent().getStringExtra("user_name");
    // ---SETTING ONLINE------
    mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("users");
    // ----ADDING ACTION BAR-----
    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    actionBar.setDisplayHomeAsUpEnabled(true);
    // ---INFLATING APP BAR LAYOUT INTO ACTION BAR----
    LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
    View actionBarView = inflater.inflate(R.layout.app_bar_layout, null);
    actionBar.setCustomView(actionBarView);
    // ---ADDING DATA ON ACTION BAR----
    mUserName = (TextView) actionBarView.findViewById(R.id.textView3);
    mUserLastSeen = (TextView) actionBarView.findViewById(R.id.textView5);
    mUserImage = (CircleImageView) actionBarView.findViewById(R.id.circleImageView);
    mUserName.setText(userName);
    mRootReference = FirebaseDatabase.getInstance().getReference();
    mImageStorage = FirebaseStorage.getInstance().getReference();
    mAuth = FirebaseAuth.getInstance();
    mCurrentUserId = mAuth.getCurrentUser().getUid();
    mMessageAdapter = new MessageAdapter(messagesList);
    mMessagesList = (RecyclerView) findViewById(R.id.recycleViewMessageList);
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.message_swipe_layout);
    mLinearLayoutManager = new LinearLayoutManager(ChatActivity.this);
    // mMessagesList.setHasFixedSize(true);
    mMessagesList.setLayoutManager(mLinearLayoutManager);
    mMessagesList.setAdapter(mMessageAdapter);
    loadMessages();
    // ----ADDING LAST SEEN-----
    mRootReference.child("users").child(mChatUser).addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String onlineValue = dataSnapshot.child("online").getValue().toString();
            String imageValue = dataSnapshot.child("thumb_image").getValue().toString();
            Picasso.with(ChatActivity.this).load(imageValue).placeholder(R.drawable.user_img).into(mUserImage);
            if (onlineValue.equals("true")) {
                mUserLastSeen.setText("online");
            } else {
                GetTimeAgo getTimeAgo = new GetTimeAgo();
                long lastTime = Long.parseLong(onlineValue);
                String lastSeen = getTimeAgo.getTimeAgo(lastTime, getApplicationContext());
                mUserLastSeen.setText(lastSeen);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
    // ----ADDING SEEN OF MESSAGES----
    mRootReference.child("chats").child(mCurrentUserId).addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (!dataSnapshot.hasChild(mChatUser)) {
                Map chatAddMap = new HashMap();
                chatAddMap.put("seen", false);
                chatAddMap.put("time_stamp", ServerValue.TIMESTAMP);
                Map chatUserMap = new HashMap();
                chatUserMap.put("chats/" + mChatUser + "/" + mCurrentUserId, chatAddMap);
                chatUserMap.put("chats/" + mCurrentUserId + "/" + mChatUser, chatAddMap);
                mRootReference.updateChildren(chatUserMap, new DatabaseReference.CompletionListener() {

                    @Override
                    public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                        if (databaseError == null) {
                            Toast.makeText(getApplicationContext(), "Successfully Added chats feature", Toast.LENGTH_SHORT).show();
                        } else
                            Toast.makeText(getApplicationContext(), "Cannot Add chats feature", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(getApplicationContext(), "Something went wrong.. Please go back..", Toast.LENGTH_SHORT).show();
        }
    });
    // ----SEND MESSAGE--BUTTON----
    mChatSendButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            String message = mMessageView.getText().toString();
            if (!TextUtils.isEmpty(message)) {
                String current_user_ref = "messages/" + mCurrentUserId + "/" + mChatUser;
                String chat_user_ref = "messages/" + mChatUser + "/" + mCurrentUserId;
                DatabaseReference user_message_push = mRootReference.child("messages").child(mCurrentUserId).child(mChatUser).push();
                String push_id = user_message_push.getKey();
                Map messageMap = new HashMap();
                messageMap.put("message", message);
                messageMap.put("seen", false);
                messageMap.put("type", "text");
                messageMap.put("time", ServerValue.TIMESTAMP);
                messageMap.put("from", mCurrentUserId);
                Map messageUserMap = new HashMap();
                messageUserMap.put(current_user_ref + "/" + push_id, messageMap);
                messageUserMap.put(chat_user_ref + "/" + push_id, messageMap);
                mRootReference.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {

                    @Override
                    public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                        if (databaseError != null) {
                            Log.e("CHAT_ACTIVITY", "Cannot add message to database");
                        } else {
                            Toast.makeText(ChatActivity.this, "Message sent", Toast.LENGTH_SHORT).show();
                            mMessageView.setText("");
                        }
                    }
                });
            }
        }
    });
    /*
        //----THE WRAP CONTENT OF IMAGE VIEW IS GIVING ERROR--- SO REMOVING THIS FUNCTIONALITY-------


       mChatAddButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent galleryIntent=new Intent();
                galleryIntent.setType("image/*");
                galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(galleryIntent,"Select Image"),GALLERY_PICK);
            }
        });
        */
    // ----LOADING 10 MESSAGES ON SWIPE REFRESH----
    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

        @Override
        public void onRefresh() {
            itemPos = 0;
            mCurrentPage++;
            loadMoreMessages();
            ;
        }
    });
}
Also used : HashMap(java.util.HashMap) DatabaseReference(com.google.firebase.database.DatabaseReference) LinearLayoutManager(android.support.v7.widget.LinearLayoutManager) DataSnapshot(com.google.firebase.database.DataSnapshot) CircleImageView(de.hdodenhof.circleimageview.CircleImageView) View(android.view.View) RecyclerView(android.support.v7.widget.RecyclerView) TextView(android.widget.TextView) SwipeRefreshLayout(android.support.v4.widget.SwipeRefreshLayout) DatabaseError(com.google.firebase.database.DatabaseError) LayoutInflater(android.view.LayoutInflater) ValueEventListener(com.google.firebase.database.ValueEventListener) HashMap(java.util.HashMap) Map(java.util.Map) ActionBar(android.support.v7.app.ActionBar)

Example 52 with DatabaseReference

use of com.google.firebase.database.DatabaseReference in project BORED by invent2017.

the class ShowStory method addView.

public void addView() {
    DatabaseReference mStoryRef = FirebaseDatabase.getInstance().getReference().child("stories").child(STORY_KEY).child("Views");
    mStoryRef.runTransaction(new Transaction.Handler() {

        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            if (mutableData.getValue() != null) {
                int storyViews = mutableData.getValue(Integer.class);
                ++storyViews;
                mutableData.setValue(storyViews);
            }
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
        }
    });
    mDataRef.child("users").child(username).addListenerForSingleValueEvent(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (!(dataSnapshot.child("ReadStories").hasChild(STORY_KEY))) {
                dataSnapshot.child("ReadStories").child(STORY_KEY).getRef().setValue(STORY_KEY);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}
Also used : DatabaseError(com.google.firebase.database.DatabaseError) Transaction(com.google.firebase.database.Transaction) DatabaseReference(com.google.firebase.database.DatabaseReference) ValueEventListener(com.google.firebase.database.ValueEventListener) MutableData(com.google.firebase.database.MutableData) DataSnapshot(com.google.firebase.database.DataSnapshot)

Example 53 with DatabaseReference

use of com.google.firebase.database.DatabaseReference in project BORED by invent2017.

the class StoryFragment method addView.

public void addView() {
    DatabaseReference mStoryRef = FirebaseDatabase.getInstance().getReference().child("stories").child(storyKey).child("Views");
    mStoryRef.runTransaction(new Transaction.Handler() {

        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            if (mutableData.getValue() != null) {
                int storyViews = mutableData.getValue(Integer.class);
                ++storyViews;
                mutableData.setValue(storyViews);
            }
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
        }
    });
    mDataRef.child("users").child(username).addListenerForSingleValueEvent(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (!(dataSnapshot.child("ReadStories").hasChild(storyKey))) {
                dataSnapshot.child("ReadStories").child(storyKey).getRef().setValue(storyKey);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}
Also used : DatabaseError(com.google.firebase.database.DatabaseError) Transaction(com.google.firebase.database.Transaction) DatabaseReference(com.google.firebase.database.DatabaseReference) ValueEventListener(com.google.firebase.database.ValueEventListener) MutableData(com.google.firebase.database.MutableData) DataSnapshot(com.google.firebase.database.DataSnapshot)

Example 54 with DatabaseReference

use of com.google.firebase.database.DatabaseReference in project Devsfolio by Madonahs.

the class PostFeedFragment method uploadImageToServer.

public void uploadImageToServer() {
    // TODO 1: Enable sending images to DataBase
    // TODO 2: ensure we get the following
    /**
     * Post post = new post();
     * post.setUsername(name);
     * post.setSomethingElse(whatever);
     * Use the setters to populate the post.
     */
    Post post = new Post(postText.getText().toString(), "Madonahs", null);
    reference.push().setValue(post, new DatabaseReference.CompletionListener() {

        @Override
        public void onComplete(DatabaseError databaseError, DatabaseReference dataReference) {
            // String error = databaseError.toString();
            if (databaseError != null) {
                String error = databaseError.toString();
            }
        // Log.i("Firebase Debug", "The error is: " + databaseError.toString());
        }
    });
    postText.setText("");
    Toast.makeText(getContext(), "Sending Feeds", Toast.LENGTH_SHORT).show();
}
Also used : DatabaseError(com.google.firebase.database.DatabaseError) DatabaseReference(com.google.firebase.database.DatabaseReference) Post(com.madonasyombua.growwithgoogleteamproject.models.Post) BindString(butterknife.BindString)

Example 55 with DatabaseReference

use of com.google.firebase.database.DatabaseReference in project iosched by google.

the class RegistrationEndpoint method registrationStatus.

@ApiMethod(path = "status", httpMethod = ApiMethod.HttpMethod.GET)
public RegistrationResult registrationStatus(ServletContext context, @Named("firebaseUserToken") String firebaseUserToken) throws IOException, ForbiddenException, ExecutionException, InterruptedException, InternalServerErrorException {
    String databaseUrl = context.getInitParameter("databaseUrl");
    LOG.info("databaseUrl: " + databaseUrl);
    String serviceAccountKey = context.getInitParameter("accountKey");
    LOG.info("accountKey: " + serviceAccountKey);
    InputStream serviceAccount = context.getResourceAsStream(serviceAccountKey);
    LOG.info("serviceAccount: " + serviceAccount);
    firebaseWrapper.initFirebase(databaseUrl, serviceAccount);
    firebaseWrapper.authenticateFirebaseUser(firebaseUserToken);
    if (!firebaseWrapper.isUserAuthenticated()) {
        throw new ForbiddenException("Not authenticated");
    }
    boolean isRegistered = isUserRegistered(context);
    final TaskCompletionSource<Boolean> isRegisteredTCS = new TaskCompletionSource<>();
    final Task<Boolean> isRegisteredTCSTask = isRegisteredTCS.getTask();
    // Update the user registration state in the Real-time Database.
    DatabaseReference dbRef = firebaseWrapper.getDatabaseReference();
    int rtdbRetries = 0;
    while (rtdbRetries < RTDB_RETRY_LIMIT) {
        dbRef.child("users").child(firebaseWrapper.getUserId()).setValue(isRegistered).addOnCompleteListener(new OnCompleteListener<Void>() {

            @Override
            public void onComplete(Task<Void> task) {
                if (task.isSuccessful()) {
                    isRegisteredTCS.setResult(true);
                } else {
                    isRegisteredTCS.setResult(false);
                }
            }
        });
        // If writing to RTDB was successful break out.
        if (Tasks.await(isRegisteredTCSTask)) {
            break;
        }
        LOG.info("Writing to RTDB has failed.");
        rtdbRetries++;
    }
    // indeed registered.
    if (rtdbRetries >= RTDB_RETRY_LIMIT) {
        throw new InternalServerErrorException("Unable to write registration status to RTDB.");
    } else {
        // Return the user registration state.
        return new RegistrationResult(isRegistered);
    }
}
Also used : ForbiddenException(com.google.api.server.spi.response.ForbiddenException) DatabaseReference(com.google.firebase.database.DatabaseReference) InputStream(java.io.InputStream) TaskCompletionSource(com.google.firebase.tasks.TaskCompletionSource) InternalServerErrorException(com.google.api.server.spi.response.InternalServerErrorException) ApiMethod(com.google.api.server.spi.config.ApiMethod)

Aggregations

DatabaseReference (com.google.firebase.database.DatabaseReference)157 DatabaseError (com.google.firebase.database.DatabaseError)95 DataSnapshot (com.google.firebase.database.DataSnapshot)87 ValueEventListener (com.google.firebase.database.ValueEventListener)61 FirebaseDatabase (com.google.firebase.database.FirebaseDatabase)50 HashMap (java.util.HashMap)24 View (android.view.View)18 MutableData (com.google.firebase.database.MutableData)17 Transaction (com.google.firebase.database.Transaction)17 Intent (android.content.Intent)16 FirebaseUser (com.google.firebase.auth.FirebaseUser)13 ArrayList (java.util.ArrayList)12 TextView (android.widget.TextView)11 Query (com.google.firebase.database.Query)11 Map (java.util.Map)11 ProgressDialog (android.app.ProgressDialog)10 LinearLayoutManager (android.support.v7.widget.LinearLayoutManager)10 ChildEventListener (com.google.firebase.database.ChildEventListener)9 SharedPreferences (android.content.SharedPreferences)8 ChatMessageHelper (ingage.ingage20.helpers.ChatMessageHelper)8