I want to link a TextView value to my database item ID. And then get the children that are under my database item in a TextView.
When I scan a Barcode with the value 7, I also want the to populate a TextView with for example toolName from the database Item with ID 7.
I've tried and tried, but I don't know how to complete this.
MainActivity:
public class UserMainActivity extends AppCompatActivity {
TextView textusername, textworkid, textuserloggedin;
Button btnalltools, qrscan;
DatabaseReference databaseUsers, databaseTools;
FirebaseAuth firebaseAuth;
FirebaseUser user;
String userID;
String toolid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_main);
firebaseAuth = FirebaseAuth.getInstance();
databaseTools = FirebaseDatabase.getInstance("").getReference("Tools");
textusername = (TextView)findViewById(R.id.tv_textusername);
textworkid = (TextView)findViewById(R.id.tv_textuserworkid);
qrscan = (Button)findViewById(R.id.btn_qrscantoolactivity);
qrscan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IntentIntegrator intentIntegrator = new IntentIntegrator(UserMainActivity.this);
intentIntegrator.setPrompt("For flash use volume up key");
intentIntegrator.setBeepEnabled(true);
intentIntegrator.setOrientationLocked(true);
intentIntegrator.setCaptureActivity(Capture.class);
intentIntegrator.initiateScan();
}
});
btnalltools = (Button)findViewById(R.id.btn_alltoollist);
btnalltools.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(UserMainActivity.this, ToollistAllActivity.class);
startActivity(intent1);
}
});
user = FirebaseAuth.getInstance().getCurrentUser();
databaseUsers = FirebaseDatabase.getInstance("").getReference("Users");
userID = user.getUid();
toolid = databaseTools.getKey();
databaseUsers.child(userID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
User userprofile = snapshot.getValue(User.class);
if (userprofile != null) {
String user = userprofile.getUserName();
String userid = userprofile.getUserWorkId();
textusername.setText(user);
textworkid.setText(userid);
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable #org.jetbrains.annotations.Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (intentResult.getContents() != null){
AlertDialog.Builder builder = new AlertDialog.Builder(UserMainActivity.this);
builder.setMessage(intentResult.getContents());
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
dialog.dismiss();
}
});
builder.show();
}else{
Toast.makeText(getApplicationContext(), "Opps", Toast.LENGTH_SHORT).show();
}
}
I've tried something like this:
IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (intentResult.getContents() != null){
TextView tv1 = dialog.findViewById(R.id.tv1);
TextView tv2 = dialog.findViewById(R.id.tv2);
tv1.setText(intentResult.getContents());
databaseTools.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
if (snapshot.hasChildren()){
if (tv1.getText().toString().equals(databaseTools)){
Tool tools = snapshot.getValue(Tool.class);
String tt = tools.getToolID();
tv2.setText(tt);
}
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
}
});
I've got it to work with this:
Query gettool = databaseTools.orderByChild("toolID").equalTo(tv1.getText().toString());
gettool.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
if (snapshot.exists()){
for (DataSnapshot snapshot1 : snapshot.getChildren()){
Tool tools = snapshot1.getValue(Tool.class);
String tt = tools.getToolName();
tv2.setText(tt);
}
Related
I had user shared preferences to get the current Uid or other Uid from realtime database. But I need to do the same without the use of shared preferences. This is for my ProfileActivity and I am using viewpager with three different fragments. The shared preferences show only the current user's profile even when searched for other user in the app.
The image attached is the output of the profile activity in my smartphone. The top bar containing the username and the logout button is of the profile activity and the rest below the blue banner is of the viewpager
public class ProfileActivity extends AppCompatActivity {
private ImageView logout;
private TextView post;
private FloatingActionButton floatingActionButton;
private TabLayout tabLayout;
private ViewPager viewPager;
private TextView username;
private FirebaseUser fUser;
private DatabaseReference databaseReference;
private FirebaseDatabase firebaseDatabase;
private FirebaseAuth firebaseAuth;
String profileId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
fUser = FirebaseAuth.getInstance().getCurrentUser();
firebaseAuth = FirebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference()
.child("Users").child(Objects.requireNonNull(firebaseAuth.getUid()));
String data = getBaseContext().getSharedPreferences("PROFILE", Context.MODE_PRIVATE)
.getString("profileId", "none");
if (data.equals("none")){
profileId = fUser.getUid();
} else{
profileId = data;
}
logout = findViewById(R.id.log_out);
username = findViewById(R.id.username);
floatingActionButton = findViewById(R.id.floatingActionButton);
post = findViewById(R.id.posts_account);
tabLayout = findViewById(R.id.tab_layout);
viewPager = findViewById(R.id.view_pager);
tabLayout.setupWithViewPager(viewPager);
VPAdapter vpAdapter = new VPAdapter(getSupportFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
vpAdapter.addFragment(new Profile(), "Profile");
vpAdapter.addFragment(new MyPosts(), "Posts");
if (profileId.equals(fUser.getUid())){
vpAdapter.addFragment(new SavedPosts(), "Saved");
}
viewPager.setAdapter(vpAdapter);
getPostCount();
userInfo();
getSupportActionBar().hide();
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ProfileActivity.this, PostActivity.class));
finish();
}
});
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog alertDialog = new AlertDialog.Builder(ProfileActivity.this).create();
alertDialog.setTitle("Are you sure to logout?");
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(ProfileActivity.this, StartActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK));
finish();
}
});
alertDialog.show();
alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE)
.setTextColor(ContextCompat.getColor(ProfileActivity.this, R.color.colorRed));
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
.setTextColor(ContextCompat.getColor(ProfileActivity.this, R.color.colorRed));
}
});
}
private void getPostCount() {
FirebaseDatabase.getInstance().getReference().child("Posts").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
int counter = 0;
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Posts posts = snapshot.getValue(Posts.class);
if (posts.getPublisher().equals(profileId)) counter ++;
}
post.setText(String.valueOf(counter));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void userInfo() {
FirebaseDatabase.getInstance().getReference().child("Users").child(profileId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
username.setText("#" + user.getUsername());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
The above is the code of the profile activity
public class MyPosts extends Fragment {
private RecyclerView recyclerView;
private PostAdapter photoAdapter;
private List<Posts> myPhotoList;
private FirebaseUser fUser;
String profileId;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_my_thoughts, container, false);
fUser = FirebaseAuth.getInstance().getCurrentUser();
String data = getContext().getSharedPreferences("PROFILE", Context.MODE_PRIVATE)
.getString("profileId", "none");
if (data.equals("none")){
profileId = fUser.getUid();
} else{
profileId = data;
}
recyclerView = view.findViewById(R.id.recycler_view_pictures);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 1));
myPhotoList = new ArrayList<>();
photoAdapter = new PostAdapter(getContext(), myPhotoList);
recyclerView.setAdapter(photoAdapter);
myPhotos();
return view;
}
private void myPhotos() {
FirebaseDatabase.getInstance().getReference().child("Posts").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
myPhotoList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Posts post = snapshot.getValue(Posts.class);
if (post.getPublisher().equals(profileId)){
myPhotoList.add(post);
}
}
Collections.reverse(myPhotoList);
photoAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
the above is the code for the posts fragments inside the viewpager of the profile activity
public class Profile extends Fragment {
private CircleImageView imageProfile;
private TextView followers;
private TextView following;
private TextView fullname;
private TextView bio;
private CircleImageView verification;
private TextView usernamebottom;
private Button editProfile;
private FirebaseUser fUser;
String profileId;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_profile, container, false);
fUser = FirebaseAuth.getInstance().getCurrentUser();
String data = getContext().getSharedPreferences("PROFILE", Context.MODE_PRIVATE)
.getString("profileId", "none");
if (data.equals("none")){
profileId = fUser.getUid();
} else{
profileId = data;
getContext().getSharedPreferences("PROFILE", Context.MODE_PRIVATE).edit().clear().apply();
}
imageProfile = view.findViewById(R.id.image_profile);
verification = view.findViewById(R.id.verification_profile);
followers = view.findViewById(R.id.followers);
following = view.findViewById(R.id.following);
fullname = view.findViewById(R.id.full_name);
bio = view.findViewById(R.id.bio);
usernamebottom = view.findViewById(R.id.username_btm);
editProfile = view.findViewById(R.id.edit_profile);
getFollowersAndFollowingCount();
userInfo();
if (profileId.equals(fUser.getUid())){
editProfile.setText("Edit profile");
} else {
checkFollowingStatus();
}
editProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String btnText = editProfile.getText().toString();
if (btnText.equals("Edit profile")){
//Go to edit profile
startActivity(new Intent(getContext(), EditProfileActivity.class));
} else{
if (btnText.equals("follow")){
FirebaseDatabase.getInstance().getReference().child("Follow").child(fUser.getUid())
.child("following").child(profileId).setValue(true);
FirebaseDatabase.getInstance().getReference().child("Follow")
.child(profileId).child("followers").child(fUser.getUid()).setValue(true);
} else {
FirebaseDatabase.getInstance().getReference().child("Follow").child(fUser.getUid())
.child("following").child(profileId).removeValue();
FirebaseDatabase.getInstance().getReference().child("Follow")
.child(profileId).child("followers").child(fUser.getUid()).removeValue();
}
}
}
});
return view;
}
private void checkFollowingStatus() {
FirebaseDatabase.getInstance().getReference().child("Follow").child(fUser.getUid()).child("following")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(profileId).exists()) {
editProfile.setText("following");
} else {
editProfile.setText("follow");
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void getFollowersAndFollowingCount() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Follow").child(profileId);
ref.child("followers").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
followers.setText("" + dataSnapshot.getChildrenCount());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
ref.child("following").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
following.setText("" + dataSnapshot.getChildrenCount());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void userInfo() {
FirebaseDatabase.getInstance().getReference().child("Users").child(profileId).addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
if (user.getImageurl().equals("default")){
imageProfile.setImageResource(R.drawable.ic_empty_profile);
} else {
Picasso.get().load(user.getImageurl()).into(imageProfile);
}
usernamebottom.setText("#" + user.getUsername());
fullname.setText(user.getName());
bio.setText(user.getBio());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
The above is the code of the user detail fragment also in the view pager of my profile activity
For the first time I want to change my value of the data in a recycler view holder, it is works, but once I click to change the value again in the same recycler view holder, it can't works and it still retrieve the old data. I tried the method like adapter.notifyDataSetChanged() but it seems like not work.
public class Admin_admittutorpage extends AppCompatActivity implements myadapter_tutorlist.OnNoteListener {
//private static final String TAG = "Sometry" ;
RecyclerView recview;
myadapter_tutorlist adapter;
public static ArrayList<User> allUser =new ArrayList<>();
AlertDialog.Builder builder;
DatabaseReference mroot ;
private FirebaseAuth mFirebaseAuth;
public void addUserInfo(User muser){
allUser.add(muser);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_admittutorpage);
recview = (RecyclerView)findViewById(R.id.admin_tutor_recyclerview);
recview.setLayoutManager(new LinearLayoutManager(this));
FirebaseRecyclerOptions<User> options = new FirebaseRecyclerOptions.Builder<User>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("Users").orderByChild("role").equalTo("Tutor"),
User.class).build();
adapter = new myadapter_tutorlist(options, this);
recview.setAdapter(adapter);
}
#Override
protected void onStart(){
super.onStart();
adapter.startListening();
}
#Override
protected void onStop(){
super.onStop();
adapter.stopListening();
}
#Override
public void onNoteClick(final int position) {
//Log.d(TAG, "trytry" + allUser.get(position).getUsername());
builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.dialog_message).setTitle(R.string.dialog_title);
builder.setMessage("Do you want to delete or activate tutor account ?")
.setCancelable(false)
.setPositiveButton("Unactivate", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button dialog.cancel();
Toast.makeText(getApplicationContext(), "you choose to unactivate tutor account", Toast.LENGTH_SHORT).show();
final String selectedEmail = allUser.get(position).getEmail();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
String myemail = ds.child("email").getValue().toString();
if(selectedEmail.equals(myemail)){
if(allUser.get(position).getActive().equals(true)) {
ds.getRef().child("active").setValue(false);
}
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
};
usersRef.addListenerForSingleValueEvent(eventListener);
}
})
.setNeutralButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getApplicationContext(), "you choose to delete tutor account", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("Activate", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'YES' Button
Toast.makeText(getApplicationContext(), "you choose to activate tutor account", Toast.LENGTH_SHORT).show();
if (allUser.get(position).getActive().equals(true)) {
Toast.makeText(getApplicationContext(), "The tutor account is already in active status", Toast.LENGTH_SHORT).show();
} else {
final String selectedEmail = allUser.get(position).getEmail();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersdRef = rootRef.child("Users");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String myemail = ds.child("email").getValue().toString();
if (selectedEmail.equals(myemail)) {
if (allUser.get(position).getActive().equals(false)) {
ds.getRef().child("active").setValue(true);
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
usersdRef.addListenerForSingleValueEvent(eventListener);
}
}
});
//Creating dialog box
AlertDialog alert = builder.create();
//Setting the title manually
alert.setTitle("Account Activation Alert");
alert.show();
}
}
I am having difficulty setting an ImageView with a string download url that is in a user object that came from the firebase storage DB. The method setImage() is saying the Imageview is a null object and this is true as I have tried to debug it and it comes up as null. How can I resolve this. I think it has something to do with the anonymous inner class.
public class DashBoard extends AppCompatActivity {
private FirebaseAuth mAuth;
private ArrayList<String> motivatingMessages;
private Button gymLocations, profile,health;
public ImageView profileImageView;
private TextView welcome;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showProfilePicture();
profileImageView = findViewById(R.id.personalProfile);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
setContentView(R.layout.activity_dash_board);
//getSupportActionBar().setTitle("Welcome To Bodify");
profile = findViewById(R.id.buttonProfile);
gymLocations = findViewById(R.id.gymFinderButton);
health = findViewById(R.id.healthButton);
welcome = findViewById(R.id.welcomeUser);
final String userID = mAuth.getUid();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("User").child(userID);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
if (user != null) {
welcome.setText("User Logged in: ");
welcome.append(user.getUserName());
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(DashBoard.this, "Error Occurred: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
gymLocations.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), GymsNearMe.class));
}
});
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), PersonalProfile.class));
}
});
health.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(DashBoard.this,Health.class));
}
});
}
public void showProfilePicture() {
mAuth = FirebaseAuth.getInstance();
final String userID = mAuth.getUid();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("User").child(userID);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
String image = user.getmImageUrl();
setImage(image);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(DashBoard.this, "Error Occurred: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public void setImage(String image) {
Picasso.get().load(image).into(profileImageView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.logOut) {
mAuth.signOut();
startActivity(new Intent(getApplicationContext(), LogIn.class));
}
return true;
}
}
enter code here
It looks like you are trying to find the view before inflating the layout:
profileImageView = findViewById(R.id.personalProfile);
move that line after the inflation so after the line:
setContentView(R.layout.activity_dash_board);
In other words, the order of the lines should be:
setContentView(R.layout.activity_dash_board);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
profileImageView = findViewById(R.id.personalProfile);
showProfilePicture();
and you do not need to set the mAuth again in the showProfilePicture
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dash_board);
profileImageView = findViewById(R.id.personalProfile);
profile = findViewById(R.id.buttonProfile);
gymLocations = findViewById(R.id.gymFinderButton);
health = findViewById(R.id.healthButton);
welcome = findViewById(R.id.welcomeUser);
showProfilePicture();
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
try with this order
I have a list that I get from firebase, this list is about posts and what I need is when user like it or unlike it, the list updated through adapter. as I used recyclerview and adapter to show my data after receiving it from firebase. Actually, everything works so fine with me but just this issue when user like or unlike the post it goes crazy. I tried to make a toast to make sure that I'm working with the same position as I expected and it proved me right.
the photo of the post appears and disappears by clicking like button like the vides shows and it does not updating the data in a proper way like it mess with the number of likes
You can find my code below with a video to illustrate the problem I am facing.
I hope somebody can help me out.
private void read_posts() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
reference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
//post_models.clear();
Post_Model post_model = dataSnapshot.getValue(Post_Model.class);
post_models.add(post_model);
post_adapter = new Post_Adapter(post_models, getContext());
recyclerviewNewsfeed.setAdapter(post_adapter);
progressBar.setVisibility(View.GONE);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Post_Model post_model = dataSnapshot.getValue(Post_Model.class);
for (int i=0;i<post_models.size();i++){
if(post_models.get(i).getId().equals(post_model.getId())){
post_models.set(i,post_model);
post_adapter.notifyItemChanged(i);
break;
}
}
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
It's my post adapter
public class Post_Adapter extends RecyclerView.Adapter<Post_Adapter.Viewholder> {
private Context context;
private List<Post_Model> post_models;
FirebaseUser firebaseUser;
List<Like_Model> like_modelList, likeblue_modelList;
View_Photos_Adapter view_Photos_adapter;
boolean userlikeit;
public static int positionn=-1;
public Post_Adapter(List<Post_Model> post_models, Context context) {
this.context = context;
this.post_models = post_models;
}
#NonNull
#Override
public Viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.post_item, parent, false);
return new Viewholder(view);
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull final Viewholder holder, final int position) {
final Post_Model post_model = post_models.get(position);
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference referencee = FirebaseDatabase.getInstance().getReference("Posts").child(post_model.getId());
referencee.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//Toast.makeText(CommentActivity.this, post_id+"", Toast.LENGTH_SHORT).show();
Post_Model post_modell = dataSnapshot.getValue(Post_Model.class);
// Toast.makeText(CommentActivity.this, post_id+"", Toast.LENGTH_SHORT).show();
if (post_modell.getLikeModels() != null) {
for (int i = 0; i < post_modell.getLikeModels().size(); i++) {
if (post_modell.getLikeModels().get(i).getUserid().equals(firebaseUser.getUid())) {
userlikeit = true;
break;
} else {
userlikeit = false;
}
}
} else {
userlikeit = false;
}
//snapshot.getRef().removeValue();
// Toast.makeText(context, userlikeit+"58", Toast.LENGTH_SHORT).show();
//Toast.makeText(CommentActivity.this, comment_models.size()+"", Toast.LENGTH_SHORT).show();
if (userlikeit) {
holder.likebluebtn.setVisibility(View.VISIBLE);
holder.likebtn.setVisibility(View.GONE);
} else {
holder.likebtn.setVisibility(View.VISIBLE);
holder.likebluebtn.setVisibility(View.GONE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
if (post_model.getUserid().equals(firebaseUser.getUid())) {
holder.editbtn.setVisibility(View.VISIBLE);
holder.deletebtn.setVisibility(View.VISIBLE);
} else {
holder.editbtn.setVisibility(View.GONE);
holder.deletebtn.setVisibility(View.GONE);
}
holder.editbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.postTextView.setVisibility(View.GONE);
holder.postEditText.setVisibility(View.VISIBLE);
holder.postEditText.setText(post_model.getPost());
holder.editbtn.setVisibility(View.GONE);
holder.savebtn.setVisibility(View.VISIBLE);
}
});
holder.savebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Post_Model post_modell = new Post_Model(post_model.getId(), post_model.getUserid()
, holder.postEditText.getText().toString(), post_model.getTime()
, post_model.getCommentModels(), post_model.getPostphotos(), post_model.getLikeModels());
FirebaseDatabase.getInstance().getReference("Posts")
.child(post_model.getId())
.setValue(post_modell);
holder.postTextView.setVisibility(View.VISIBLE);
holder.postEditText.setVisibility(View.GONE);
holder.editbtn.setVisibility(View.VISIBLE);
holder.savebtn.setVisibility(View.GONE);
Toast.makeText(context, "Post has been edited successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, NewsfeedActivity.class);
context.startActivity(intent);
((Activity) context).overridePendingTransition(R.anim.slide_in_right, R.anim.slide_in_left);
((Activity) context).finish();
}
});
holder.deletebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(context)
.setTitle("Delete Post")
.setMessage("Are you sure you want to delete this post?")
// Specifying a listener allows you to take an action before dismissing the dialog.
// The dialog is automatically dismissed when a dialog button is clicked.
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
final DatabaseReference referencee = FirebaseDatabase.getInstance().getReference("Posts")
.child(post_model.getId());
referencee.removeValue();
Toast.makeText(context, "Post deleted successfully", Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, NewsfeedActivity.class);
context.startActivity(intent);
((Activity) context).overridePendingTransition(R.anim.slide_in_right, R.anim.slide_in_left);
((Activity) context).finish();
}
})
// A null listener allows the button to dismiss the dialog and take no further action.
.setNegativeButton(android.R.string.no, null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
});
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
like_modelList = new ArrayList<>();
likeblue_modelList = new ArrayList<>();
//Toast.makeText(context, read_likes(post_model.getId())+"", Toast.LENGTH_SHORT).show();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
// Toast.makeText(Create_Coworking_SpaceActivity.this, "111111111", Toast.LENGTH_LONG).show();
if (user.getId().equals(post_model.getUserid())) {
if (user.getImageURL().equals("default")) {
holder.userImage.setImageResource(R.drawable.ic_imgprofile);
} else {
Glide.with(holder.itemView).load(user.getImageURL()).into( holder.userImage);
}
holder.username.setText(user.getUsername());
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
if (post_model.getPostphotos() == null) {
holder.postPhotosRC.setVisibility(View.GONE);
} else {
holder.postPhotosRC.setHasFixedSize(true);
holder.postPhotosRC.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
view_Photos_adapter = new View_Photos_Adapter(post_model.getPostphotos(), context);
holder.postPhotosRC.setAdapter(view_Photos_adapter);
}
holder.postTextView.setText(post_model.getPost());
holder.posttimeTextView.setText(post_model.getTime());
holder.commentbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, CommentActivity.class);
intent.putExtra("post_id", post_model.getId());
context.startActivity(intent);
((Activity) context).overridePendingTransition(R.anim.slide_in_right, R.anim.slide_in_left);
}
});
if (post_model.getCommentModels() != null) {
holder.numofcommentsEditText.setText(post_model.getCommentModels().size() + "");
holder.numofcommentsTextView.setText(post_model.getCommentModels().size() + "");
}
final int[] li = {0};
holder.likebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
like(post_model.getId());
// Post_Adapter.this.notifyItemChanged(position);
positionn=position;
}
});
holder.likebluebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, userlikeit+"5", Toast.LENGTH_SHORT).show();
unlike(post_model.getId());
// Post_Adapter.this.notifyItemChanged(position);
positionn=position;
}
});
if (post_model.getLikeModels() != null) {
holder.numoflikesEditText.setText(post_model.getLikeModels().size() + "");
holder.numoflikesTextView.setText(post_model.getLikeModels().size() + "");
}
holder.likesTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, LikeActivity.class);
intent.putExtra("post_id", post_model.getId());
context.startActivity(intent);
((Activity) context).overridePendingTransition(R.anim.slide_in_right, R.anim.slide_in_left);
}
});
holder.commentsTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, CommentActivity.class);
intent.putExtra("post_id", post_model.getId());
context.startActivity(intent);
((Activity)
context).overridePendingTransition(R.anim.slide_in_right,
R.anim.slide_in_left);
}
});
}
#Override
public int getItemCount() {
return post_models == null ? 0 : post_models.size();
}
Hello I'm trying to create a profile screen where the user can upload their own profile image and change the ImageView into something that they've uploaded. But upon using this Upload profile image for a user Firebase as a reference I encountered an error when I'm starting to upload the images to the database.
My Code
public class userMain extends Fragment {
private TextView userfirstName,usersecondName,userNumber,userGender,userEmail,userDate;
private Button btnChoose, btnUpload;
private ImageView imageView;
private Uri filePath;
private FirebaseStorage storage;
private StorageReference storageReference;
private final int PICK_IMAGE_REQUEST = 71;
public userMain() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_user_main, container, false);
btnUpload = (Button) view.findViewById(R.id.savePhoto);
imageView = (ImageView) view.findViewById(R.id.imageView3);
userfirstName = (TextView) view.findViewById(R.id.firstnametv);
usersecondName = (TextView) view.findViewById(R.id.secondnametv);
userNumber = (TextView) view.findViewById(R.id.numbertv);
userGender = (TextView) view.findViewById(R.id.gendertv);
userEmail = (TextView) view.findViewById(R.id.emailtv);
userDate = (TextView) view.findViewById(R.id.datetv);
FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
String useruid=user.getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Accounts").child("Users").child(useruid);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chooseImage();
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadImage();
}
});
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String firstname = dataSnapshot.child("first").getValue(String.class);
String secondname = dataSnapshot.child("second").getValue(String.class);
String number = dataSnapshot.child("number").getValue(String.class);
String gender = dataSnapshot.child("gender").getValue(String.class);
String email = dataSnapshot.child("email").getValue(String.class);
String date = dataSnapshot.child("date").getValue(String.class);
userfirstName.setText(firstname);
usersecondName.setText(secondname);
userNumber.setText(number);
userGender.setText(gender);
userEmail.setText(email);
userDate.setText(date);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return view;
}
private void uploadImage() {
if(filePath != null)
{
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(getContext(), "Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getContext(), "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
}
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
String useruid=user.getUid();
final DatabaseReference img = FirebaseDatabase.getInstance().getReference().child("Accounts").child("Users").child(useruid);
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null )
{
filePath = data.getData();
StorageReference filepath= storageReference.child("Images").child(filePath.getLastPathSegment());
filepath.putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
img.child("image").setValue(downloadUrl);
}
});
}
}
}
Change this:
StorageReference filepath= storageReference.child("Images").child(filePath.getLastPathSegment());
filepath.putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
img.child("image").setValue(downloadUrl);
}
to this:
StorageReference filepath= storageReference.child("Images").child(filePath.getLastPathSegment());
filepath.putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String downloadUrl = taskSnapshot.getDownloadUrl().toString()
img.child("image").setValue(downloadUrl);
}
saving the downloadUrl as string in your firebase database