I am following the Codelab tutorial on firebase of the FriendlyChat app. I have reached the Indexing section. I have implemented the code as required but I do not see the app indexing work when I search google on the emulator.
Here is the manifest section.
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data
android:host="friendlychat.firebase.google.com"
android:scheme="http"
android:pathPrefix="/message"/>
</intent-filter>
Here is the MainActivity.java
The tutorial is on this page https://codelabs.developers.google.com/codelabs/firebase-android/#8
Could the problem be that I am using the emulator?
Here is the MainActivity.java
public class MainActivity extends AppCompatActivity
implements GoogleApiClient.OnConnectionFailedListener {
public static class MessageViewHolder extends RecyclerView.ViewHolder {
TextView messageTextView;
ImageView messageImageView;
TextView messengerTextView;
CircleImageView messengerImageView;
public MessageViewHolder(View v) {
super(v);
messageTextView = (TextView) itemView.findViewById(R.id.messageTextView);
messageImageView = (ImageView) itemView.findViewById(R.id.messageImageView);
messengerTextView = (TextView) itemView.findViewById(R.id.messengerTextView);
messengerImageView = (CircleImageView) itemView.findViewById(R.id.messengerImageView);
}
}
private static final String TAG = "MainActivity";
public static final String MESSAGES_CHILD = "messages";
private static final int REQUEST_INVITE = 1;
private static final int REQUEST_IMAGE = 2;
private static final String LOADING_IMAGE_URL = "https://www.google.com/images/spin-32.gif";
public static final int DEFAULT_MSG_LENGTH_LIMIT = 10;
public static final String ANONYMOUS = "anonymous";
private static final String MESSAGE_SENT_EVENT = "message_sent";
private String mUsername;
private String mPhotoUrl;
private SharedPreferences mSharedPreferences;
private GoogleApiClient mGoogleApiClient;
private static final String MESSAGE_URL = "http://friendlychat.firebase.google.com/message/";
private Button mSendButton;
private RecyclerView mMessageRecyclerView;
private LinearLayoutManager mLinearLayoutManager;
private ProgressBar mProgressBar;
private EditText mMessageEditText;
private ImageView mAddMessageImageView;
// Firebase instance variables
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
private DatabaseReference mFirebaseDatabaseReference;
private FirebaseRecyclerAdapter<FriendlyMessage, MessageViewHolder> mFirebaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
// Set default username is anonymous.
mUsername = ANONYMOUS;
// Initialize Firebase Auth
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
if(mFirebaseUser == null){
// Not signed in, launch the Sign in activity
startActivity(new Intent(this, SignInActivity.class));
finish();
return;
} else {
mUsername = mFirebaseUser.getDisplayName();
if(mFirebaseUser.getPhotoUrl() != null){
mPhotoUrl = mFirebaseUser.getPhotoUrl().toString();
}
}
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API)
.build();
// Initialize ProgressBar and RecyclerView.
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mMessageRecyclerView = (RecyclerView) findViewById(R.id.messageRecyclerView);
mLinearLayoutManager = new LinearLayoutManager(this);
mLinearLayoutManager.setStackFromEnd(true);
mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
// New child entries
mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
mFirebaseAdapter = new FirebaseRecyclerAdapter<FriendlyMessage, MessageViewHolder>(
FriendlyMessage.class,
R.layout.item_message,
MessageViewHolder.class,
mFirebaseDatabaseReference.child(MESSAGES_CHILD)) {
#Override
protected FriendlyMessage parseSnapshot(DataSnapshot snapshot){
FriendlyMessage friendlyMessage = super.parseSnapshot(snapshot);
if(friendlyMessage != null){
friendlyMessage.setId(snapshot.getKey());
}
return friendlyMessage;
}
#Override
protected void populateViewHolder(final MessageViewHolder messageViewHolder,
FriendlyMessage friendlyMessage, int position) {
mProgressBar.setVisibility(ProgressBar.INVISIBLE);
if(friendlyMessage.getText() != null){
// write this message to the on-device index
FirebaseAppIndex.getInstance().update(getMessageIndexable(friendlyMessage));
Log.d(TAG, friendlyMessage.getText());
// log a view action on it
FirebaseUserActions.getInstance().end(getMessageViewAction(friendlyMessage));
messageViewHolder.messageTextView.setText(friendlyMessage.getText());
messageViewHolder.messageTextView.setVisibility(TextView.VISIBLE);
messageViewHolder.messageImageView.setVisibility(ImageView.GONE);
} else {
String imageUrl = friendlyMessage.getImageUrl();
if(imageUrl.startsWith("gs://")){
StorageReference storageReference = FirebaseStorage.getInstance()
.getReferenceFromUrl(imageUrl);
storageReference.getDownloadUrl().addOnCompleteListener(
new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()){
String downloadUrl = task.getResult().toString();
Glide.with(messageViewHolder.messageImageView.getContext())
.load(downloadUrl)
.into(messageViewHolder.messageImageView);
} else {
Log.w(TAG, "Getting download url was not successful.",
task.getException());
}
}
}
);
} else {
Glide.with(messageViewHolder.messageImageView.getContext())
.load(friendlyMessage.getImageUrl())
.into(messageViewHolder.messageImageView);
}
messageViewHolder.messageImageView.setVisibility(ImageView.VISIBLE);
messageViewHolder.messageTextView.setVisibility(TextView.GONE);
}
messageViewHolder.messengerTextView.setText(friendlyMessage.getName());
if( friendlyMessage.getPhotoUrl() == null){
messageViewHolder.messengerImageView.setImageDrawable(ContextCompat.getDrawable(MainActivity.this,
R.drawable.ic_account_circle_black_36dp));
} else {
Glide.with(MainActivity.this)
.load(friendlyMessage.getPhotoUrl())
.into(messageViewHolder.messengerImageView);
}
}
};
mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver(){
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
int friendlyMessageCount = mFirebaseAdapter.getItemCount();
int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
// If the recycler view is initially being loaded or the
// user is at the bottom of the list, scroll to the bottom
// of the list to show the newly added message
if (lastVisiblePosition == -1 ||
(positionStart >= (friendlyMessageCount - 1) &&
lastVisiblePosition == (positionStart -1))){
mMessageRecyclerView.scrollToPosition(positionStart);
}
}
});
mMessageRecyclerView.setAdapter(mFirebaseAdapter);
mMessageEditText = (EditText) findViewById(R.id.messageEditText);
mMessageEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(mSharedPreferences
.getInt(CodelabPreferences.FRIENDLY_MSG_LENGTH, DEFAULT_MSG_LENGTH_LIMIT))});
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) {
}
});
mSendButton = (Button) findViewById(R.id.sendButton);
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Send messages on click.
FriendlyMessage friendlyMessage = new
FriendlyMessage(mMessageEditText.getText().toString(),
mUsername,
mPhotoUrl,
null /* no image */);
mFirebaseDatabaseReference.child(MESSAGES_CHILD)
.push().setValue(friendlyMessage);
mMessageEditText.setText("");
}
});
mAddMessageImageView = (ImageView) findViewById(R.id.addMessageImageView);
mAddMessageImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Select image for image message on click.
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_IMAGE);
}
});
}
#Override
public void onStart() {
super.onStart();
// Check if user is signed in.
// TODO: Add code to check if user is signed in.
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult: requestCode=" + requestCode + ", resultCode=" + resultCode);
if(requestCode == REQUEST_IMAGE){
if(resultCode == RESULT_OK) {
if(data != null){
final Uri uri = data.getData();
Log.d(TAG, "Uri: " + uri.toString());
FriendlyMessage tempMessage = new FriendlyMessage(null, mUsername, mPhotoUrl,
LOADING_IMAGE_URL);
mFirebaseDatabaseReference.child(MESSAGES_CHILD).push()
.setValue(tempMessage, new DatabaseReference.CompletionListener(){
#Override
public void onComplete(DatabaseError databaseError,
DatabaseReference databaseReference){
if(databaseError == null){
String key = databaseReference.getKey();
StorageReference storageReference =
FirebaseStorage.getInstance()
.getReference(mFirebaseUser.getUid())
.child(key)
.child(uri.getLastPathSegment());
putImageInStorage(storageReference, uri, key);
} else {
Log.w(TAG, "Unable to write message to database.",
databaseError.toException());
}
}
});
}
}
}
}
private void putImageInStorage(StorageReference storageReference, Uri uri, final String key){
storageReference.putFile(uri).addOnCompleteListener(MainActivity.this,
new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
FriendlyMessage friendlyMessage =
new FriendlyMessage(null, mUsername, mPhotoUrl,
task.getResult().getMetadata().getDownloadUrl()
.toString());
mFirebaseDatabaseReference.child(MESSAGES_CHILD).child(key)
.setValue(friendlyMessage);
} else {
Log.w(TAG, "Image upload task was not successful.",
task.getException());
}
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.sign_out_menu:
mFirebaseAuth.signOut();
Auth.GoogleSignInApi.signOut(mGoogleApiClient);
mUsername = ANONYMOUS;
startActivity(new Intent(this, SignInActivity.class));
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
// An unresolvable error has occurred and Google APIs (including Sign-In) will not
// be available.
Log.d(TAG, "onConnectionFailed:" + connectionResult);
Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
}
private Indexable getMessageIndexable(FriendlyMessage friendlyMessage) {
PersonBuilder sender = Indexables.personBuilder()
.setIsSelf(mUsername.equals(friendlyMessage.getName()))
.setName(friendlyMessage.getName())
.setUrl(MESSAGE_URL.concat(friendlyMessage.getId() + "/sender"));
PersonBuilder recipient = Indexables.personBuilder()
.setName(mUsername)
.setUrl(MESSAGE_URL.concat(friendlyMessage.getId() + "/recipient"));
Indexable messageToIndex = Indexables.messageBuilder()
.setName(friendlyMessage.getText())
.setUrl(MESSAGE_URL.concat(friendlyMessage.getId()))
.setSender(sender)
.setRecipient(recipient)
.build();
return messageToIndex;
}
private Action getMessageViewAction(FriendlyMessage friendlyMessage){
return new Action.Builder(Action.Builder.VIEW_ACTION)
.setObject(friendlyMessage.getName(), MESSAGE_URL.concat(friendlyMessage.getId()))
.setMetadata(new Action.Metadata.Builder().setUpload(false))
.build();
}
If you take from copy/paste, that is only about wrong place code, try
From Android Studio, on toolbar Click "CODE" then select "REARRANGE
CODE" than try "RUN" again.
Or try see sample from original MainActivity.java in android folder
instead android-start on
https://github.com/firebase/friendlychat-android repository
Related
I'm creating an app that display notes list in a recyclerView. I connected the app with firebase authentication and realtime database.
The Realtime Database JSON tree looks like this:
The problem is that I want "Notes" to be part of "Users" which is not the case, because when I login to my app, I found the same Notes in every user account. I want the notes to be displayed for a specific user when they create them.
Here is my code:
SignupActivity.java
public class SignupActivity extends AppCompatActivity {
private static final String TAG = "";
private static final int RC_SIGN_IN = 9001;
EditText mName, mEmail,mPassword;
Button mSignupBtn;
FirebaseAuth mAuth;
ProgressBar progressBar;
View mViewHelper;
GoogleSignInButton button;
GoogleSignInClient mGoogleSignInClient;
FirebaseAuth.AuthStateListener mAuthListner;
FirebaseFirestore fStore;
String userID;
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListner);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
TextView textView = findViewById(R.id.textView);
textView.setText(Html.fromHtml(getString(R.string.agree_terms)));
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
mEmail = findViewById(R.id.et_email_address);
mPassword = findViewById(R.id.et_password);
mName = findViewById(R.id.et_name);
mSignupBtn = findViewById(R.id.create_btn);
progressBar = findViewById(R.id.loading_spinner);
mViewHelper = findViewById(R.id.view_helper);
button = findViewById(R.id.login_google_btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn();
}
});
mAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
mSignupBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
final String name = mName.getText().toString();
if(TextUtils.isEmpty(email)) {
mEmail.setError("Email is required.");
return;
}
if(TextUtils.isEmpty(name)) {
mName.setError("Name is required.");
return;
}
if(TextUtils.isEmpty(password)) {
mPassword.setError("Password is required.");
return;
}
if(password.length() < 6) {
mPassword.setError("Password Must be >= 6 Characters");
return;
}
progressBar.setVisibility(View.VISIBLE);
mViewHelper.setVisibility(View.VISIBLE);
mSignupBtn.setVisibility(View.INVISIBLE);
// register the user in firebase
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
Toast.makeText(SignupActivity.this, "User Created", Toast.LENGTH_SHORT).show();
userID = mAuth.getCurrentUser().getUid();
DocumentReference documentReference = fStore.collection("users").document(userID);
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child(userID);
Map<String, Object> user = new HashMap<>();
user.put("name", name);
user.put("email", email);
user.put("image", "default");
user.put("thumb_image", "default");
current_user_db.setValue(user);
documentReference.set(user).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "onSuccess: user Profile is created for "+ userID);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: "+ e.toString());
}
});
Intent intent = new Intent(SignupActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
else{
Toast.makeText(SignupActivity.this, "Error !" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
mViewHelper.setVisibility(View.INVISIBLE);
mSignupBtn.setVisibility(View.VISIBLE);
}
});
}
});
mAuthListner = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(SignupActivity.this, MainActivity.class));
}
}
};
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken("886475354465-j5suema9gt5mhi2fhli0un9vsn1olvaa.apps.googleusercontent.com")
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
// ...
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
//updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(SignupActivity.this, "Aut Fail", Toast.LENGTH_SHORT).show();
//updateUI(null);
}
// ...
}
});
}
}
NotesAdapter.java
public class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.MyHolder>
{
List<Listdata> noteslist;
private Context context;
public NotesAdapter(List<Listdata> noteslist,Context context)
{
this.context=context;
this.noteslist=noteslist;
}
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item,viewGroup,false);
MyHolder myHolder=new MyHolder(view);
return myHolder;
}
#Override
public void onBindViewHolder(#NonNull MyHolder myHolder, int position) {
Listdata data=noteslist.get(position);
myHolder.title.setText(data.getTitle());
myHolder.desc.setText(data.getDesc());
}
#Override
public int getItemCount() {
return noteslist.size();
}
class MyHolder extends RecyclerView.ViewHolder {
TextView title,desc;
public MyHolder(#NonNull View itemView) {
super(itemView);
title=itemView.findViewById(R.id.title);
desc=itemView.findViewById(R.id.desc);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Listdata listdata=noteslist.get(getAdapterPosition());
Intent i=new Intent(context, StreamActivity.class);
i.putExtra("id",listdata.id);
i.putExtra("title",listdata.title);
i.putExtra("desc",listdata.desc);
context.startActivity(i);
}
});
}
}
}
AddNotesActivity.java
public class AddNotesActivity extends AppCompatActivity {
EditText title,desc;
String titlesend,descsend;
private DatabaseReference mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_notes);
title=findViewById(R.id.title);
desc=findViewById(R.id.desc);
mDatabase = FirebaseDatabase.getInstance().getReference();
}
public void AddNotes(View view) {
titlesend=title.getText().toString();
descsend=desc.getText().toString();
if(TextUtils.isEmpty(titlesend) || TextUtils.isEmpty(descsend)){
return;
}
AddNotes(titlesend,descsend);
}
private void AddNotes(String titlesend, String descsend)
{
String id=mDatabase.push().getKey();
Listdata listdata = new Listdata(id,titlesend, descsend);
mDatabase.child("Notes").child(id).setValue(listdata).
addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(AddNotesActivity.this, "Notes Added", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),NotesActivity.class));
}
});
}
}
NotesActivity.java
public class NotesActivity extends AppCompatActivity {
// Firebase instance variables
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
//HomeScreen variables
RecyclerView recyclerView;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
List<Listdata> list =new ArrayList<>();
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
recyclerView=findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(NotesActivity.this);
recyclerView.setLayoutManager(layoutManager);
// Initialize Firebase Auth
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
// Notes Screen
final NotesAdapter notesAdapter=new NotesAdapter(list,this);
recyclerView.setAdapter(notesAdapter);
FloatingActionButton fab = findViewById(R.id.fab);
firebaseDatabase=FirebaseDatabase.getInstance();
databaseReference=firebaseDatabase.getReference("Notes");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren())
{
Listdata listdata=dataSnapshot1.getValue(Listdata.class);
list.add(listdata);
}
notesAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), AddNotesActivity.class));
}
});
// end NotesScreen
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mFirebaseAuth.getCurrentUser();
if(currentUser == null){
sendToStart();
}
}
private void sendToStart() {
Intent startIntent = new Intent(NotesActivity.this, LoginActivity.class);
startActivity(startIntent);
finish();
}
Please I need help on how should I modify my code to display the notes for a specific user when they create them. documentation links will be much appreciated.
you simply need to change this line of code from AddNotesActivity.java
mDatabase.child("Notes").child(id)
to
mDatabase.child("Users").child(userID).child("Notes").child(id)
and don't forget to retrieve the data in NotesActivity.java
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(userID).child("Notes");
I face a problem when I send a comment, that comment does not appear in RecyclerView, I have to go back and reopen Activity again to see my reply.
BlogSingleActivity.java
public class BlogSingleActivity extends AppCompatActivity {
private String mPost_key = null;
DatabaseReference mDatabase;
private ImageView mBlogSingleImage;
private TextView mBlogSingleTitle;
private TextView mBlogSingleDesc;
private TextView mBlogSingleUsername, mNumbersOfComments;
private TextView mBlogSingleDate;
private DatabaseReference ReplayDatabase;
private RecyclerView mReplayBlogList;
private TextView emptyView;
FirebaseRecyclerAdapter<Blog, BlogViewHolder> mAdapter;
private EditText mReplayText;
private FirebaseAuth mAuth;
private FirebaseUser mCurrentUser;
private DatabaseReference mDatabaseUser;
private Uri mImagUri = null;
private static final int GALLERY_REQUEST = 2;
private StorageReference mStorage;
private ImageButton mselectImage;
Button sendBTN;
private ProgressDialog mProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blog_single);
mPost_key = getIntent().getExtras().getString("blog_id");
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
ReplayDatabase = FirebaseDatabase.getInstance().getReference().child("Replay");
mBlogSingleDesc = findViewById(R.id.singleBlogDesc);
mBlogSingleTitle = findViewById(R.id.post_Tittle);
mBlogSingleImage = findViewById(R.id.singleBlogImage);
mBlogSingleUsername = findViewById(R.id.singleBlogUsername);
mBlogSingleDate = findViewById(R.id.singleBlogDate);
mNumbersOfComments = findViewById(R.id.numberofcomments);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mReplayBlogList = findViewById(R.id.replay_blog_list);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
mReplayBlogList.setLayoutManager(layoutManager);
mReplayBlogList.setNestedScrollingEnabled(false);
emptyView = findViewById(R.id.empty_view);
chickitem();
mAuth = FirebaseAuth.getInstance();
mCurrentUser = mAuth.getCurrentUser();
mDatabaseUser = FirebaseDatabase.getInstance().getReference().child("Users").child(mCurrentUser.getUid());
mReplayText = findViewById(R.id.ReplayField);
mStorage = FirebaseStorage.getInstance().getReference();
mselectImage = findViewById(R.id.replayImageSelect);
sendBTN = findViewById(R.id.send_BTN);
getfirebaseData();
mProgress = new ProgressDialog(this);
mselectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GALLERY_REQUEST);
}
});
sendBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startReplay();
getfirebaseData();;
disappearKeyboard();
mReplayText.getText().clear();
mselectImage.setImageResource(R.mipmap.add_btn);
mselectImage.setBackgroundColor(getResources().getColor(R.color.image_background_color));
}
});
mDatabase.child(mPost_key).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String post_title = (String) dataSnapshot.child("tittle").getValue();
String post_desc = (String) dataSnapshot.child("desc").getValue();
String post_image = (String) dataSnapshot.child("image").getValue();
String post_username = (String) dataSnapshot.child("username").getValue();
Object post_date = dataSnapshot.child("date").getValue();
Blog timeStamp = new Blog();
timeStamp.setDate(post_date);
if (timeStamp.getDate() != null) {
String datee = timeStamp.getDate().toString();
long time = Long.parseLong(datee);
String timeAgo = TimeAgo.getTimeAgo(time);
mBlogSingleDate.setText(timeAgo);
}
mBlogSingleTitle.setText(post_title);
mBlogSingleDesc.setText(post_desc);
mBlogSingleUsername.setText(post_username);
Picasso.with(BlogSingleActivity.this)
.load(post_image)
.into(mBlogSingleImage);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void disappearKeyboard() {
InputMethodManager inputManager =
(InputMethodManager) this.
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(
this.getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
private void startReplay() {
{
final String replay_val = mReplayText.getText().toString().trim();
//send date to firebase database
if (!TextUtils.isEmpty(replay_val) && mImagUri != null) {
mProgress.setMessage("جاري الإرسال....");
mProgress.show();
StorageReference filepath = mStorage.child("Replay_Images").child(mImagUri.getLastPathSegment());
filepath.putFile(mImagUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
if (mAuth.getCurrentUser() != null) {
#SuppressWarnings("VisibleForTests") final Uri downloadUrl = taskSnapshot.getDownloadUrl();
final DatabaseReference newPost = ReplayDatabase.child(mPost_key).push();
mDatabaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
newPost.child("replayimage").setValue(downloadUrl.toString());
newPost.child("replay").setValue(replay_val);
newPost.child("replaydate").setValue(ServerValue.TIMESTAMP);
newPost.child("uid").setValue(mCurrentUser.getUid());
newPost.child("replayname").setValue(dataSnapshot.child("name").getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
chickitem();
mAdapter.notifyDataSetChanged();
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mProgress.dismiss();
}
}
});
} else if ((!TextUtils.isEmpty(replay_val))) {
mProgress.setMessage("جاري الإرسال....");
mProgress.show();
if (mAuth.getCurrentUser() != null) {
final DatabaseReference newPost = ReplayDatabase.child(mPost_key).push();
mDatabaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
newPost.child("replay").setValue(replay_val);
newPost.child("replaydate").setValue(ServerValue.TIMESTAMP);
newPost.child("uid").setValue(mCurrentUser.getUid());
newPost.child("replayname").setValue(dataSnapshot.child("name").getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
chickitem();
mAdapter.notifyDataSetChanged();
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mProgress.dismiss();
}
}
}
}
private void getfirebaseData() {
mAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
Blog.class,
R.layout.replay_row,
BlogViewHolder.class,
ReplayDatabase.child(mPost_key)
) {
#Override
protected void populateViewHolder(final BlogViewHolder viewHolder, final Blog model, int position) {
viewHolder.setReplay(model.getReplay());
viewHolder.setReplayname(model.getReplayname());
viewHolder.setReplaydate(model.getReplaydate());
viewHolder.setReplayimage(getApplicationContext(), model.getReplayimage());
}
};
mReplayBlogList.setAdapter(mAdapter);
}
public static class BlogViewHolder extends RecyclerView.ViewHolder {
View mView;
ImageView replay_imagee;
TextView recive_replay, post_replayname, post_replaydate;
public BlogViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setReplay(String replay) {
recive_replay = mView.findViewById(R.id.replay_text);
recive_replay.setText(replay);
}
public void setReplayname(String replayname) {
post_replayname = mView.findViewById(R.id.replayer_name_field);
post_replayname.setText(replayname);
}
public void setReplaydate(Object relaydate) {
post_replaydate = mView.findViewById(R.id.post_replaydate);
Blog timeStamps = new Blog();
timeStamps.setDate(relaydate);
if (timeStamps.getDate()!=null){
String dateee = timeStamps.getDate().toString();
long times = Long.parseLong(dateee);
String timeAgoo = TimeAgo.getTimeAgo(times);
post_replaydate.setText(timeAgoo);
}
}
public void setReplayimage(final Context ctx, final String replayimage) {
replay_imagee = mView.findViewById(R.id.replay_image);
Picasso.with(ctx).load(replayimage).networkPolicy(NetworkPolicy.OFFLINE).into(replay_imagee, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(ctx).load(replayimage).into(replay_imagee);
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
mImagUri = result.getUri();
mselectImage.setImageURI(mImagUri);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
private void chickitem() {
final AtomicInteger count = new AtomicInteger();
ReplayDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long numChildren = dataSnapshot.child(mPost_key).getChildrenCount();
if (numChildren == 0) {
emptyView.setVisibility(View.VISIBLE);
emptyView.setText("لا توجد تعليقات");
mReplayBlogList.setVisibility(View.INVISIBLE);
mNumbersOfComments.setText("لا توجد تعليقات");
} else {
mNumbersOfComments.setText("" + numChildren);
emptyView.setVisibility(View.VISIBLE);
emptyView.setText("التعليقات...");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onStart(){
super.onStart();
getfirebaseData();
}
#Override
public void onResume(){
super.onResume();
getfirebaseData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
The screen looks like .
There are two comments. To see these comment I have to go back and reopen this Activity.
I'm not 100% sure about this, but I think you're missing the mReplayBlogList.notifyDataSetChanged(); after the line mReplayBlogList.setAdapter(mAdapter); in getfirebaseData().
Maybe you could give it a try. Let me know if it solved :)
I'm making random chat app where every 2 users are in 1 room. My app worked well if I don't rotate the device, but I just tried to rotate several times right after app is launched to make app robust. Then, the app crashed right away
how can I log in anonymously to firebase authentication and add onCompleteListener when user rotates his/her while the firebase authentication is in progress?
When I first launch the app, a dialog is showed up which is used to announce the user that the app is initializing something and during the dialog is showed in onCreateView of a fragment, app tries to log in to firebase authentication anonymously and set onCompleteListener because when authentication is completed,
I have to insert to firebase database '/user_state/{uid}/"home"' with uid and dismiss dialog to make user possible to push button which is used to find another user to chat where the uid is needed too.
Because the uid is needed in both jobs, I need to do these jobs right after the authentication is completed.
I just thought that I could implement inserting '/user_state/{uid}/"home"' by cloud functions for firebase, but I didn't know how I could know the time when I dismiss the initializing dialog that I showed before because I have to know when the authentication is completed and I need callback function. So I added onCompleteListener like this
FirebaseAuth.getInstance().signInAnonymously().addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "signInAnonymously:success");
mAuthInitDialog.dismiss();
mCurrentUser = mAuth.getCurrentUser();
UserState state = new UserState(STATE_HOME);
mFirebaseDatabase
.getReference("user_state/" + mCurrentUser.getUid())
.setValue(state);
} else {
Log.w(TAG, "signInAnonymously:failure", task.getException());
mAuthInitDialog.dismiss();
Toast.makeText(getActivity(), "Authentication Failed", Toast.LENGTH_SHORT).show();
}
}
});
But when I rotate the device, the activity is destroyed and listener has gone for sure. So, I just thought that how about changing my code like below
Task mTask = FirebaseAuth.getInstance().signInAnonymously();
mTask.addOnCompleteListener( ...
and I used onSaveInstanceState method and Gson to save my Task Object like below
bundle.putString(BUNDLE_TASK_AUTH, new Gson().toJson(mTaskAuth));
and restored like below
if(savedInstanceState != null) {
mTask = new Gson().fromJson(savedInstanceState.getString(BUNDLE_TASK_AUTH), Task.class);
mTask.setOnCompleteListener( ...
}
But, I'm not sure if the listener could catch the authentication complete event even though the listener is retored after the fragment is recreated every time
Because I thought that authentication complete event can occur when after the activity is destroyed and before the activity is recreated.
I just want to make robust app even though there are several device rotations using firebase authentication. What should I do?
Code for MainFragment.java
public class MainFragment extends Fragment {
private static final String TAG = "sgc109.MainFragment";
private static final String DIALOG_PROGRESS = "DialogProgress";
private static final String BUNDLE_IS_WAITING = "bundle_is_waiting";
private static final String BUNDLE_TASK_AUTH = "bundle_task_auth";
private static final String CMD_START_WAITING = "start_waiting";
private static final String CMD_STOP_WAITING = "stop_waiting";
private static final String CMD_EXIT = "exit";
private static final String CMD_SEND = "send";
private static final String STATE_HOME = "home";
private static final String STATE_WAITING = "waiting";
private static final String STATE_MATCHED = "matched";
private static final String STATE_PENDING = "pending";
private static final int REQUEST_CHAT_ROOM = 0;
private boolean isWaiting;
private boolean hasRequestedAuth;
private Task mTaskAuth;
private FirebaseAuth mAuth;
private Button mEnterTheRoomButton;
private ProgressDialog mProgressDialog;
private ProgressDialog mAuthInitDialog;
private FirebaseDatabase mFirebaseDatabase;
private FirebaseUser mCurrentUser;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (savedInstanceState != null) {
Log.i(TAG, "retore savedInstanceState!");
isWaiting = savedInstanceState.getBoolean(BUNDLE_IS_WAITING, false);
mTaskAuth = new Gson().fromJson(savedInstanceState.getString(BUNDLE_TASK_AUTH), Task.class);
}
if (isWaiting) {
showProgressDialog();
}
View view = inflater.inflate(R.layout.fragment_main, container, false);
mAuth = FirebaseAuth.getInstance();
mCurrentUser = mAuth.getCurrentUser();
mFirebaseDatabase = FirebaseDatabase.getInstance();
if (mCurrentUser == null) {
mAuthInitDialog = new ProgressDialog(getActivity());
mAuthInitDialog.setTitle("첫 실행 초기화 중");
mAuthInitDialog.setCanceledOnTouchOutside(false);
mAuthInitDialog.setCancelable(false);
mAuthInitDialog.show();
if (mTaskAuth == null) {
mTaskAuth = mAuth.signInAnonymously();
}
mTaskAuth.addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "signInAnonymously:success");
mAuthInitDialog.dismiss();
mCurrentUser = mAuth.getCurrentUser();
UserState state = new UserState(STATE_HOME);
mFirebaseDatabase
.getReference("user_state/" + mCurrentUser.getUid())
.setValue(state);
} else {
Log.w(TAG, "signInAnonymously:failure", task.getException());
mAuthInitDialog.dismiss();
Toast.makeText(getActivity(), "Authentication Failed", Toast.LENGTH_SHORT).show();
}
}
});
}
else {
mFirebaseDatabase
.getReference()
.child("user_state")
.child(mCurrentUser.getUid())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserState state = dataSnapshot.getValue(UserState.class);
if (state.state.equals(STATE_MATCHED)) {
enterChatRoom();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "onCancelled");
}
});
}
mEnterTheRoomButton = (Button) view.findViewById(R.id.activity_main_enter_the_room_button);
mEnterTheRoomButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCurrentUser == null) {
return;
}
if (!isWaiting) {
startWaitingForOtherUser();
isWaiting = true;
}
showProgressDialog();
}
});
return view;
}
#Override
public void onStop() {
super.onStop();
if (mProgressDialog != null) mProgressDialog.dismiss();
if (mAuthInitDialog != null) mAuthInitDialog.dismiss();
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.i(TAG, "onSavedInstaneState()");
super.onSaveInstanceState(outState);
outState.putBoolean(BUNDLE_IS_WAITING, isWaiting);
outState.putString(BUNDLE_TASK_AUTH, new Gson().toJson(mTaskAuth));
}
public void showProgressDialog() {
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
isWaiting = false;
dialog.cancel();
stopWaitingForOtherUser();
return true;
}
return false;
}
});
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.setTitle(R.string.find_other_user_progress_dialog_text);
mProgressDialog.show();
}
public void stopWaitingForOtherUser() {
CommandSender.sendCommand(CMD_STOP_WAITING);
}
public void startWaitingForOtherUser() {
CommandSender.sendCommand(CMD_START_WAITING);
}
public void enterChatRoom() {
isWaiting = false;
Intent intent = ChatRoomActivity.newIntent(getActivity());
startActivityForResult(intent, REQUEST_CHAT_ROOM);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) {
return;
}
switch (requestCode) {
case REQUEST_CHAT_ROOM:
boolean reEnter = data.getBooleanExtra(ChatRoomActivity.EXTRA_RE_ENTER_ROOM, false);
if (reEnter){
showProgressDialog();
startWaitingForOtherUser();
}
default:
return;
}
}
}
I solved this by using ViewModel. I found from here that ViewModel holds our data even though Activity is destroyed because of configuration change such as device rotation.
My changed code is below.
MainFragment.java
public class MainFragment extends Fragment {
private static final String TAG = "sgc109.MainFragment";
private static final String DIALOG_PROGRESS = "DialogProgress";
private static final String BUNDLE_IS_WAITING = "bundle_is_waiting";
private static final String BUNDLE_IS_AUTH_COMPLETE = "bundle_is_auth_complete";
private static final String CMD_START_WAITING = "start_waiting";
private static final String CMD_STOP_WAITING = "stop_waiting";
private static final String CMD_EXIT = "exit";
private static final String CMD_SEND = "send";
private static final String STATE_HOME = "home";
private static final String STATE_WAITING = "waiting";
private static final String STATE_MATCHED = "matched";
private static final String STATE_PENDING = "pending";
private static final int REQUEST_CHAT_ROOM = 0;
private boolean mIsWaiting;
private boolean mIsAuthComplete;
private Button mEnterTheRoomButton;
private ProgressDialog mProgressDialog;
private ProgressDialog mAuthInitDialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (savedInstanceState != null) {
Log.i(TAG, "retore savedInstanceState!");
mIsWaiting = savedInstanceState.getBoolean(BUNDLE_IS_WAITING, false);
mIsAuthComplete = savedInstanceState.getBoolean(BUNDLE_IS_AUTH_COMPLETE, false);
}
if (mIsWaiting) {
showProgressDialog();
}
View view = inflater.inflate(R.layout.fragment_main, container, false);
if (mIsAuthComplete) {
showAuthInitDialog();
MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
model.getTask().addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
mAuthInitDialog.dismiss();
if (task.isSuccessful()) {
Log.d(TAG, "signInAnonymously:success");
mIsAuthComplete = true;
UserState state = new UserState(STATE_HOME);
FirebaseDatabase
.getInstance()
.getReference("user_state/" + FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(state);
} else {
Log.w(TAG, "signInAnonymously:failure", task.getException());
getActivity().finish();
}
}
});
} else {
FirebaseDatabase
.getInstance()
.getReference()
.child("user_state")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserState state = dataSnapshot.getValue(UserState.class);
if (state.state.equals(STATE_MATCHED)) {
enterChatRoom();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "onCancelled");
}
});
}
mEnterTheRoomButton = (Button) view.findViewById(R.id.activity_main_enter_the_room_button);
mEnterTheRoomButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (FirebaseAuth.getInstance().getCurrentUser() == null) {
Toast.makeText(getActivity(), "Shit Fuck!", Toast.LENGTH_SHORT).show();
return;
}
showProgressDialog();
startWaitingForOtherUser();
mIsWaiting = true;
}
});
return view;
}
private void showAuthInitDialog() {
mAuthInitDialog = new ProgressDialog(getActivity());
mAuthInitDialog.setTitle("첫 실행 초기화 중");
mAuthInitDialog.setCanceledOnTouchOutside(false);
mAuthInitDialog.setCancelable(false);
mAuthInitDialog.show();
}
#Override
public void onStop() {
super.onStop();
if (mProgressDialog != null) mProgressDialog.dismiss();
if (mAuthInitDialog != null) mAuthInitDialog.dismiss();
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.i(TAG, "onSavedInstaneState()");
super.onSaveInstanceState(outState);
outState.putBoolean(BUNDLE_IS_WAITING, mIsWaiting);
outState.putBoolean(BUNDLE_IS_AUTH_COMPLETE, mIsAuthComplete);
}
public void showProgressDialog() {
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
mIsWaiting = false;
dialog.cancel();
stopWaitingForOtherUser();
return true;
}
return false;
}
});
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.setTitle(R.string.find_other_user_progress_dialog_text);
mProgressDialog.show();
}
public void stopWaitingForOtherUser() {
CommandSender.sendCommand(CMD_STOP_WAITING);
}
public void startWaitingForOtherUser() {
CommandSender.sendCommand(CMD_START_WAITING);
}
public void enterChatRoom() {
mIsWaiting = false;
Intent intent = ChatRoomActivity.newIntent(getActivity());
startActivityForResult(intent, REQUEST_CHAT_ROOM);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) {
return;
}
switch (requestCode) {
case REQUEST_CHAT_ROOM:
boolean reEnter = data.getBooleanExtra(ChatRoomActivity.EXTRA_RE_ENTER_ROOM, false);
if (reEnter) {
showProgressDialog();
startWaitingForOtherUser();
}
default:
return;
}
}
}
MyViewModel.java
public class MyViewModel extends ViewModel {
private Task task;
public Task getTask(){
if (task == null){
task = FirebaseAuth.getInstance().signInAnonymously();
}
return task;
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
public static final String ANONYMOUS = "anonymous";
public static final int RC_SIGN_IN = 1;
private static final int RC_PHOTO_PICKER = 2;
private String mUsername;
// Firebase instance variables
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mMessagesDatabaseReference;
private ChildEventListener mChildEventListener;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private FirebaseStorage mFirebaseStorage;
private StorageReference mChatPhotosStorageReference;
private FirebaseRemoteConfig mFirebaseRemoteConfig;
private RecyclerView recyclerView;
private FloatingActionButton floatingActionButton;
PhotosAdapter contactsAdapter;
List<Photos> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUsername = ANONYMOUS;
recyclerView=(RecyclerView)findViewById(R.id.recyclerview);
floatingActionButton=(FloatingActionButton)findViewById(R.id.floatingactionbutton);
contactList = new ArrayList();
contactsAdapter=new PhotosAdapter(contactList,getApplicationContext());
// Initialize Firebase components
mFirebaseDatabase = FirebaseDatabase.getInstance();
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseStorage = FirebaseStorage.getInstance();
mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
mMessagesDatabaseReference = mFirebaseDatabase.getReference().child("messages");
mChatPhotosStorageReference = mFirebaseStorage.getReference().child("chat_photos");
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
onSignedInInitialize(user.getDisplayName());
} else {
// User is signed out
onSignedOutCleanup();
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setProviders(
AuthUI.EMAIL_PROVIDER,
AuthUI.GOOGLE_PROVIDER)
.build(),
RC_SIGN_IN);
}
}
};
recyclerView.setAdapter(contactsAdapter);
recyclerView.setLayoutManager(new GridLayoutManager(getApplicationContext(),5));
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
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);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
// Sign-in succeeded, set up the UI
Toast.makeText(this, "Signed in!", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
// Sign in was canceled by the user, finish the activity
Toast.makeText(this, "Sign in canceled", Toast.LENGTH_SHORT).show();
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(this, 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
Photos friendlyMessage = new Photos(downloadUrl.toString());
mMessagesDatabaseReference.push().setValue(friendlyMessage);
}
});
}
}
#Override
protected void onResume() {
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
#Override
protected void onPause() {
super.onPause();
if (mAuthStateListener != null) {
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
}
}
private void onSignedInInitialize(String username) {
mUsername = username;
attachDatabaseReadListener();
}
private void onSignedOutCleanup() {
mUsername = ANONYMOUS;
}
private void attachDatabaseReadListener() {
if (mChildEventListener == null) {
mChildEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Photos friendlyMessage = dataSnapshot.getValue(Photos.class);
contactsAdapter.add(friendlyMessage);
}
public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
public void onChildRemoved(DataSnapshot dataSnapshot) {}
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
public void onCancelled(DatabaseError databaseError) {}
};
mMessagesDatabaseReference.addChildEventListener(mChildEventListener);
}
}
}
PhotosAdapter
public class PhotosAdapter extends RecyclerView.Adapter<PhotosAdapter.MyViewHolder> {
private List<Photos> photosList;
private Context context;
public static final String Position="AdapterPosition";
public PhotosAdapter(List<Photos> contactsList, Context context) {
this.photosList = contactsList;
this.context = context;
}
#Override
public PhotosAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.list_item, null);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(PhotosAdapter.MyViewHolder holder, int position) {
Photos contacts = photosList.get(position);
Glide.with(context).load(contacts.getPhotoUrl()).into(holder.contactimageView);
}
#Override
public int getItemCount() {
return photosList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public ImageView contactimageView;
private final Context context;
public MyViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
contactimageView = (ImageView) itemView.findViewById(R.id.imageview);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
/* Intent intent = new Intent(context, ChatActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Position,getAdapterPosition());
context.startActivity(intent);*/
}
public void add(Photos photos){
photosList.add(photos);
}
}
Photos
public class Photos {
private String photoUrl;
public Photos() {
}
public Photos(String photoUrl) {
this.photoUrl = photoUrl;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
}
This is my code. I am uploading an image on click of FloatingAction button to Firebase Storage.The image gets uploaded successfully, but I am not able to retrieve the image to the ImageView of my RecyclerView. What am I doing wrong? I am also able to see url of image in Storage.Still not able to retrieve message in imageview of recyclerview. Please help.......
you can try this also:-
yourFragment.isResumed()
hi guys how can i send a data to firebase when i logging in want to see different info from other accounts now i see the save data that i sent. this is a code:
This is my Activity_category Activity
public class Activity_category extends Activity {
class Layout{
Layout(){
textView2= (TextView)findViewById(R.id.textView2);
listview1=(RecyclerView)findViewById(R.id.listview1);
registerForContextMenu(listview1);
}
TextView textView2;
RecyclerView listview1;
}
class Events{
Events(){
firebaseDatabase = FirebaseDatabase.getInstance();
myRef = FirebaseDatabase.getInstance().getReference("User_Details");
l.listview1.setLayoutManager(new LinearLayoutManager(Activity_category.this));
Toast.makeText(Activity_category.this, "Wait ! Fetching List...", Toast.LENGTH_SHORT).show();
// l.listview1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// #Override
// public void onItemClick(AdapterView<?> adapterView, View view, int i, long id) {
// }
// });
}
}
Layout l;
Events e;
FirebaseDatabase firebaseDatabase;
DatabaseReference myRef;
FirebaseRecyclerAdapter<showdataitems, ShowDataViewHolder> mFirebaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
l = new Layout(); e = new Events();
}
public Activity_category() {
// Required empty public constructor
}
#Override
public void onStart() {
super.onStart();
//Log.d("LOGGED", "IN onStart ");
mFirebaseAdapter = new FirebaseRecyclerAdapter<showdataitems, ShowDataViewHolder>(showdataitems.class, R.layout.category, ShowDataViewHolder.class, myRef) {
public void populateViewHolder(final ShowDataViewHolder viewHolder, showdataitems model, final int position) {
viewHolder.Image_URL(model.getImage_URL());
viewHolder.Image_Title(model.getImage_Title());
//OnClick Item
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(Activity_category.this);
builder.setMessage("Do you want to Delete this data ?").setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
int selectedItems = position;
mFirebaseAdapter.getRef(selectedItems).removeValue();
mFirebaseAdapter.notifyItemRemoved(selectedItems);
l.listview1.invalidate();
onStart();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.setTitle("Confirm");
dialog.show();
}
});
}
};
l.listview1.setAdapter(mFirebaseAdapter);
}
//View Holder For Recycler View
public static class ShowDataViewHolder extends RecyclerView.ViewHolder {
private final TextView text1;
private final ImageView imageView3;
public ShowDataViewHolder(final View itemView) {
super(itemView);
imageView3 = (ImageView) itemView.findViewById(R.id.imageView3);
text1 = (TextView) itemView.findViewById(R.id.text1);
}
private void Image_Title(String title) {
text1.setText(title);
}
private void Image_URL(String title) {
// image_url.setImageResource(R.drawable.loading);
Glide.with(itemView.getContext())
.load(title)
.crossFade()
.placeholder(R.drawable.newmenu1)
.thumbnail(0.1f)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imageView3);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()){
case 1:
break;
}
return super.onContextItemSelected(item);
}
This is my Uploadinfo Activity
public class Uploadinfo extends Activity{
class Layout{
Layout(){
menuBtn= (Button)findViewById(R.id.menuBtn);
cancelBtn= (Button)findViewById(R.id.cancelBtn);
btnAddimage= (Button)findViewById(R.id.btnAddimage);
imageView= (ImageView)findViewById(R.id.imageView);
editText= (EditText)findViewById(R.id.editText);
}
Button menuBtn , cancelBtn,btnAddimage;
ImageView imageView;
EditText editText;
}
class Events{
Events(){
mProgressDialog = new ProgressDialog(Uploadinfo.this);
l.btnAddimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getApplicationContext(), "Call for Permission", Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERNAL_STORAGE);
}
}
else
{
callgalary();
}
}
});
mdatabaseRef = FirebaseDatabase.getInstance().getReference();
mRoofRef = new Firebase("https://restaurant-menu-4bdf2.firebaseio.com/").child("User_Details").push(); // Push will create new child every time we upload data
mStorage = FirebaseStorage.getInstance().getReferenceFromUrl("gs://restaurant-menu-4bdf2.appspot.com/");
l.menuBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String mName = l.editText.getText().toString().trim();
if(mName.isEmpty())
{
Toast.makeText(getApplicationContext(), "Fill all Field", Toast.LENGTH_SHORT).show();
return;
}
Firebase childRef_name = mRoofRef.child("Image_Title");
childRef_name.setValue(mName);
Toast.makeText(getApplicationContext(), "Updated Info", Toast.LENGTH_SHORT).show();
}
});
}
}
Layout l;
Events e;
public static final int READ_EXTERNAL_STORAGE = 0;
private static final int GALLERY_INTENT = 2;
private ProgressDialog mProgressDialog;
private Firebase mRoofRef;
private Uri mImageUri = null;
private DatabaseReference mdatabaseRef;
private StorageReference mStorage;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
l = new Layout(); e = new Events();
}
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
callgalary();
return;
}
Toast.makeText(getApplicationContext(), "...", Toast.LENGTH_SHORT).show();
}
private void callgalary() {
Intent intent1 = new Intent();
intent1.setType("image/*");
intent1.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent1, "Select Picture"), GALLERY_INTENT);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK) {
mImageUri = data.getData();
l.imageView.setImageURI(mImageUri);
StorageReference filePath = mStorage.child("User_Images").child(mImageUri.getLastPathSegment());
mProgressDialog.setMessage("Uploading Image....");
mProgressDialog.show();
filePath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUri = taskSnapshot.getDownloadUrl(); //Ignore This error
mRoofRef.child("Image_URL").setValue(downloadUri.toString());
Glide.with(getApplicationContext())
.load(downloadUri)
.crossFade()
.placeholder(R.drawable.newmenu1)
.diskCacheStrategy(DiskCacheStrategy.RESULT)
.into( l.imageView);
Toast.makeText(getApplicationContext(), "Updated.", Toast.LENGTH_SHORT).show();
mProgressDialog.dismiss();
}
});
}
}