Images not loading from URL by Picasso from Firebase Database - android

Firebase image
Model class
public class Category
{
private String Name;
private String Image;
public Category(String name, String image) {
Name = name;
Image = image;
}
public Category() {
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
}
Activity class
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference reference;
FirebaseStorage storage;
StorageReference storageReference;
//Add new menu
MaterialEditText edtTxtName;
Button selectImage;
Button uploadImage;
//Adding new category
Category newCategory;
Uri savedImageUri;
private final int PICK_IMAGE_REQUEST=71;
MaterialEditText edtTxtNewCategoryName;
FloatingActionButton fab;
FirebaseRecyclerAdapter<Category,MenuViewHolder> recyclerAdapter;
TextView userName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
edtTxtNewCategoryName=findViewById(R.id.edt_txt_new_item_name);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("Menu Mangement");
setSupportActionBar(toolbar);
fab =findViewById(R.id.fab);
//Firebase init
database=FirebaseDatabase.getInstance();
reference=database.getReference("Category");
storage=FirebaseStorage.getInstance();
storageReference=storage.getReference();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDailog();
}
});
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);
//Setting header name
/* View view=navigationView.getHeaderView(0);
userName = view.findViewById(R.id.username);
userName.setText(Common.currentUser.getName());*/
//View init
recyclerView=findViewById(R.id.recycler_menu);
layoutManager=new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
loadMenu();
}
private void selectImage() {
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode==PICK_IMAGE_REQUEST && resultCode==Activity.RESULT_OK
&& data!=null && data.getData()!=null)
{
savedImageUri=data.getData();//getting uri
selectImage.setText("Image Selected !");
}
}
private void uploadImage() {
final ProgressDialog progressDialog=new ProgressDialog(this);
progressDialog.setMessage("Uploading Image");
progressDialog.show();
String image= UUID.randomUUID().toString();
final StorageReference imageFolder=storageReference.child("images/"+image);
imageFolder.putFile(savedImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(Home.this, "Uploaded", Toast.LENGTH_SHORT).show();
imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
{
#Override
public void onSuccess(Uri uri)
{
newCategory=new Category(edtTxtName.getText().toString(),uri.toString());
Toast.makeText(Home.this, ""+uri.toString(), Toast.LENGTH_SHORT).show();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Home.this, ""+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 "+progress+" %");
}
});
}
private void showDailog() {
final AlertDialog.Builder alertDailog=new AlertDialog.Builder(this);
alertDailog.setTitle("Add new Category");
alertDailog.setMessage("Please fill all the fields");
LayoutInflater inflater=this.getLayoutInflater();
View view=inflater.inflate(R.layout.add_new_menu_layout,null);
edtTxtName=view.findViewById(R.id.edt_txt_new_item_name);
alertDailog.setView(view);
alertDailog.setIcon(R.drawable.ic_shopping_cart_black_24dp);
alertDailog.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(newCategory!=null){
reference.push().setValue(newCategory);
}
}
});
alertDailog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDailog.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDailog.show();
}
private void loadMenu()
{
recyclerAdapter=new FirebaseRecyclerAdapter<Category, MenuViewHolder>(
Category.class,R.layout.menu_layout,
MenuViewHolder.class,reference) {
#Override
protected void populateViewHolder(MenuViewHolder viewHolder, final Category model, int position)
{
viewHolder.menuName.setText(model.getName());
Picasso.get().load(model.getImage()).into(viewHolder.imageView);
viewHolder.setItemClickListner(new ItemClickListner() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
//Getting menuId
Intent intent=new Intent(Home.this,FoodList.class);
intent.putExtra("CategoryId",recyclerAdapter.getRef(position).getKey());
startActivity(intent);
}
});
}
};
recyclerAdapter.notifyDataSetChanged();//notifiy us if data has been changed.
recyclerView.setAdapter(recyclerAdapter);
}
In activity class,firebase adapter is implemented.by refrence of firebase database ,images are loading with only id "-LO061DOhjG2hVZlqY79" but with id's like '01' '02' are not loading
Adapter is loading images very slow
Output of this code
Help will highly appreciated

Because you are using private fields and public getters and setters, the name of your fields in your Category class, doesn't matter. If you want to use different names in your class than in the database, you might use an annotation called PropertyName in front of the getter.
images are loading with the only id "-LO061DOhjG2hVZlqY79" but with id's like '01' '02' are not loading
As I see in your screenshot, the image of the first element "01" with the name "Finger Foods" is displayed correctly in the UI. So it doesn't matter if the children have a key that looks like this 01, 02, or -LO061DOhjG2hVZlqY79 the data should be displayed. As a matter of fact, it is displayed, the name of the next item, "Western Soups" is displayed, so most likely the problem is with your URL. So please make sure that the URL actually exists and has it contains a valid image.

Related

I need to get user image from firebase to show it on ViewHolder after user uplaoded thier image in profile activity

I have a profile activity that user upload their profile images, user uploads 2 images ( back and front) the images are showing fine in the profile activity, but I also want to show one of this image (back or front) in another activity ( ViewHolder activity ). I have tried many things but couldn't figure out as i am only testing how firebase works, I really appreciate if someone can help me here.
Here is my profile activity where user upload images to firebase.
public class ProfileActivity extends AppCompatActivity implements View.OnClickListener{
private ImageView backimage;
private CircleImageView profileimage;
TextView totalscore,correctattempts,totalattempts,user_name,java_score,python_score,php_score,android_score,phone_number;
private Uri filepath;
private final int PICK_IMAGE_REQUEST = 71;
private int id;
StorageReference storageReference;
DatabaseReference users,defaultimages,scoretbl;
String Storage_Path = "All_Image_Uploads/";
// Root Database Name for Firebase Database.
public static final String Database_Path = "All_Image_Uploads_Database";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_profile);
storageReference = FirebaseStorage.getInstance().getReference();
users = FirebaseDatabase.getInstance().getReference("Users");
defaultimages = FirebaseDatabase.getInstance().getReference("Database_Path");
java_score=findViewById(R.id.javascore);
phone_number=findViewById(R.id.user_phonenumber);
python_score=findViewById(R.id.pythonscore);
php_score=findViewById(R.id.phpscore);
android_score =findViewById(R.id.androidscore);
backimage = findViewById(R.id.header_cover_image);
profileimage=findViewById(R.id.user_profile_photo);
totalattempts=findViewById(R.id.questionsattempted);
correctattempts=findViewById(R.id.correctattempts);
totalscore=findViewById(R.id.totalscore);
user_name =findViewById(R.id.user_profile_name);
backimage.setOnClickListener(this);
profileimage.setOnClickListener(this);
user_name.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
user_name.setText(Common.currentUser.getUserName());
phone_number.setText(Common.currentUser.getEmail());
users.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
/* String score=dataSnapshot.child(Common.currentuser.getUsername()).child("totalScore").getValue().toString();
totalscore.setText(score);
String tattempts=dataSnapshot.child(Common.currentuser.getUsername()).child("questionsAttempted").getValue().toString();
totalattempts.setText(tattempts);
String cattempts=dataSnapshot.child(Common.currentuser.getUsername()).child("correctAttempts").getValue().toString();
correctattempts.setText(cattempts);
phone_number.setText(Common.currentuser.getEmail());
*/
Picasso.with(getBaseContext()).load(dataSnapshot.child(Common.currentUser.getUserName()).child("pathtobackimage").getValue().toString())
.into(backimage);
Picasso.with(getBaseContext()).load(dataSnapshot.child(Common.currentUser.getUserName()).child("pathtoprofileimage").getValue().toString())
.into(profileimage);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
/*
scoretbl.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.child("Java").exists())
java_score.setText(dataSnapshot.child("Java").child("score").getValue().toString());
if(dataSnapshot.child("Python").exists())
python_score.setText(dataSnapshot.child("Python").child("score").getValue().toString());
if(dataSnapshot.child("PHP").exists())
php_score.setText(dataSnapshot.child("PHP").child("score").getValue().toString());
if(dataSnapshot.child("Android").exists())
android_score.setText(dataSnapshot.child("Android").child("score").getValue().toString());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
*/
}
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST&&resultCode ==RESULT_OK
&& data !=null && data.getData()!= null){
filepath = data.getData();
if(id==R.id.header_cover_image)
Picasso.with(this).load(filepath).into(backimage);
else
Picasso.with(this).load(filepath).into(profileimage);
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.header_cover_image:{
id = R.id.header_cover_image;
chooseImage();
uploadImageback();
break;
}
case R.id.user_profile_photo:{
id = R.id.user_profile_photo;
chooseImage();
uploadImageprofile();
break;
}
}
}
private void uploadImageback() {
final StorageReference backref = storageReference.child("images/").
child(Common.currentUser.getUserName()+"/"+ Common.currentUser.getUserName()+"back");
if(filepath!=null){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading..");
progressDialog.show();
backref.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
backref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
users.child(Common.currentUser.getUserName()).child("pathtobackimage").setValue(uri.toString());
Toast.makeText(ProfileActivity.this,"Uploaded",Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ProfileActivity.this,"Not Uploaded",Toast.LENGTH_LONG).show();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(ProfileActivity.this,"Failure",Toast.LENGTH_LONG).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 uploadImageprofile() {
if(filepath!=null){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading.. ");
progressDialog.show();
final StorageReference profileref = storageReference.child("images/").
child(Common.currentUser.getUserName()+"/"+ Common.currentUser.getUserName()+"profile");
profileref.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
profileref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
users.child(Common.currentUser.getUserName()).child("pathtoprofileimage").setValue(uri.toString());
Toast.makeText(ProfileActivity.this,"Profile Uploaded",Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ProfileActivity.this,"Profile not Uploaded",Toast.LENGTH_LONG).show();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(ProfileActivity.this,"Failure",Toast.LENGTH_LONG).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+" %");
}
});
}
}
}
and I want to show one of these image in my ViewHolder activity as you can see the text view (name and score are showing) which is coming from a ranking Fragment activity
public class RankingViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView name_text,score_text;
private ItemClickListener itemClickListener;
public RankingViewHolder(View itemView) {
super(itemView);
name_text = (TextView) itemView.findViewById(R.id.name_text);
score_text = (TextView) itemView.findViewById(R.id.score_text);
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View view) {
itemClickListener.onClick(view,getAdapterPosition(),false);
}
}
and the Fragment activity
public class RankingFragment extends Fragment {
View myFragment;
FirebaseDatabase database;
RecyclerView rankingList;
LinearLayoutManager layoutManager;
FirebaseRecyclerAdapter<Ranking,RankingViewHolder> adapter;
DatabaseReference questionScore,rankingTable;
int sum = 0; //score is default by zero
public static RankingFragment newInstance(){
RankingFragment rankingFragment = new RankingFragment();
return rankingFragment ;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
database = FirebaseDatabase.getInstance();
questionScore = database.getReference("Question_Score");
rankingTable = database.getReference("Ranking");
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
myFragment = inflater.inflate(R.layout.fragment_ranking,container,false);
rankingList = (RecyclerView) myFragment.findViewById(R.id.ranking_list);
layoutManager = new LinearLayoutManager(getActivity());
rankingList.setHasFixedSize(true);
//Using orderByChild method , this will sort the ranking in ascending order
//reverse the data by using layout manager
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
rankingList.setLayoutManager(layoutManager);
updateScore(Common.currentUser.getUserName(), new RankingCallBack<Ranking>() {
#Override
public void callBack(Ranking ranking) {
//Ranking Score update
rankingTable.child(ranking.getUserName())
.setValue(ranking);
// showRanking();
}
});
adapter = new FirebaseRecyclerAdapter<Ranking, RankingViewHolder>(
Ranking.class,
R.layout.ranking_layout,
RankingViewHolder.class,
rankingTable.orderByChild("score")
) {
#Override
protected void populateViewHolder(RankingViewHolder viewHolder, final Ranking model, int position) {
viewHolder.name_text.setText(model.getUserName());
viewHolder.score_text.setText(String.valueOf(model.getScore()));
//prevent crash when user click
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Intent scoreDetail = new Intent(getActivity(),Score_Detail.class);
scoreDetail.putExtra("viewUser",model.getUserName());
startActivity(scoreDetail);
}
});
}
};
adapter.notifyDataSetChanged();
rankingList.setAdapter(adapter);
return myFragment;
}
private void updateScore(final String userName, final RankingCallBack<Ranking> callBack) {
questionScore.orderByChild("user").equalTo(userName)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot data:dataSnapshot.getChildren())
{
Question_Score quest = data.getValue(Question_Score.class);
sum += Integer.parseInt(quest.getScore());
}
Ranking ranking = new Ranking(userName,sum);
callBack.callBack(ranking);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
and here is my Ranking class
public class Ranking {
private String userName;
private long score;
private String urlProfilePic;
public Ranking(){
}
public Ranking(String userName, long score, String pathtobackimage ) {
this.userName = userName;
this.score = score;
this.urlProfilePic = pathtobackimage;
}
public String getUrlProfilePic() {
return urlProfilePic;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public long getScore() {
return score;
}
public void setScore(long score) {
this.score = score;
}
}
Here the screen shot to help more how I wanted
I put my comment in answer field because of this restriction: 'You must have 50 reputation to comment'.
Anyway, back to your question. One solution would be to save the current user 'key' to a SharedPreference file. In your new Activity, use that 'key' to retrieve the data from Firebase.
EDIT: Added solution
Quoted: "...and I want to show one of these image in my ViewHolder activity as you can see the text view (name and score are showing) which is coming from a ranking Fragment activity..."
Solution: Search for fixme. In RankingViewHolder class, add:
public class RankingViewHolder extends ...
//...
public TextView name_text, score_text;
public ImageView profileImageView; //fixme
//...
public RankingViewHolder(View itemView) {
//...
score_text = (TextView) itemView.findViewById(R.id.score_text);
profileImageView = (ImageView) itemView.findViewById(R.id.profile_image_view); //fixme
//...
Inside populateViewHolder()
viewHolder.score_text.setText(String.valueOf(model.getScore()));
Picasso.with(getContext()) //fixme
.load(Common.currentUser.getUrlProfilePic()) //fixme
.into(viewHolder.profileImageView); //fixme
Inside RankingFragment class, since you are already using Common.currentUser.getUserName(), might as well create another variable under it to store the url link to the user's profile picture, and retrieve the link via Common.currentUser.getUrlProfilePic().
EDIT#2:
The images stored in FB storage have this links:
gs://FIXME_FIREBASE.com/images/userName/userNameback.jpeg
gs://FIXME_FIREBASE.com/images/userName/userNameprofile.jpeg
However to use in Picasso, need this kind of links:
https://firebasestorage.googleapis.com/v0/b/FIXME/o/FIXME/images/userName/userNameback.jpeg?alt=media&token=FIXME
Question is how to get that?
One solution is that after you successfully upload the image, get the download url (example below).
The tricky part is that the download url is not immediately available, and you have to use .getMetadata(), .getDownloadUrl() to do that.
Once the url is received, you have to figure out how to save this link to the user's profile in your FB database.
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
StorageMetadata storageMetadata = taskSnapshot.getMetadata();
StorageReference reference = storageMetadata.getReference();
reference.getDownloadUrl() // Get the download URL for the file
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Log.i(TAG, uri.toString()); //fixme: save this to user's profile
}
});
}
Inside populateViewHolder, you are using Ranking model that contains the username and score.
Modify that Ranking model class to add an additional String variable urlProfilePic that contains the url to the user's image (above result), and generate the getter for it called getUrlProfilePic(). Then you can use it in this way inside the populateViewHolder:
viewHolder.score_text.setText(String.valueOf(model.getScore()));
Picasso.with(getContext())
.load(model.getUrlProfilePic()) //fixme
.into(viewHolder.profileImageView);

77/5000 RecyclerView shows only duplicates of the same item from the firestore database [duplicate]

Firebase image
Model class
public class Category
{
private String Name;
private String Image;
public Category(String name, String image) {
Name = name;
Image = image;
}
public Category() {
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
}
Activity class
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference reference;
FirebaseStorage storage;
StorageReference storageReference;
//Add new menu
MaterialEditText edtTxtName;
Button selectImage;
Button uploadImage;
//Adding new category
Category newCategory;
Uri savedImageUri;
private final int PICK_IMAGE_REQUEST=71;
MaterialEditText edtTxtNewCategoryName;
FloatingActionButton fab;
FirebaseRecyclerAdapter<Category,MenuViewHolder> recyclerAdapter;
TextView userName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
edtTxtNewCategoryName=findViewById(R.id.edt_txt_new_item_name);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("Menu Mangement");
setSupportActionBar(toolbar);
fab =findViewById(R.id.fab);
//Firebase init
database=FirebaseDatabase.getInstance();
reference=database.getReference("Category");
storage=FirebaseStorage.getInstance();
storageReference=storage.getReference();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDailog();
}
});
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);
//Setting header name
/* View view=navigationView.getHeaderView(0);
userName = view.findViewById(R.id.username);
userName.setText(Common.currentUser.getName());*/
//View init
recyclerView=findViewById(R.id.recycler_menu);
layoutManager=new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
loadMenu();
}
private void selectImage() {
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode==PICK_IMAGE_REQUEST && resultCode==Activity.RESULT_OK
&& data!=null && data.getData()!=null)
{
savedImageUri=data.getData();//getting uri
selectImage.setText("Image Selected !");
}
}
private void uploadImage() {
final ProgressDialog progressDialog=new ProgressDialog(this);
progressDialog.setMessage("Uploading Image");
progressDialog.show();
String image= UUID.randomUUID().toString();
final StorageReference imageFolder=storageReference.child("images/"+image);
imageFolder.putFile(savedImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(Home.this, "Uploaded", Toast.LENGTH_SHORT).show();
imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
{
#Override
public void onSuccess(Uri uri)
{
newCategory=new Category(edtTxtName.getText().toString(),uri.toString());
Toast.makeText(Home.this, ""+uri.toString(), Toast.LENGTH_SHORT).show();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Home.this, ""+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 "+progress+" %");
}
});
}
private void showDailog() {
final AlertDialog.Builder alertDailog=new AlertDialog.Builder(this);
alertDailog.setTitle("Add new Category");
alertDailog.setMessage("Please fill all the fields");
LayoutInflater inflater=this.getLayoutInflater();
View view=inflater.inflate(R.layout.add_new_menu_layout,null);
edtTxtName=view.findViewById(R.id.edt_txt_new_item_name);
alertDailog.setView(view);
alertDailog.setIcon(R.drawable.ic_shopping_cart_black_24dp);
alertDailog.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(newCategory!=null){
reference.push().setValue(newCategory);
}
}
});
alertDailog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDailog.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDailog.show();
}
private void loadMenu()
{
recyclerAdapter=new FirebaseRecyclerAdapter<Category, MenuViewHolder>(
Category.class,R.layout.menu_layout,
MenuViewHolder.class,reference) {
#Override
protected void populateViewHolder(MenuViewHolder viewHolder, final Category model, int position)
{
viewHolder.menuName.setText(model.getName());
Picasso.get().load(model.getImage()).into(viewHolder.imageView);
viewHolder.setItemClickListner(new ItemClickListner() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
//Getting menuId
Intent intent=new Intent(Home.this,FoodList.class);
intent.putExtra("CategoryId",recyclerAdapter.getRef(position).getKey());
startActivity(intent);
}
});
}
};
recyclerAdapter.notifyDataSetChanged();//notifiy us if data has been changed.
recyclerView.setAdapter(recyclerAdapter);
}
In activity class,firebase adapter is implemented.by refrence of firebase database ,images are loading with only id "-LO061DOhjG2hVZlqY79" but with id's like '01' '02' are not loading
Adapter is loading images very slow
Output of this code
Help will highly appreciated
Because you are using private fields and public getters and setters, the name of your fields in your Category class, doesn't matter. If you want to use different names in your class than in the database, you might use an annotation called PropertyName in front of the getter.
images are loading with the only id "-LO061DOhjG2hVZlqY79" but with id's like '01' '02' are not loading
As I see in your screenshot, the image of the first element "01" with the name "Finger Foods" is displayed correctly in the UI. So it doesn't matter if the children have a key that looks like this 01, 02, or -LO061DOhjG2hVZlqY79 the data should be displayed. As a matter of fact, it is displayed, the name of the next item, "Western Soups" is displayed, so most likely the problem is with your URL. So please make sure that the URL actually exists and has it contains a valid image.

Image is not retrieved in ImageView of RecyclerView from Firebase

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()

Displaying images from Firebase DB that's stored in Firebase Storage

I am making a fitness android application and I am storing progress images of Users using the Firebase Storage. A reference to the Firebase Database is also made with the URL of the image thats found in Firebase Storage.
I am attempting to retrieve the images and show them in a GridLayout but am recieveing a 'Bound to Type Error'
I am displaying the images using a recyclerView.
I am also using Picasso to load the image.
Photo Activity
public class PhotosActivity extends BaseActivity {
#BindView(R.id.activity_photos_fab)
FloatingActionButton newPhoto;
private StorageReference mStorage;
private ProgressDialog mProgressDialog;
RecyclerView recyclerView;
FirebaseRecyclerAdapter adapter;
private static final int GALLERY_INTENT = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photos);
ButterKnife.bind(this);
mStorage = FirebaseStorage.getInstance().getReference();
mProgressDialog = new ProgressDialog(this);
recyclerView = (RecyclerView) findViewById(R.id.activity_photos_recyclerView);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_INTENT && resultCode == RESULT_OK) {
mProgressDialog.setTitle("Uploading..");
mProgressDialog.show();
// Get the URI of the photo
Uri uri = data.getData();
StorageReference filepath = mStorage.child("Photos").child(userEmail).child(uri.getLastPathSegment());
Firebase photosReference = new Firebase(Utils.FIRE_BASE_PHOTOS_REFERENCE + userEmail);
// Add the photo to the database
// if successful then show a toast to say a photo has been added
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(), "You added a photo", Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
}
});
String photoURL = filepath.getDownloadUrl().toString();
bus.post(new PhotoService.AddPhotoRequest(photoURL, userEmail));
}
}
#Override
protected void onResume() {
super.onResume();
Firebase photosReference = new Firebase(Utils.FIRE_BASE_PHOTOS_REFERENCE + userEmail);
Query sortQuery = photosReference.orderByKey();
adapter = new FirebaseRecyclerAdapter<Photo, PhotoViewHolder>(Photo.class,
R.layout.list_individual_photo,
PhotoViewHolder.class,
sortQuery) {
#Override
protected void populateViewHolder(PhotoViewHolder photoViewHolder, Photo photo, int i) {
photoViewHolder.populate(PhotosActivity.this, photo);
}
};
GridLayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 4);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
#Override
protected void onPause() {
super.onPause();
adapter.cleanup();
}
#OnClick(R.id.activity_photos_fab)
public void setNewPhoto() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
}
}
PhotoViewHolder
public class PhotoViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.list_individual_photo_imageView)
ImageView photoImage;
#BindView(R.id.list_individual_photo_progressBar)
ProgressBar photoProgressBar;
public PhotoViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public void populate (Context context, Photo photo) {
itemView.setTag(photo);
Picasso.with(context).load(photo.getPhotoURl())
.fit()
.centerCrop()
.into(photoImage, new Callback() {
#Override
public void onSuccess() {
photoProgressBar.setVisibility(View.GONE);
}
#Override
public void onError() {
}
});
}
}
LivePhotoService
public class LivePhotoService extends BaseLiveService {
#Subscribe
public void getPhotos(final PhotoService.GetPhotoRequest request) {
final PhotoService.GetPhotoResponse response = new PhotoService.GetPhotoResponse();
response.valueEventListener = request.firebase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
response.photo = dataSnapshot.getValue(Photo.class);
if(response.photo != null) {
bus.post(response);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Toast.makeText(application.getApplicationContext(), firebaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
Photo Object
public class Photo {
private String photoID;
private String photoURl;
private HashMap<String, Object> photoDate;
private String ownerEmail;
public Photo(String photoID, String photoURl, HashMap photoDate, String ownerEmail) {
this.photoID = photoID;
this.photoURl = photoURl;
this.photoDate = photoDate;
this.ownerEmail = ownerEmail;
}
public String getPhotoID() {
return photoID;
}
public String getPhotoURl() {
return photoURl;
}
public HashMap getPhotoDate() {
return photoDate;
}
public String getOwnerEmail() {
return ownerEmail;
}
}
Consider using Firebase-UI Android library which gives you ability to load images from storage ref directly. In your case it would look something like this
I'm not sure if Picasso is supported but you can use Glide
For example:
mStorageRef = FirebaseStorage.getInstance().getReference();
Glide.with(this /* context */)
.using(new FirebaseImageLoader())
.load(mStorageRef + "/Photos/" + userId)
.error(R.drawable.default)
.into(imageView);

RecyclerView isn't showing data until refreshed

I'm using Firebase to populate my RecyclerView, but the problem is that every time I open the app, I need to swipe down to refresh and then the list of items is available.
Here is my code
public class MainActivity extends AppCompatActivity {
private static final int RC_PHOTO_PICKER = 2;
DatabaseReference db;
FirebaseHelper helper;
MyAdapter adapter;
RecyclerView rv;
EditText nameEditTxt,grpTxt,descTxt,linkTxt;
FirebaseAuth.AuthStateListener authListener;
SwipeRefreshLayout swipeRefresh;
Uri downloadUrl;
String Admin_code;
FirebaseStorage mfirebaseStorage;
private StorageReference mEventPhotoReference;
FloatingActionButton fab;
SharedPreferences sharedPreferences;
ProgressBar spinner;
static boolean calledAlready=false;
public MyAdapter adapter1;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
spinner = (ProgressBar)findViewById(R.id.progressBar);
spinner.setVisibility(View.GONE);
mfirebaseStorage=FirebaseStorage.getInstance();
if(!calledAlready){
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
calledAlready=true;
}
swipeRefresh=(SwipeRefreshLayout)findViewById(R.id.swiperefresh);
//SETUP RECYCLER
rv = (RecyclerView) findViewById(R.id.rv);
rv.setLayoutManager(new LinearLayoutManager(this));
//INITIALIZE FIREBASE DB
db= FirebaseDatabase.getInstance().getReference();
mEventPhotoReference=mfirebaseStorage.getReference().child("Event Photos");
helper=new FirebaseHelper(db);
//ADAPTER
adapter=new MyAdapter(this,helper.retrieve());
rv.setAdapter(adapter);
adapter.notifyDataSetChanged();
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
rv.setAdapter(adapter);
swipeRefresh.setRefreshing(false);
}
});
sharedPreferences= PreferenceManager.getDefaultSharedPreferences(this);
Admin_code=sharedPreferences.getString(getString(R.string.Admin_code),getString(R.string.Admin_default_value));
Log.e("MainActivity","" + Admin_code);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
displayInputDialog();
}
});
fab.setVisibility(View.GONE);
showBtn();
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onResume() {
showBtn();
super.onResume();
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void showBtn(){
Admin_code=sharedPreferences.getString(getString(R.string.Admin_code),getString(R.string.Admin_default_value));
if(Objects.equals(Admin_code, "28011996")){
fab.setVisibility(View.VISIBLE);
}
else
fab.setVisibility(View.GONE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_logout) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
return true;
}
if(id==R.id.settings){
Intent settingsIntent=new Intent(this,Settings.class);
startActivity(settingsIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ((requestCode& 0xffff) == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
StorageReference photoRef=mEventPhotoReference.child(selectedImageUri.getLastPathSegment());
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
downloadUrl = taskSnapshot.getDownloadUrl();
Toast.makeText(MainActivity.this,"Photo selected successfully",Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this,"there was a problem uploading photo",Toast.LENGTH_LONG).show();
}
});
}
}
//DISPLAY INPUT DIALOG
private void displayInputDialog()
{
Dialog d=new Dialog(this);
d.setTitle("Save To Firebase");
d.setContentView(R.layout.input_dialog);
nameEditTxt= (EditText) d.findViewById(R.id.nameEditText);
grpTxt= (EditText) d.findViewById(R.id.propellantEditText);
descTxt= (EditText) d.findViewById(R.id.descEditText);
Button saveBtn= (Button) d.findViewById(R.id.saveBtn);
Button photoBtn=(Button)d.findViewById(R.id.photoBtn);
linkTxt = (EditText) d.findViewById(R.id.linkEditText);
photoBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
}
});
//SAVE
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//GET DATA
String name=nameEditTxt.getText().toString();
String propellant=grpTxt.getText().toString();
String desc=descTxt.getText().toString();
String link=linkTxt.getText().toString();
Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();
//SET DATA
Spacecraft s=new Spacecraft();
s.setName(name);
s.setPropellant(propellant);
s.setDescription(desc);
s.setLink(link);
s.setImageUrl(downloadUrl.toString());
s.setTimestamp(ts);
//SIMPLE VALIDATION
if(name != null && name.length()>0)
{
//THEN SAVE
if(helper.save(s))
{
//IF SAVED CLEAR EDITXT
nameEditTxt.setText("");
grpTxt.setText("");
descTxt.setText("");
linkTxt.setText("");
downloadUrl=null;
adapter=new MyAdapter(MainActivity.this,helper.retrieve());
rv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}else
{
Toast.makeText(MainActivity.this, "Name Must Not Be Empty", Toast.LENGTH_SHORT).show();
}
}
});
d.show();
}
After Searching for a while, I found out that I should use notifyDataSetChanged(); but it doesn't work.
Here is my helper class where I'm fetching data:
public class FirebaseHelper {
DatabaseReference db;
Boolean saved=null;
ArrayList<Spacecraft> spacecrafts=new ArrayList<>();
public FirebaseHelper(DatabaseReference db) {
this.db = db;
}
//WRITE IF NOT NULL
public Boolean save(Spacecraft spacecraft)
{
if(spacecraft==null)
{
saved=false;
}else
{
try
{
db.child("Spacecraft").push().setValue(spacecraft);
saved=true;
}catch (DatabaseException e)
{
e.printStackTrace();
saved=false;
}
}
return saved;
}
//IMPLEMENT FETCH DATA AND FILL ARRAYLIST
private void fetchData(DataSnapshot dataSnapshot)
{
spacecrafts.clear();
for (DataSnapshot ds : dataSnapshot.getChildren())
{
Spacecraft spacecraft=ds.getValue(Spacecraft.class);
spacecrafts.add(spacecraft);
}
}
//READ THEN RETURN ARRAYLIST
public ArrayList<Spacecraft> retrieve() {
db.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
fetchData(dataSnapshot);
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return spacecrafts;
}
It'll be great if someone could help me out here. This is the last problem in my project.
The problem is due to the adapter not knowing about the data that has been fetched asynchronously. Let's try to look at your code step-by-step:
adapter = new MyAdapter(this, helper.retrieve());
helper.retrieve() will initiate an asynchronous request to fetch data from firebase and immediately returns an empty ArrayList (as the data from firebase hasn't reached the app yet).
rv.setAdapter(adapter);
This line sets the adapter to recyclerView, which has an empty arraylist as data, so it won't show anything on the UI.
After the data is received from firebase, ArrayList<Spacecraft> spacecrafts is updated with new data. But the adapter is not notified about this new data. Ideally, adapter.notifyDataSetChanged() should be called after new data is put into the array list.
Hence, when you swipe to refresh after the initial call, the adapter is set to recycler view, leading to an internal call to notifyDataSetChanged(), which in turn loads the new data on to the UI.
Easiest solution is to notify the adapter when new data is received from Firebase. Below is the pseudo code for it -
Create an interface OnFirebaseDataChanged and add a method void dataChanged(); to it.
MainAcitivty should implement this interface and the implementation of that method should call adapter.notifyDataSetChanged()
helper = new FirebaseHelper(db); should be changed to helper = new FirebaseHelper(db, this);
FirebaseHelper's constructor should have a 2nd parameter of type OnFirebaseDataChanged and should save it in a field called dataChangeListener.
Add a line at the end of fetchData method in FirebaseHelper dataChangeListener.dataChanged();
The ideal solution would be to architect the code differently, but that topic is out of scope of this question.

Categories

Resources