Firebase having problem displaying the image uploaded on the Firebase database. Looking the variables with the debug it seems there is the URL of the image but it doesn't show on the Navigation header when i run the app. Like this: that image is the placeholder
these are the variables
this is the code
mAuth = FirebaseAuth.getInstance();
UserRef = FirebaseDatabase.getInstance().getReference().child("Users");
currentUserID = Objects.requireNonNull(mAuth.getCurrentUser()).getUid();
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("ES ");
toolbar.setTitleTextAppearance(this, R.style.toolbar_textAppearance);
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
NavProfileImage = navigationView.getHeaderView(0).findViewById(R.id.profile_image);
NavTextView = navigationView.getHeaderView(0).findViewById(R.id.text_Nickname);
navigationView.setNavigationItemSelectedListener(this);
UserRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Log.d("image Path", NavProfileImage.toString());
if (dataSnapshot.hasChild("nickname")) {
String nickname = dataSnapshot.child("nickname").getValue(String.class);
NavTextView.setText(nickname);
}
if (dataSnapshot.hasChild("profileImage")) {
String image = dataSnapshot.child("profileImage").getValue(String.class);
Picasso.get().load(image).placeholder(R.mipmap.ic_launcher).into(NavProfileImage);
} else {
Toast.makeText(HomeActivity.this, "Profile name do not exists...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Related
I have a recyclerView called "Notes", I'm trying to add an new recylerview called "Assignments" which will be created inside the notes recylerview item.
When I click on a recylerview item (notes) it send me to ClassworkActivity in which the assignments' recyclerview will be added to it.
So I want to add the assignment recyclerview as a child of the notes recyclerview.
Here's what I tried:
final AssignmentAdapter assignmentAdapter=new AssignmentAdapter(assignlist,this);
recyclerView.setAdapter(assignmentAdapter);
FloatingActionButton fab = findViewById(R.id.fab);
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
String userID = mCurrentUser.getUid();
firebaseDatabase=FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference().child("Users").child(userID).child("Notes").child(id).child("Assignments");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren())
{
AssignListdata listdata=dataSnapshot1.getValue(AssignListdata.class);
assignlist.add(listdata);
}
assignmentAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
// fab
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), AddAssignmentActivity.class));
}
});
But I'm getting the error on this line:
databaseReference = firebaseDatabase.getReference().
child("Users").
child(userID).
child("Notes").
child(id).
child("Assignments");
since I didn't create the variable id : child(id). which is the id of the Notes List
Can anyone tell me how to declare this variable?
Another thing is that the assignments are created as a Notes in the NotesActivity, not in the ClassworkActivity!
Also, this is a github link of my project, Please take a look at it:
Notes App
When you click on recyclerView item of Notes, get the noteID usinng which position is clicked.
now when you open ClassworkActivity, bind that id with intent and get it in ClassworkActivity onCreate() and while creating AssignmentAdapter use that noteID as id.
pass noteId using intent as:
Intent myIntent = new Intent(CurrentActivity.this, ClassworkActivity.class); // UPDATE CURRENT ACTIVITY NAME
myIntent.putExtra("noteID", noteID);
startActivity(myIntent);
and receive in ClassworkActivity onCreate() as:
Intent mIntent = getIntent();
int id = mIntent.getIntExtra("noteID", 0);
I have a card view with on-click listener on it. As I click on it the color of card view get change which means it is ON. But as I move on any another activity the color of card view get change. I do not want that color to get change. Help me out.
Code of card view...
private void setToggleEvent(GridLayout mainGrid) {
final CardView bulb=(CardView)mainGrid.getChildAt(0);
bulb.setCardBackgroundColor(Color.parseColor("#404040"));
bulb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(bulb.getCardBackgroundColor().getDefaultColor()!=Color.parseColor("#FFD100"))
{
bulb.setCardBackgroundColor(Color.parseColor("#FFD100"));
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("BULB");
myRef.setValue("1");
}
else
{
bulb.setCardBackgroundColor(Color.parseColor("#404040"));
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("BULB");
myRef.setValue("0");
}
}
});
try this :
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
String color = sharedPreferences.getString("MY_KEY", "#fcfcfc");//#fcfcfc is defualt value!
bulb.setCardBackgroundColor(Color.parseColor(color));
bulb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (bulb.getCardBackgroundColor().getDefaultColor() != Color.parseColor("#fcfcfc")) {
bulb.setCardBackgroundColor(Color.parseColor("#fcfcfc"));
sharedPreferences.edit().putString("MY_KEY", "#fcfcfc").apply();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("BULB");
myRef.setValue("1");
} else {
bulb.setCardBackgroundColor(Color.parseColor("#404040"));
sharedPreferences.edit().putString("MY_KEY", "#404040").apply();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("BULB");
myRef.setValue("0");
}
}
});
I want to save data of authenticated users in Firebase, there are two ways to authenticate data in my app after which the user is taken to the MainActivity.Java. I would like to see if the user is using the application for the first time if so add the details to the user tree in Firebase RealtimeDatabase.
As of now after adding the code in OnCreate below the comment of adding the user, the app does not crash or give any errors, but it also does not hit the Firebase DB and update it.
Here is my code of the OnCreate section of the MainActivity.Java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Carousel
customCarouselView = findViewById(R.id.customCarouselView);
customCarouselView.setPageCount(sampleImages.length);
customCarouselView.setSlideInterval(4000);
customCarouselView.setImageListener(imageListener);
customCarouselView.setImageClickListener(new ImageClickListener() {
#Override
public void onClick(int position) {
// Toast.makeText(MainActivity.this, "Clicked item: " + position, Toast.LENGTH_SHORT).show();
redirectToHotDeals();
}
});
// -- Carousel
FirebaseAuth.getInstance().getCurrentUser();
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
// User is signed in.
String name = FirebaseAuth.getInstance().getCurrentUser().getDisplayName();
String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
NavigationView navigationView = findViewById(R.id.nav_view);
View headerView = navigationView.getHeaderView(0);
TextView navUsername = headerView.findViewById(R.id.emailText);
TextView navUID = headerView.findViewById(R.id.uid);
navUID.setText("ID: " + uid.substring(0, 10));
navUsername.setText(email);
} else {
// No user is signed in.
redirectToLogin();
}
// Action Bar
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Coupons List");
mRecyclerView = findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
// Set Layout
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
// Send Query to Firebase Db
mFirebaseDatabase = FirebaseDatabase.getInstance();
mRef = mFirebaseDatabase.getReference("Data");
// Add User to DB or Update it
String name = FirebaseAuth.getInstance().getCurrentUser().getDisplayName();
String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseUser fUser = FirebaseAuth.getInstance().getCurrentUser();
User user = new User(name, email);
mRef.child("User").child(fUser.getUid()).setValue(user);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
Here is the image of the Firebase Database: I would like if the first child has the UID followed by the email and contact as its child.
Here is my User.Java:
public class User {
public String name, email, phone;
public User(String name, String email){
}
public User(String name, String email, String phone) {
this.name = name;
this.email = email;
this.phone = phone;
}
}
You can use this piece of code to update values in your database:
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()){
Log.d("Tag","SignInWithCredential: success");
FirebaseUser fUser = mAuth.getCurrentUser();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
assert fUser != null;
User user = new User(fUser.getDisplayName(),fUser.getUid());
ref.child("users").child(fUser.getUid()).setValue(user);
}
else{
Log.w("TAG","SignInWithCredential: failure", task.getException());
Toast.makeText(MainActivity.this,"Authentication failed", Toast.LENGTH_SHORT).show();
}
}
});
Duplicate declaration for the NavigationView first. Define it as follows inside your onCreate():
navigationView = findViewById(R.id.nav_view);
And then;
NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
About the Firebase data set, User node doesn't seem to be child of Data which you declared it like this:
mRef = mFirebaseDatabase.getReference("Data");
mRef.child("User").child(fUser.getUid()).setValue(user);
Instead, try this:
mRef = mFirebaseDatabase.getReference("User");
mRef.child("UID").setValue(user);
Note that we need to be sure that User node is the reference in here. It seems like there is another root reference which we need to check the whole structure but I've just give you the path of how to get and set the data.
However, as documentation said, you'll need to be authenticated-Logged-in to be able to use Firebase database update-remove or etc. Otherwise, you should change your rules to open for everyone can do edits or etc.
I am removing a list item with a PopupMenu on my RecyclerViewAdapter, but when the item is removed it stays on the Firebase.
This is on the onBindViewHolder on the RecyclerAdapter
holder.opcionesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//creating a popup menu
PopupMenu popup = new PopupMenu(context, holder.opcionesButton);
//inflating menu from xml resource
popup.inflate(R.menu.menu_edit);
//adding click listener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.edit_item:
//handle menu1 click
break;
case R.id.delete_item:
tareasList.remove(position);
notifyItemRemoved(position);
Toast.makeText(context, "Tareas eliminada!", Toast.LENGTH_SHORT).show();
break;
}
return false;
}
});
//displaying the popup
popup.show();
}
});
And this is on the MainFragment
final Query tareasQuery = mTareasDatabase.child(userId);
tareasQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Tareas tareas = new Tareas();
tareas.setFecha(dataSnapshot.getValue(Tareas.class).getFecha());
tareas.setDescripcion(dataSnapshot.getValue(Tareas.class).getDescripcion());
tareas.setLista(dataSnapshot.getValue(Tareas.class).getLista());
tareas.setPrioridad(dataSnapshot.getValue(Tareas.class).getPrioridad());
mTareasList.add(tareas);
mTareasAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
String tareasId = dataSnapshot.getValue(Tareas.class).getTareasId();
mTareasDatabase.child(userId).child(tareasId).removeValue();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
String tareasId = dataSnapshot.getValue(Tareas.class).getTareasId();
mTareasDatabase.child(userId).child(tareasId).removeValue();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Everything is working fine, except that is not deleting it from the firebase
Solution
Remove the item from the firebase and the recycler view at the same time
case R.id.delete_item:
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
String tareasId = tareas.getTareasId();
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String userId = user.getUid();
DatabaseReference databaseReference = firebaseDatabase.getReference("Tareas")
.child(userId).child(tareasId);
databaseReference.removeValue();
tareasList.remove(position);
notifyItemRemoved(position);
Toast.makeText(context, "Tareas eliminada!", Toast.LENGTH_SHORT).show();
break;
Okay I solved it. I just had to add all the database references on the delete item, and remove it from the recycler view and the database at the same time
case R.id.delete_item:
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
String tareasId = tareas.getTareasId();
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String userId = user.getUid();
DatabaseReference databaseReference = firebaseDatabase.getReference("Tareas")
.child(userId).child(tareasId);
databaseReference.removeValue();
tareasList.remove(position);
notifyItemRemoved(position);
Toast.makeText(context, "Tareas eliminada!", Toast.LENGTH_SHORT).show();
break;
this is because you are deleting from the local list only. You have to remove the value from firebase too. For deleting use code
firebaseRef.removeValue();
In your firebaseRef you have to show which value you want to delete.
I am building an android instagram clone app with Firebase. I have enabled social media sharing buttons in my app to share the contents of a story via Facebook, email, WhatsApp, etc but don't know how to go about it.
Take a look at what I've tried:
public class InstacloneApp extends AppCompatActivity {
private RelativeLayout relativeLayout;
private ImageView postCoverImg, userPhotoUrl;
private TextView post_Title, post_Descpn, post_Author, postDate;
private Button commentsBtn;
private FloatingActionButton shareFAB;
private String post_details = null;
private FirebaseAuth mAuth;
private DatabaseReference postRef;
private Context mCtx = this;
private String uid_post = null;
private ScrollView scrollView;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insta_clone_app);
relativeLayout = (RelativeLayout) findViewById(R.id.activity_blog_posts_view);
scrollView = (ScrollView) findViewById(R.id.scrollView);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
post_details = getIntent().getExtras().getString("post+key");
postCoverImg = (ImageView) findViewById(R.id.post_Backdrop);
post_Title = (TextView) findViewById(R.id.post_title);
post_Descpn = (TextView) findViewById(R.id.post_description_long);
post_Author = (TextView) findViewById(R.id.authorTV);
userPhotoUrl = (ImageView) findViewById(R.id.author_photo);
postDate = (TextView) findViewById(R.id.post_date);
shareFAB = (FloatingActionButton) findViewById(R.id.shareFAB);
commentsBtn = (Button) findViewById(R.id.commentsBtn);
mAuth = FirebaseAuth.getInstance();
postRef = FirebaseDatabase.getInstance().getReference().child("Blog").child("All_Posts");
postRef.keepSynced(true);
postRef.child(post_details.toString()).addValueEventListener(new ValueEventListener() { // this is to retrieve and view the blog post data
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String title_post = (String) dataSnapshot.child("postTitle").getValue();
String desc_post = (String) dataSnapshot.child("full_postDesc").getValue();
String backdrop_post = (String) dataSnapshot.child("postImage").getValue();
String date_post = (String) dataSnapshot.child("postDate").getValue();
uid_post = (String) dataSnapshot.child("uid").getValue();
post_Title.setText(title_post);
post_Descpn.setText(desc_post);
postDate.setText(date_post);
Glide.with(mCtx).load(backdrop_post).into(postCoverImg);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
shareFAB.setOnClickListener(new View.OnClickListener() { // my implemented share action
#Override
public void onClick(View view) {
String content = post_details;
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("*/*");
shareIntent.putExtra(Intent.EXTRA_TEXT,content);
startActivity(Intent.createChooser(shareIntent,"Share With"));
}
});
Since your sharing the post content try changing your
from:
intent.setType("*/*");
To:
intent.setType("text/plain");
I assume you want to share Image and Text(description or some other details) both for that you can have a look at this question
If you want to add a link to your app, something like in apps like Reddit/Instagram have a look at this question
You can combine both to share the Image and Text (url + small description/username) to any app that accepts it like WhatsApp
Hope it helped!
You should try
shareIntent.setType("text/plain");
instead of
shareIntent.setType("*/*");