Java tutorial
/** * Copyright Google Inc. All Rights Reserved. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ca.ggolda.lendit.fragments; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.text.Editable; import android.text.InputFilter; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.Toast; import com.firebase.ui.auth.AuthUI; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import java.util.ArrayList; import java.util.List; import ca.ggolda.lendit.R; import ca.ggolda.lendit.adapters.AdapterMessages; import ca.ggolda.lendit.objects.InstanceMessage; import static android.app.Activity.RESULT_CANCELED; import static android.app.Activity.RESULT_OK; public class FragChat extends Fragment { private static final String TAG = "FragChat"; public static final String ANONYMOUS = "anonymous"; public static final int DEFAULT_MSG_LENGTH_LIMIT = 144; public static final int RC_SIGN_IN = 1; private static final int RC_PHOTO_PICKER = 2; private ListView mMessageListView; private AdapterMessages mMessageAdapter; private ProgressBar mProgressBar; private ImageButton mPhotoPickerButton; private EditText mMessageEditText; private Button mSendButton; private String mUsername; private FirebaseDatabase mFirebaseDatabase; private DatabaseReference mMessagesDatabaseReference; private ChildEventListener mChildEventListener; private FirebaseAuth mFirebaseAuth; private FirebaseAuth.AuthStateListener mAuthStateListener; private FirebaseStorage mFirebaseStorage; private StorageReference mChatPhotosStorageReference; private String UserID; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.activity_chat, container, false); // Get UserID mFirebaseAuth = FirebaseAuth.getInstance(); FirebaseUser user = mFirebaseAuth.getCurrentUser(); UserID = user.getUid(); mUsername = user.getDisplayName(); mUsername = ANONYMOUS; mFirebaseDatabase = FirebaseDatabase.getInstance(); mUsername = user.getDisplayName(); mFirebaseStorage = FirebaseStorage.getInstance(); mMessagesDatabaseReference = mFirebaseDatabase.getReference().child("messages"); mChatPhotosStorageReference = mFirebaseStorage.getReference().child("chat_photos"); // Initialize references to views mProgressBar = (ProgressBar) v.findViewById(R.id.progressBar); mMessageListView = (ListView) v.findViewById(R.id.messageListView); mPhotoPickerButton = (ImageButton) v.findViewById(R.id.photoPickerButton); mMessageEditText = (EditText) v.findViewById(R.id.messageEditText); mSendButton = (Button) v.findViewById(R.id.sendButton); // Initialize message ListView and its adapter List<InstanceMessage> friendlyMessages = new ArrayList<>(); mMessageAdapter = new AdapterMessages(getContext(), R.layout.message_slide, friendlyMessages); mMessageListView.setAdapter(mMessageAdapter); // Initialize progress bar mProgressBar.setVisibility(ProgressBar.INVISIBLE); // ImagePickerButton shows an image picker to upload a image for a message mPhotoPickerButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/jpeg"); intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true); startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER); } }); // Enable Send button when there's text to send mMessageEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { if (charSequence.toString().trim().length() > 0) { mSendButton.setEnabled(true); } else { mSendButton.setEnabled(false); } } @Override public void afterTextChanged(Editable editable) { } }); mMessageEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(DEFAULT_MSG_LENGTH_LIMIT) }); // Send button sends a message and clears the EditText mSendButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // TODO: Send messages on click InstanceMessage friendlyMessage = new InstanceMessage(mMessageEditText.getText().toString(), mUsername, null); mMessagesDatabaseReference.push().setValue(friendlyMessage); // Clear input box mMessageEditText.setText(""); } }); mChildEventListener = new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { InstanceMessage friendlyMessage = dataSnapshot.getValue(InstanceMessage.class); mMessageAdapter.add(friendlyMessage); } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(DatabaseError databaseError) { } }; mMessagesDatabaseReference.addChildEventListener(mChildEventListener); mAuthStateListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { //user signed in OnSignedInInitialise(user.getDisplayName()); } else { //user signed out OnSignedOutCleanUp(); startActivityForResult( AuthUI.getInstance().createSignInIntentBuilder() .setProviders(AuthUI.EMAIL_PROVIDER, AuthUI.GOOGLE_PROVIDER).build(), RC_SIGN_IN); } } }; return v; } private void OnSignedInInitialise(String username) { mUsername = username; attachDatabaseReadListenter(); } private void OnSignedOutCleanUp() { mUsername = ANONYMOUS; mMessageAdapter.clear(); detachDatabaseReadListener(); } private void attachDatabaseReadListenter() { if (mChildEventListener == null) { mChildEventListener = new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { InstanceMessage friendlyMessage = dataSnapshot.getValue(InstanceMessage.class); mMessageAdapter.add(friendlyMessage); } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(DatabaseError databaseError) { } }; mMessagesDatabaseReference.addChildEventListener(mChildEventListener); } } private void detachDatabaseReadListener() { if (mChildEventListener != null) { mMessagesDatabaseReference.removeEventListener(mChildEventListener); mChildEventListener = null; } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RC_SIGN_IN) { if (resultCode == RESULT_OK) { Toast.makeText(getContext(), "You're Signed In", Toast.LENGTH_SHORT).show(); } else if (resultCode == RESULT_CANCELED) { Toast.makeText(getContext(), "Sign In Canceled", Toast.LENGTH_SHORT).show(); getActivity().finish(); } } else if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) { Uri selectedImageUri = data.getData(); // Get a reference to store file at chat_photos/<FILENAME> StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment()); // Upload file to Firebase Storage photoRef.putFile(selectedImageUri).addOnSuccessListener(getActivity(), new OnSuccessListener<UploadTask.TaskSnapshot>() { public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { // When the image has successfully uploaded, we get its download URL Uri downloadUrl = taskSnapshot.getDownloadUrl(); // Set the download URL to the message box, so that the user can send it to the database InstanceMessage friendlyMessage = new InstanceMessage(null, mUsername, downloadUrl.toString()); mMessagesDatabaseReference.push().setValue(friendlyMessage); } }); } } }