How to upload multiple images to firebase database and retrieve - java

How to store all images in Firebase database under at index values.
This is sample screenshot of my firebase database structure
This is my photos uploading class but images are storing using single id and single image url only. How to upload multiple images to firebase database and retrieve . Please Help me and im new to firebase database multiple images uploading.
public class PhotoUploadActivity extends AppCompatActivity implements View.OnClickListener {
private String mListID,mInspectionID;
private FirebaseStorage firebaseStorage;
private StorageReference storageReference;
private Button openCustomGallery;
private Button mUploadPhoto;
private GridView selectedImageGridView;
private static final int CustomGallerySelectId = 1;//Set Intent Id
public static final String CustomGalleryIntentKey = "ImageArray";//Set Intent Key Value
private List<String> selectedImages;
private GalleryAdapter adapter;
private String imagesArray;
private String timestampString;
private String formattedTimestamp;
private Long timestamp;
private int failUplaod;
private int successUpload;
private ProgressDialog uploadProgress;
private String pathPhoto;
private String remarkPhoto;
private int currentprogress;
private ImageView currentImage;
private String mTestID;
private ArrayList<String > blogimages;
private String mKeyID, mAddress, mLocationKey, mRegion;
private HashMap<String,Object> photos = new HashMap<>();
private HashMap<String, String> metadata = new HashMap<>();
public static boolean loaded = false;
StorageReference mstorageReference;
DatabaseReference mdatabaseReference;
FirebaseAuth firebaseAuth;
DatabaseReference userdatabaseReference;
EditText desc;
Button upload;
private ProgressDialog mProgressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_selected);
setTitle("Write Post");
mProgressbar = new ProgressDialog(this);
initViews();
setListeners();
mstorageReference = FirebaseStorage.getInstance().getReference();
mdatabaseReference = FirebaseDatabase.getInstance().getReference().child("Blog");
firebaseAuth = FirebaseAuth.getInstance();
userdatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(firebaseAuth.getCurrentUser().getUid());
upload = (Button)findViewById(R.id.new_post_submit);
desc = (EditText)findViewById(R.id.new_post_text);
upload.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
UploadTask uploadTask;
if( selectedImageGridView.getChildCount()!= 0)
{
blogimages = new ArrayList<>();
mProgressbar.setMessage("Post Uploading_Please Wait.....");
mProgressbar.show();
for ( int i = 0; i < selectedImages.size(); i++) {
Uri uri = Uri.parse("file://"+selectedImages.get(i));
Log.v("URIIII", String.valueOf(uri));
final String CurrentUser = firebaseAuth.getCurrentUser().getUid();
StorageReference reference = mstorageReference.child("Blog_pics/users").child(uri.getLastPathSegment());
uploadTask = reference.putFile(uri);
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
//todo: if want to make this the full progress bar, just need to make this as the sum of all progress and add to the main progress dialog
double progress = (100.0 * (taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount());
mProgressbar.setMessage("Uploading Images.....");
mProgressbar.show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
final Uri downloaduri = taskSnapshot.getDownloadUrl();
Log.v("DOWNLOAD URI", String.valueOf(downloaduri));
blogimages.add(downloaduri.toString());
Log.v("BLOGGIMAGES", String.valueOf(blogimages));
// final String path= uri.getLastPathSegment();
final String key = mdatabaseReference.push().getKey();
final String posttitle = desc.getText().toString();
final String CurrentUser = firebaseAuth.getCurrentUser().getUid();
userdatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date today = Calendar.getInstance().getTime();
final String current_time = df.format(today);
Blog blog = new Blog();
long millis = System.currentTimeMillis();
int timestamp = ((int) (millis/1000))* -1;
blog.setTimestamp(current_time);
blog.setTime(timestamp);
blog.setTitle(posttitle);
blog.setUrl(blogimages);
blog.setUid(firebaseAuth.getCurrentUser().getUid());
blog.setUsername(dataSnapshot.child("name").getValue().toString());
blog.setImage(dataSnapshot.child("image").getValue().toString());
mdatabaseReference.child(key).setValue(blog) .addOnSuccessListener(new OnSuccessListener<Void>()
{
#Override
public void onSuccess(Void aVoid)
{
Intent mm = new Intent(PhotoUploadActivity.this, MainActivity.class);
startActivity(mm);
}
}).addOnFailureListener(new OnFailureListener()
{
#Override
public void onFailure(#NonNull Exception e)
{
Toast.makeText(PhotoUploadActivity.this,"Failed to post the blog.. Try again later",Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onCancelled(DatabaseError error) {
}
});
}
}) .addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}else
{
Toast.makeText(PhotoUploadActivity.this,"Please enter all fields and Select images.",Toast.LENGTH_LONG).show();
}
}
});
selectedImageGridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder deleteDialog = new AlertDialog.Builder(PhotoUploadActivity.this)
.setTitle("Delete Item?")
.setMessage("Do you want to remove this item?")
.setNegativeButton("No", null)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
adapter.removeitem(position);
adapter.notifyDataSetChanged();
/*Or you can do it this way if the top one doesnt work:
selectedImageGridView.setAdapter(null);*/
}
});
deleteDialog.create().show();
return true;
}
});
}
private void initViews() {
openCustomGallery = (Button) findViewById(R.id.openCustomGallery);
selectedImageGridView = (GridView) findViewById(R.id.selectedImagesGridView);
// mUploadPhoto = (Button) findViewById(R.id.UploadPhotos);
}
//set Listeners
private void setListeners() {
openCustomGallery.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.openCustomGallery:
//Start Custom Gallery Activity by passing intent id
Intent intent = new Intent(PhotoUploadActivity.this, CustomGalleryActivity.class);
startActivityForResult(intent, CustomGallerySelectId);
break;
}
}
#Override
protected void onActivityResult(int requestcode, int resultcode, Intent imagereturnintent) {
super.onActivityResult(requestcode, resultcode, imagereturnintent);
switch (requestcode) {
case CustomGallerySelectId:
if (resultcode == RESULT_OK) {
imagesArray = imagereturnintent.getStringExtra(CustomGalleryIntentKey);//get Intent data
//Convert string array into List by splitting by ',' and substring after '[' and before ']'
selectedImages = Arrays.asList(imagesArray.substring(1, imagesArray.length() - 1).split(", "));
//loadGridView(new ArrayList<String>(selectedImages));//call load gridview method by passing converted list into arrayList
adapter = new GalleryAdapter(PhotoUploadActivity.this,new ArrayList<>(selectedImages),false);
selectedImageGridView.setAdapter(adapter);
}
break;
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
//I'm saving the instance state of photos.. let's see how
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("Photos",photos);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
savedInstanceState.getSerializable("Photos");
}
}

To solve this, store the image urls in a Map. Your database structure should look like this:
Firebase-root
|
--- Blog
|
--- blogId
|
--- urls
| |
| --- "https://firebasestorage...": true
| |
| --- "https://firebasestorage...": true
|
--- //the other blog details
To display all those images, just get the urls object, which is a map and iterate to get the keys which are actual the urls of your photos.
Edit:
There is also an alternative structure which looks like this:
Firebase-root
|
--- Blog
|
--- blogId
|
--- urls
| |
| --- pushedKeyOne: "https://firebasestorage..."
| |
| --- pushedKeyTwo: "https://firebasestorage..."
|
--- //the other blog details

Related

How to retrieve latest entry from the firebase realtime database?

I am trying to take inputs from one user and send the same data to another user. I am not sure what to put as an argument in child so that it refers to the same data and I can retrieve and show the data to another user for approval. I am able to send the image but for the data fields like visitor,mobile and flat not sure what to do.
My code is as follows.
Data entry File Code
public class Main4Activity extends AppCompatActivity {
private static final int PERMISSION_CODE = 1000;
private static final int IMAGE_CAPTURE_CODE = 1001;
Button btn;
ImageView imageView;
static Uri image_uri;
ImageView mImageView;
TextView mCaptureBtn;
Button uploadbtn;
static String downloadurl;
public static String Dvisitor;
public static String Dmobile;
static DatabaseReference reff;
//for upload
private Uri filePath;
private final int PICK_IMAGE_REQUEST = 71;
FirebaseStorage storage;
StorageReference storageReference;
//for upload
static String URL;
//Data store of Visitor
static EditText visitor;
static EditText mbnumber;
EditText bnmbr;
static EditText fnmbr;
EditText emal;
EditText pswrd;
HashMap<String,Object> map = new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
//for upload
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
//for upload
mImageView = (ImageView) findViewById(R.id.imageView2);
mCaptureBtn = (TextView) findViewById(R.id.textView4);
//Data for Visitor
visitor = (EditText) findViewById(R.id.vname);
mbnumber = (EditText) findViewById(R.id.mnumber);
bnmbr = (EditText) findViewById(R.id.blknmbr);
fnmbr = (EditText) findViewById(R.id.fltnmbr);
emal = (EditText) findViewById(R.id.emailId);
pswrd = (EditText) findViewById(R.id.passwordfield2);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
upload();
FirebaseDatabase.getInstance().getReference().child("Image").push().setValue(map)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
map.put("visitor",visitor.getText().toString());
map.put("mobile",mbnumber.getText().toString());
map.put("block",bnmbr.getText().toString());
map.put("flat",fnmbr.getText().toString());
map.put("email",emal.getText().toString());
map.put("password",pswrd.getText().toString());
Toast.makeText(Main4Activity.this, "Successful data registration", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Main4Activity.this, "Failed data registration", Toast.LENGTH_SHORT).show();
}
});
}
});
//Camera functionality click and upload starts
mCaptureBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
String[] permission = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permission, PERMISSION_CODE);
} else {
openCamera();
}
} else {
openCamera();
}
}
});
imageView = (ImageView) findViewById(R.id.imageView);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main4Activity.this, MainActivity.class);
startActivity(intent);
}
});
}
private void openCamera() {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From the Camera");
image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_CAPTURE_CODE);
{
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSION_CODE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openCamera();
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
mImageView.setImageURI(image_uri);
}
}
private void upload(){
if(image_uri != null)
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
final StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
ref.putFile(image_uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(Main4Activity.this, "Uploaded", Toast.LENGTH_SHORT).show();
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
DatabaseReference imagestore = FirebaseDatabase.getInstance().getReference().child("Image").push();
//HashMap<String, String> hasmap = new HashMap<>();
URL = uri.toString();
map.put("imgurl",URL);
//map.put("imageurl", String.valueOf(uri));
imagestore.setValue(map).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Intent intent= new Intent(Main4Activity.this,Main5Activity.class);
startActivity(intent);
}
});
//This is your image url do whatever you want with it.
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Main4Activity.this, "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 + "%");
}
});
}
}
}
//Camera functionality click and upload starts
Code for another user to Approve
public class Main5Activity extends AppCompatActivity {
Button btnAllow, btnProhibit;
private String Dvisitor;
private String Dmobile;
private String Dflat;
DatabaseReference reff;
ImageView img;
private DatabaseReference Post;
static TextView textView;
String roadies;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main5);
btnAllow = (Button) findViewById(R.id.button);
btnProhibit = (Button) findViewById(R.id.button2);
textView = (TextView) findViewById(R.id.textView5);
img = (ImageView) findViewById(R.id.imageView3);
imageshow();
init();
readonetime();
}
private void readonetime() {
Query query = Post.orderByKey().limitToLast(1);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot child: dataSnapshot.getChildren()) {
String post = dataSnapshot.child("visitor").getValue(String.class);
String post1 = dataSnapshot.child("mobile").getValue(String.class);
String post2 = dataSnapshot.child("flat").getValue(String.class);
textView.setText("Mr. "+post+"with mobile number: " + post1+"wants to visit your flat: " + post2);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void init() {
Post = FirebaseDatabase.getInstance().getReference().child("Image");
}
private void imageshow() {
reff = FirebaseDatabase.getInstance().getReference().child("Image");
reff.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Picasso.get().load(Main4Activity.URL).fit().into(img);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(Main5Activity.this, "OoooooLalalala", Toast.LENGTH_SHORT).show();
}
});
btnAllow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main5Activity.this, Main8Activity.class);
startActivity(intent);
}
});
btnProhibit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main5Activity.this, Main9Activity.class);
startActivity(intent);
}
});
}
}
In your Main5Activity, I think:
This:
for(DataSnapshot child: dataSnapshot.getChildren()) {
String post = dataSnapshot.child("visitor").getValue(String.class);
String post1 = dataSnapshot.child("mobile").getValue(String.class);
String post2 = dataSnapshot.child("flat").getValue(String.class);
textView.setText("Mr. "+post+"with mobile number: " + post1+"wants to visit your flat: " + post2);
}
Must be like this:
for(DataSnapshot ds: dataSnapshot.getChildren()) {
String post = ds.child("visitor").getValue(String.class);
String post1 = ds.child("mobile").getValue(String.class);
String post2 = ds.child("flat").getValue(String.class);
textView.setText("Mr. "+post+"with mobile number: " + post1+"wants to visit your flat: " + post2);
}

First and last switch button getting triggred in recycler view

Hi I have switch button (switchTaskFinished) on my recycler view,when I am clicking any button, the last button is getting selected. Also when I press button it updates the data to firebase. And changes the button status accordingly. But even though buttons value is true it only updates last button status not others.
public class MyAdaptorUser extends RecyclerView.Adapter<MyAdaptorUser.myViewHolder> {
private Context context;
private ArrayList<TaskModel> taskLists;
private Switch switchTaskFinished;
private OnTaskClickListner mTaskListner;
private AlertDialog dialog;
private AlertDialog.Builder builder;
private TaskConfirmationSender taskConfirmationSender;
public MyAdaptorUser(Context c, ArrayList<TaskModel> t, OnTaskClickListner onTaskClickListner) {
context = c;
taskLists = t;
this.mTaskListner = onTaskClickListner;
}
#NonNull
#Override
public MyAdaptorUser.myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
builder = new AlertDialog.Builder(parent.getContext());
builder.setTitle("Please Wait").setView(R.layout.my_progress_view).setCancelable(false);
dialog = builder.create();
return new MyAdaptorUser.myViewHolder(LayoutInflater.from(context).inflate(R.layout.task_preview, parent, false), mTaskListner);
}
#Override
public void onBindViewHolder(#NonNull MyAdaptorUser.myViewHolder holder, final int position) {
//Set title and description to task preview textviews
holder.title.setText(taskLists.get(position).getTaskTitle());
holder.dueDate.setText(taskLists.get(position).getDueDate());
holder.description.setText(taskLists.get(position).getTaskDescription());
//Sets the path of database to taskAwatingConfirmation/task_title/UserEmail
final DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();
try {
String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
email = removeSpecialCharacter(email);
final DatabaseReference taskConfirmationRef = dbRef
.child("taskAwatingConfirmation")
.child(taskLists.get(position).getTaskTitle())
.child(email);
taskConfirmationRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//Fetching switchButton Status (Task finished) from database
switchTaskFinished.setChecked(false);
String buttonStatus = (String) dataSnapshot.child("buttonStatus").getValue();
if (buttonStatus != null) {
Log.d("taskerror", buttonStatus);
if (buttonStatus.equals("true")) {
switchTaskFinished.setChecked(true);
} else if (buttonStatus.equals("false")) {
switchTaskFinished.setChecked(false);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
switchTaskFinished.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(final CompoundButton buttonView, boolean isChecked) {
//dialog = builder.show();
taskConfirmationSender = new TaskConfirmationSender();
//When Task Finished button is clicked send data to database
sendConfirmationToAdmin(new FirebaseCallBack() {
#Override
public void Callback(TaskConfirmationSender taskConfirmationSender) {
taskConfirmationSender.setButtonStatus(String.valueOf(buttonView.isChecked()));
taskConfirmationSender.setTaskDueDate(taskLists.get(position).getDueDate());
if (buttonView.isChecked()) {
taskConfirmationRef.setValue(taskConfirmationSender).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
}
});
}else{
taskConfirmationRef.setValue(taskConfirmationSender).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
}
});
}
}
});
}
});
} catch (NullPointerException ignored) {
dialog.dismiss();
}
}
private String removeSpecialCharacter(String email) {
StringBuffer sbf = new StringBuffer(email);
email = String.valueOf(sbf.reverse());
int length = email.length();
email = email.substring(4, length);
StringBuffer stringBuffer = new StringBuffer(email);
email = String.valueOf(stringBuffer.reverse());
return email.replace("#", "_");
}
private void sendConfirmationToAdmin(final FirebaseCallBack firebaseCallBack) {
DatabaseReference volunteerRef = FirebaseDatabase.getInstance().getReference()
.child("Volunteer").child("Member")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
taskConfirmationSender = new TaskConfirmationSender();
try {
//Fetching details of users (full name, email) from database and setting their value to taskConfirmation Object
volunteerRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String userName = dataSnapshot.child("fullName").getValue().toString();
String userEmail = dataSnapshot.child("email").getValue().toString();
String userId = dataSnapshot.getKey();
//TODO: Fetch UID of user and set it to taskConfirmation OBject
taskConfirmationSender.setUserEmail(userEmail);
taskConfirmationSender.setUserName(userName);
taskConfirmationSender.setId(userId);
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
String submissionDate = day + "/" + month + "/" + year;
taskConfirmationSender.setSubmissionDate(submissionDate);
firebaseCallBack.Callback(taskConfirmationSender);
/**/
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
} catch (NullPointerException ee) {
}
}
private interface FirebaseCallBack {
void Callback(TaskConfirmationSender taskConfirmationSender);
}
#Override
public int getItemCount() {
return taskLists.size();
}
class myViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title, dueDate, description;
OnTaskClickListner onTaskClickListner;
public myViewHolder(#NonNull View itemView, OnTaskClickListner onTaskClickListner) {
super(itemView);
title = itemView.findViewById(R.id.taskTitle);
dueDate = itemView.findViewById(R.id.taskDueDate);
description = itemView.findViewById(R.id.taskDescription);
switchTaskFinished = itemView.findViewById(R.id.switchTaskFinished);
this.onTaskClickListner = onTaskClickListner;
ConstraintLayout taskBar = itemView.findViewById(R.id.linearLayoutTaskBar);
itemView.setOnClickListener(this);
//hides delete task button
taskBar.setVisibility(View.GONE);
}
#Override
public void onClick(View v) {
onTaskClickListner.onTaskClick(getAdapterPosition());
}
}
public interface OnTaskClickListner {
void onTaskClick(int position);
}
}
Maybe its because of the valueEventListener that stays attached:
Instead of this:
taskConfirmationRef.addValueEventListener(new ValueEventListener() {.........
Do this:
taskConfirmationRef.addListenerForSingleValueEvent(new ValueEventListener() {......
And set the switch to checked or unchecked when you turn on or off:
if (buttonView.isChecked()) {
//here
switchTaskFinished.setChecked(true);
taskConfirmationRef.setValue(taskConfirmationSender).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
}
});
}else{
//here
switchTaskFinished.setChecked(false);
...................

how can I get the products of the sellers

I have compared the others questions but they have different problems.
My question is, how can I display (on the user activity) all the products that the sellers have added on the firebase database?
The sellers have their own register and login activity before they add the products, meaning each seller will be having is own name or id.
You can check my database sample on the picture below.
**Sorry guys I have updated the code but now it is crashing the app every time I click the button to go to the add products activity**
public class SellerAddProductActivity extends AppCompatActivity {
private String saveCurrentDate;
private String saveCurrentTime;
private String CategoryName;
private String downloadImageUrl;
private String productRandomKey;
private String Description;
private String Price, Quantity, State;
private String Pname, Store;
private Button AddProductButton;
private EditText InputProductName;
private EditText InputProductPrice, InputStoreName;
private EditText InputProductDescription, InputProductQauntity, InputProductState;
private StorageReference ProductImageRef;
private Uri ImageUri;
private DatabaseReference ProductsRef, ProductsInfo;
private ProgressDialog loadingBar;
private static final int GalleryPick = 1;
private ImageView InputProductImage;
FirebaseUser currentUser;
FirebaseUser mAuth;
String userID = mAuth.getUid(); //--> Store each seller name with this ID
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seller_add_product);
ProductImageRef = FirebaseStorage.getInstance().getReference().child("Product Images");
CategoryName = getIntent().getExtras().get("category").toString();
ProductsRef = FirebaseDatabase.getInstance().getReference().child("Products");
ProductsInfo = FirebaseDatabase.getInstance().getReference().child("ProductsInfo");
mAuth = FirebaseAuth.getInstance().getCurrentUser();
AddProductButton = (Button) findViewById(R.id.add_product);
InputProductName = (EditText) findViewById(R.id.product_name);
InputProductImage = (ImageView) findViewById(R.id.product_image_select);
InputProductPrice = (EditText) findViewById(R.id.product_price);
InputProductQauntity = (EditText) findViewById(R.id.product_quantity);
InputProductState = (EditText) findViewById(R.id.product_state);
InputStoreName = (EditText) findViewById(R.id.store_name);
loadingBar = new ProgressDialog(this);
InputProductDescription = (EditText) findViewById(R.id.product_description);
InputProductImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
OpenGallery();
}
});
AddProductButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validateProductData();
}
});
}
private void OpenGallery() {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GalleryPick);
}
#Override
protected void onActivityResult
(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GalleryPick && resultCode == RESULT_OK && data != null) {
ImageUri = data.getData();
InputProductImage.setImageURI(ImageUri);
}
}
private void validateProductData() {
Description = InputProductDescription.getText().toString();
Price = InputProductPrice.getText().toString();
Pname = InputProductName.getText().toString();
Quantity = InputProductQauntity.getText().toString();
State = InputProductState.getText().toString();
Store = InputStoreName.getText().toString();
if (ImageUri == null) {
Toast.makeText(this, "Please Add Product Image!", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(Description)) {
Toast.makeText(this, "Please Enter the Product Description!", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(Price)) {
Toast.makeText(this, "Please Enter the Product Price!", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(Pname)) {
Toast.makeText(this, "Please Enter the Product Name!", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(Quantity)) {
Toast.makeText(this, "Enter Quantity in Number!", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(State)) {
Toast.makeText(this, "Specify the State of your Product!", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(Store)) {
Toast.makeText(this, "Store Name is Mandatory!", Toast.LENGTH_SHORT).show();
} else {
StoreProductInfo();
}
}
private void StoreProductInfo() {
loadingBar.setTitle("Adding Product");
loadingBar.setMessage("Please wait!");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
Calendar calendar = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy");
saveCurrentDate = currentDate.format(calendar.getTime());
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss a");
saveCurrentTime = currentTime.format(calendar.getTime());
// Unique Random Key for the Products added by the admin
productRandomKey = saveCurrentDate + saveCurrentTime;
// Unique Random Key to store the image added by the admin
final StorageReference filePath = ProductImageRef.
child(ImageUri.getLastPathSegment() + productRandomKey + ".jpg");
final UploadTask uploadTask = filePath.putFile(ImageUri);
//Displaying the Upload Error to the seller
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
String message = e.toString();
Toast.makeText(SellerAddProductActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(SellerAddProductActivity.this, "Image Uploaded!", Toast.LENGTH_SHORT).show();
Task<Uri> uriTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
downloadImageUrl = filePath.getDownloadUrl().toString();
return filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
downloadImageUrl = task.getResult().toString();
Toast.makeText(SellerAddProductActivity.this, "Product Image Added",
Toast.LENGTH_SHORT).show();
SaveProductInfoToDatabase();
}
}
});
}
});
}
private void SaveProductInfoToDatabase() {
HashMap<String, Object> productMap = new HashMap<>();
productMap.put("pid", productRandomKey);
productMap.put("storename", Store);
productMap.put("date", saveCurrentDate);
productMap.put("time", saveCurrentTime);
productMap.put("description", Description);
productMap.put("image", downloadImageUrl);
productMap.put("Category", CategoryName);
productMap.put("state", State);
productMap.put("quantity", Quantity);
productMap.put("price", Price);
productMap.put("pname", Pname);
ProductsRef.child("Products").child(userID).child(productRandomKey);
ProductsInfo.child(productRandomKey).updateChildren(productMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Intent intent = new Intent(SellerAddProductActivity.this, SellerAddProductActivity.class);
startActivity(intent);
loadingBar.dismiss();
Toast.makeText(SellerAddProductActivity.this, "Product
Added",Toast.LENGTH_SHORT).show();
} else {
loadingBar.dismiss();
String message = task.getException().toString();
Toast.makeText(SellerAddProductActivity.this,
"Error:"+message,Toast.LENGTH_SHORT).show();
}
}
});
} }
This how I'm displaying the products on the buyer/user activity
public class HomeActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener{
private DatabaseReference productsRef;
private RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
productsRef = FirebaseDatabase.getInstance().getReference().child("Products");
recyclerView = findViewById(R.id.recycler_menu);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<Products> options =
new FirebaseRecyclerOptions.Builder<Products>()
.setQuery(productsRef, Products.class).build();
FirebaseRecyclerAdapter<Products, ProductsViewHolder> adapter
= new FirebaseRecyclerAdapter<Products, ProductsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ProductsViewHolder holder,int position,#NonNull final Products model){
holder.txtProductName.setText(model.getPname());
holder.txtProductPrice.setText("Price " + model.getPrice() + "$");
Picasso.get().load(model.getImage()).into(holder.imageView);
//sending the product ID to the ProductDetailsActivity
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(HomeActivity.this, ProductDetailsActivity.class);
intent.putExtra("pid", model.getPid());
startActivity(intent);
}
});
}
#NonNull
#Override
public ProductsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_products,parent,false);
ProductsViewHolder holder = new ProductsViewHolder(view);
return holder;
}
};
GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(), 2);
recyclerView.setLayoutManager(gridLayoutManager);
adapter.startListening();
recyclerView.setAdapter(adapter);
}
As I understand, you want to bring up all the sellers information to the one logged in in your app.
To do that you can do a for loop inside products to get each seller id, and then querie each user to get the products.
But you will need to change your database structure to make it easier.
I recommend to you to store inside the nested child Products the id of that product to querie in another table. For example
Products
|
--- userID
|
--- Products
|
--- product_key1: true
|
--- product_key2: true
And then in another node have the information of that product
ProductsInfo
|
--- product_key1
| |
| --- productName: "Orange"
| |
| --- productPrice: 1
|
--- product_key2
|
--- productName: "Pineapple"
|
--- productPrice: 3
So now, we will just get each userID and get each user products
First, instead of hardcoded seller names you should use getUid() to get each seller unique UID.
FirebaseAuth mAuth;
mAuth = FirebaseAuth.getInstance().getCurrentUser();
String userID = mAuth.getUid(); //--> Store each seller name with this ID
Now we just loop inside Products to get each user ID
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userKey = ds.getKey();
Log.d("SellersID", userKey);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Now that you have all the sellers key you can loop inside products and get each product key for each seller, and with that you can now get the data from ProductsInfo node
Your problem is at your database reference productsRef
You should add more to your reference, based on what you want to get from your database:
productsRef = FirebaseDatabase.getInstance().getReference().child("Products").child("here you put seller name"); // in your case the seller name is "d"
Hope it helps. For more informations ask me

Upload Images to Firebase Storage and have a link in Firebase Database

I am currently working on an Incident Reporting application which allows users to choose and upload images.
I am already successful in posting images to Firebase Storage but I am wondering if it is possible to have a link/url in Firebase Database from which I can click to redirect me to Firebase Storage to see that image.
I want this function so that along with user inputs such as Title, Date, Remarks, the end-user would be able to see the "image" child with the link along with other inputs
I have tried searching StackOverflow and Youtube for answers but most of them are old and seem outdated. There is a command "getDownloadUrl" but i believe it has been deprecated.
This is the code from my class that uploads my image to Firebase Storage
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(getActivity(),"Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getActivity(),"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);
}
ReportFragment
import static android.app.Activity.RESULT_OK;
import static com.firebase.ui.auth.AuthUI.getApplicationContext;
public class ReportFragment extends Fragment implements
AdapterView.OnItemSelectedListener{
private Button btnChoose,btnUpload;
private ImageView imageView;
private Uri filePath;
private final int PICK_IMAGE_REQUEST = 71;
private TextView mDisplayDate;
private DatePickerDialog.OnDateSetListener mDateSetListener;
private EditText reportedBy;
private TextView date; //upstairs declare alr as mDisplayDate
private Spinner spinner; //downstairs declare alr as spinner3
private EditText location;
private Spinner spinner2; //downstairs declare alr as spinner2
private EditText details;
private Spinner spinner3; //downstairs declare alr as spinner1
private EditText remarks;
private EditText title;
private Button submitIncident;
public static TextView resultTextView3;
Button scan_btn3;
private ImageView imageView2;
private TextView imgUrl1;
DatabaseReference databaseIncidents;
FirebaseStorage storage;
StorageReference storageReference;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable
ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_report, container, false);
databaseIncidents =
FirebaseDatabase.getInstance().getReference("Incidents");
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
btnChoose = (Button) v.findViewById(R.id.btnChoose);
btnUpload = (Button) v.findViewById(R.id.btnUpload);
imageView = (ImageView) v.findViewById(R.id.imgView);
reportedBy = (EditText) v.findViewById(R.id.etreportedby);
// Below have already line 151
// date = (TextView) v.findViewById(R.id.tvdate);
location = (EditText) v.findViewById(R.id.etlocation);
details = (EditText) v.findViewById(R.id.etdetails);
remarks = (EditText) v.findViewById(R.id.etremarks);
title = (EditText) v.findViewById(R.id.ettitle);
submitIncident = (Button) v.findViewById(R.id.btnSubmit);
resultTextView3 = (TextView)v.findViewById(R.id.result_text3);
scan_btn3 = (Button)v.findViewById(R.id.btn_scan3);
imageView2 = (ImageView)v.findViewById(R.id.ivimagescardinput);
imgUrl1 = (TextView)v.findViewById(R.id.tvimagescard);
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chooseImage();
}
});
// btnUpload.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// uploadImage();
// }
// });
scan_btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new
Intent(getActivity(),ScanCodeActivity.class));
}
});
submitIncident.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
incidentSubmit();
uploadImage();
Glide.with(getActivity()).load(URL).into(imageView2);
}
});
return`
}
private void incidentSubmit(){
String reportedname = reportedBy.getText().toString().trim();
String location1 = location.getText().toString();
String details1 = details.getText().toString();
String remarks1 = remarks.getText().toString();
String urgency1 = spinner.getSelectedItem().toString();
String type1 = spinner2.getSelectedItem().toString();
String splocation1 = spinner3.getSelectedItem().toString();
String date1 = mDisplayDate.getText().toString();
String title1 = title.getText().toString();
String qrlocation1 = resultTextView3.getText().toString();
String image1 = imgUrl1.getText().toString();
if(!TextUtils.isEmpty(reportedname)) {
String incidentId = databaseIncidents.push().getKey();
Incident incident = new
Incident(reportedname,location1,details1,remarks1,urgency1,type1,splocation1,date1,title1,qrlocation1,image1);
databaseIncidents.child(incidentId).setValue(incident);
Toast.makeText(getActivity(), "Incident Added", Toast.LENGTH_LONG).show();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new IncmanFragment());
fragmentTransaction.commit();
} else {
Toast.makeText(getActivity(), "All fields must be entered",Toast.LENGTH_LONG).show();
}
}
private void uploadImage() {
if (filePath != null) {
final StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
ref.putFile(filePath).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()) {
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String URL = uri.toString();
databaseIncidents.child("imageId").setValue(URL.toString());
}
});
}
}
});
}
}
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);
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
filePath = data.getData();
try{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getApplicationContext().getContentResolver(),filePath);
imageView.setImageBitmap(bitmap);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String text = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
Any help or tutorials is greatly appreciated!
Database Inputs (not including image)
For storing the images to your Firebase Storage, you first set a correct reference and just store the image there, very similar to Firebase Database data storing.
To have a link in the Firebase Database, you can just use downloadUri you can get from storage and have it stored in the database.
The code for this looks something like this, you can take an inspiration from this and come up with a code that suits you more:
private void uploadFile(Bitmap bitmap) {
FirebaseStorage storage = FirebaseStorage.getInstance();
final StorageReference storageRef = storage.getReference();
final StorageReference ImagesRef = storageRef.child("images/"+mAu.getCurrentUser().getUid()+".jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] data = baos.toByteArray();
final UploadTask uploadTask = ImagesRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.i("whatTheFuck:",exception.toString());
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (!task.isSuccessful()) {
Log.i("problem", task.getException().toString());
}
return ImagesRef.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users").child(mAu.getCurrentUser().getUid());
Log.i("seeThisUri", downloadUri.toString());// This is the one you should store
ref.child("imageURL").setValue(downloadUri.toString());
} else {
Log.i("wentWrong","downloadUri failure");
}
}
});
}
});
}
If i understand correctly you can upload images to storage succesfully but you are having trouble when you want to get that image direct url.
Try this code:
StorageReference storageRef=FirebaseStorage.getInstance().getReference().child("images/"+ UUID.randomUUID().toString());
storageRef.putFile(filePath).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String URL = uri.toString();
//This is your image url do whatever you want with it.
}
});
}
}
});

BaseAdapter - how to use notifyItemRemoved

I have a BaseAdapter which is responsible for my SwipeCardView. Now I need to add something like this notifyItemRemoved to remove one specific item and show the new list. I need to remove the item at the bottom of my code at the AlertDialog part. Everything is working, its just I don't know how to remove it. Unfortunately, I can't find the right syntax for it. FYI I removed method like the constructor etc. to keep the post small:
public class FeedAdapter extends BaseCardAdapter {
private List<EventObject> ideen;
private Activity context;
#Override
public void onBindData(final int position, View cardview) {
if (ideen.size() ==0 || ideen == null){
return;
}
ImageView bild = cardview.findViewById(R.id.imageView);
TextView name = cardview.findViewById(R.id.name);
final EventObject eo = ideen.get(position);
name.setText(eo.getName());
TextView adress = cardview.findViewById(R.id.address);
Geocoder geocoder;
List<Address> addresses = null;
geocoder = new Geocoder(context, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(Double.parseDouble(eo.getLat()), Double.parseDouble(eo.getLng()), 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
} catch (IOException e) {
e.printStackTrace();
}
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
String[] separatedadress = address.split(",");
adress.setText(separatedadress[0]+" , "+city);
TextView date = cardview.findViewById(R.id.date);
date.setText(eo.getDate());
Button teilnehmen = cardview.findViewById(R.id.teilnehmen);
teilnehmen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String userid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child(userid).child("acceptedEvents").child(eo.getId());
ref.setValue(true);
getPLZ(eo.getId(), eo, position);
}
});
bild.setImageResource(R.drawable.blau);
}
private void getPLZ(final String id, final EventObject eo, final int position) {
String userid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child(userid).child("plz");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String plz = dataSnapshot.getValue().toString();
setParticipantInEvent(plz, id, eo, position);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void setParticipantInEvent(String plz, String id, EventObject eo, int position){
String userid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Events").child(plz).child(id);
ref.child("participants").child(userid).setValue(true);
askForCalendar(eo, position);
}
private void askForCalendar(final EventObject eventObject, final int position) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Event in deinem Kalender speichern?")
.setCancelable(false)
.setPositiveButton("Ja", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", Long.parseLong(eventObject.getTs()));
intent.putExtra("allDay", true);
intent.putExtra("endTime", Long.parseLong(eventObject.getTs())+60*60*1000);
intent.putExtra("title", eventObject.getName());
context.startActivity(intent);
}
})
.setNegativeButton("Nein", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Here i have to remove one item:
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}

Categories

Resources