Я пытаюсь получить изображения и текст, сохраненные в Firebase под текущим идентификатором пользователя. Прежде чем сохранять их под идентификатором пользователя, я мог получить изображения в программе просмотра, но все могли видеть изображения. Поскольку я реализовал идентификатор аутентификации, при попытке извлечь изображения ничего не отображается.
В галерее я выбираю изображение и добавляю два редактируемых текста, которые будут сохранены вместе с ним.
public class Gallery extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST = 1;
private Button mButtonChooseImage;
private Button mButtonUpload;
private TextView mTextViewShowUploads;
private EditText mEditTextFileName;
private EditText mEditTextDescription;
private ImageView mImageView;
private ProgressBar mProgressBar;
private Uri mImageUri;
private StorageReference mStorageRef;
private DatabaseReference mDatabaseRef;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private StorageTask mUploadTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
mButtonChooseImage = findViewById(R.id.button_image2);
mButtonUpload = findViewById(R.id.button_upload2);
mTextViewShowUploads = findViewById(R.id.text_view_show_uploads);
mEditTextFileName = findViewById(R.id.edit_text_file_name);
mEditTextDescription=findViewById(R.id.edit_text_description);
mImageView = findViewById(R.id.image_view);
mProgressBar = findViewById(R.id.progress_bar);
// mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String userID = user.getUid();
mStorageRef = FirebaseStorage.getInstance().getReference("uploads").child(userID);
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
mButtonChooseImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openFileChooser();
}
});
mButtonUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mUploadTask != null && mUploadTask.isInProgress()) {
Toast.makeText(Gallery.this, "Upload in progress", Toast.LENGTH_SHORT).show();
} else {
uploadFile();
}
}
});
mTextViewShowUploads.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openImagesActivity();
}
});
}
private void openFileChooser() {
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) {
mImageUri = data.getData();
Picasso.with(this).
load(mImageUri).
into(mImageView);
}
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void uploadFile() {
if (mImageUri != null) {
StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
mUploadTask = fileReference.putFile(mImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
mProgressBar.setProgress(0);
}
}, 500);
Toast.makeText(Gallery.this, "Upload successful", Toast.LENGTH_LONG).show();
/* Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(upload);*/
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
String user_id = mAuth.getCurrentUser().getUid();
DatabaseReference current_db = FirebaseDatabase.getInstance().getReference("uploads").child(user_id);
Uri downloadUrl = urlTask.getResult();
Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),downloadUrl.toString());
upload.setDescription(mEditTextDescription.getText().toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(upload);
current_db.setValue(uploadId);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(Gallery.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());
mProgressBar.setProgress((int) progress);
}
});
} else {
Toast.makeText(this, "No file selected", Toast.LENGTH_SHORT).show();
}
}
private void openImagesActivity() {
Intent intent = new Intent(this, ImagesActivity.class);
startActivity(intent);
}
}
Вот мой класс ImageAdapter:
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder>{
private Context mContext;
private List<Upload> mUploads;
private OnItemClickListener mListener;
public ImageAdapter(Context context, List<Upload> uploads){
mContext = context;
mUploads = uploads;
}
@Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, parent, false);
return new ImageViewHolder(v);
}
@Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
holder.textViewDescription.setText(uploadCurrent.getDescription());
Picasso.with(mContext)
.load(uploadCurrent.getImageUrl())
.fit()
.centerInside()
.into(holder.imageView);
}
@Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
public TextView textViewName;
public TextView textViewDescription;
public ImageView imageView;
public ImageViewHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.text_view_name);
textViewDescription = itemView.findViewById(R.id.text_view_description);
imageView = itemView.findViewById(R.id.image_view_upload);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
@Override
public void onClick(View v) {
if (mListener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
mListener.onItemClick(position);
}
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select Action");
MenuItem doWhatever = menu.add(Menu.NONE, 1, 1, "Do Whatever");
MenuItem delete = menu.add(Menu.NONE, 2, 2, "Delete");
doWhatever.setOnMenuItemClickListener(this);
delete.setOnMenuItemClickListener(this);
}
@Override
public boolean onMenuItemClick(MenuItem item) {
if(mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
switch (item.getItemId()){
case 1:
mListener.onWhatEverClick(position);
return true;
case 2:
mListener.onDeleteClick(position);
return true;
}
}
}
return false;
}
}
public interface OnItemClickListener{
void onItemClick(int position);
void onWhatEverClick(int position);
void onDeleteClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
}
Затем изображения должны быть возвращены в ImagesActivity в представление переработчика, но ничего не отображается. Я не уверен, что я пытаюсь получить их правильно, так как часть userID смутила меня.
public class ImagesActivity extends AppCompatActivity implements ImageAdapter.OnItemClickListener {
private RecyclerView mRecyclerView;
private ImageAdapter mAdapter;
private FirebaseStorage mStorage; //firebase storage variable
private DatabaseReference mDatabaseRef;
private ValueEventListener mDBListener;
private List<Upload> mUploads;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_images);
mRecyclerView = findViewById(R.id.recyler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mUploads = new ArrayList<>();
mAdapter = new ImageAdapter(ImagesActivity.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(ImagesActivity.this);
//https://www.youtube.com/watch?v=n2vcTdUpsLI
mStorage = FirebaseStorage.getInstance();
//end
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String userID = user.getUid();
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads").child(userID);
mDBListener=mDatabaseRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
mUploads.clear();
for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){
Upload upload = postSnapshot.getValue(Upload.class);
//https://www.youtube.com/watch?v=n2vcTdUpsLI
upload.setKey(postSnapshot.getKey());
//end
mUploads.add(upload);
}
mAdapter.notifyDataSetChanged();
/*mAdapter = new ImageAdapter(ImagesActivity.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(ImagesActivity.this); */
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Toast.makeText(ImagesActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onItemClick(int position) {
Toast.makeText(this, "Normal click at position: " + position, Toast.LENGTH_SHORT).show();
}
@Override
public void onWhatEverClick(int position) {
Toast.makeText(this, "Whatever click at position: " + position, Toast.LENGTH_SHORT).show();
}
@Override
public void onDeleteClick(int position) {
Upload selectedItem = mUploads.get(position);
final String selectedKey = selectedItem.getKey();
StorageReference imageRef = mStorage.getReferenceFromUrl(selectedItem.getImageUrl());
imageRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
mDatabaseRef.child(selectedKey).removeValue();
Toast.makeText(ImagesActivity.this, "Item Deleted", Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onDestroy(){
super.onDestroy();
mDatabaseRef.removeEventListener(mDBListener);
}
}