我遵循了教程,并成功地将数据加载到Firebase中,并在RecyclerView中检索回来,还学会了如何删除数据,但现在我不知道如何在Firebase中更新此数据并显示它在RecyclerView.I中使用Picasso作为图像。
这是我的Gallery.java文件
public class Gallery extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST= 1;
private Button mButtonChooseImage;
private Button mButtonUpload;
private TextView mTextViewShowGallery;
private EditText mEditTextFileName,mEditTextDesc;
private ImageView mImageView;
private ProgressBar mProgressBar;
private Uri mImageUri;
private StorageReference mStorageRef;
private DatabaseReference mDatabaseRef;
private StorageTask mUploadTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
mButtonChooseImage = (Button)findViewById(R.id.btnChoose);
mButtonUpload = (Button)findViewById(R.id.btnUpload);
mTextViewShowGallery = (TextView)findViewById(R.id.tvShow);
mImageView = (ImageView)findViewById(R.id.imgView);
mProgressBar = (ProgressBar)findViewById(R.id.progress_bar);
mEditTextFileName = (EditText)findViewById(R.id.txtName);
mEditTextDesc = (EditText)findViewById(R.id.txtDesc);
mStorageRef = FirebaseStorage.getInstance().getReference("uploads");
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();
}
}
});
mTextViewShowGallery.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();
UploadImage uploadImage = new UploadImage(mEditTextFileName.getText().toString().trim(),
mEditTextDesc.getText().toString().trim(),taskSnapshot.getDownloadUrl().toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(uploadImage);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(Gallery.this,e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnPausedListener(new OnPausedListener<UploadTask.TaskSnapshot>() {
@Override
public void onPaused(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(Gallery.this,ImagesActivity.class);
startActivity(intent);
}
}
下面的一个是针对recyclerview的ImagesActivity,这里的删除操作正常工作,正如我所提到的,我已经使用AlertDialog打开并更新我试图模仿gallery.java中的一些东西的细节但是不能弄清楚他们应该如何安排。
public class ImagesActivity extends AppCompatActivity implements ImageAdapter.OnItemClickListener {
private RecyclerView mRecyclerView;
private ImageAdapter mAdapter;
private ProgressBar mProgressCircle;
private static final int PICK_IMAGE_REQUEST= 1;
private StorageTask mUploadTask;
private Uri mImageUri;
private StorageReference mStorageRef;
private FirebaseStorage mStorage;
private DatabaseReference mDatabaseRef;
private ValueEventListener mDBListener;
private List<UploadImage> mUploads;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_images);
mRecyclerView = findViewById(R.id.recycler_view);
mProgressCircle= findViewById(R.id.progress_circle);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mUploads = new ArrayList<>();
mAdapter = new ImageAdapter(ImagesActivity.this,mUploads);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(ImagesActivity.this);
mStorage = FirebaseStorage.getInstance();
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
mDBListener = mDatabaseRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUploads.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
UploadImage uploadImage = postSnapshot.getValue(UploadImage.class);
uploadImage.setKey(postSnapshot.getKey());
mUploads.add(uploadImage);
}
mAdapter.notifyDataSetChanged();
mProgressCircle.setVisibility(View.INVISIBLE);
}
@Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ImagesActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
mProgressCircle.setVisibility(View.INVISIBLE);
}
});
}
private String getFileExtension(Uri uri)
{
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
@Override
public void onItemClick(int position) {
Toast.makeText(this, "Normal Click", Toast.LENGTH_SHORT).show();
}
@Override
public void onUpdateClick(int position) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.update_dialog, null);
dialogBuilder.setView(dialogView);
final EditText TextName = (EditText) dialogView.findViewById(R.id.txtName);
final EditText TextDesc = (EditText) dialogView.findViewById(R.id.txtDesc);
final ImageView ImageView = (ImageView) dialogView.findViewById(R.id.imgView);
final Button chooseFile = (Button) dialogView.findViewById(R.id.btnChoose);
final Button UpdateDetails = (Button) dialogView.findViewById(R.id.btnUpdate);
dialogBuilder.setTitle("Update Details");
final AlertDialog b = dialogBuilder.create();
b.show();
chooseFile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openFileChooser();
}
});
UpdateDetails.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mUploadTask != null && mUploadTask.isInProgress())
{
Toast.makeText(ImagesActivity.this, "Upload In Progress", Toast.LENGTH_SHORT).show();
}
else
{
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) {
Toast.makeText(ImagesActivity.this, "Update Successful", Toast.LENGTH_LONG).show();
UploadImage uploadImage = new UploadImage(TextName.getText().toString().trim(),
TextDesc.getText().toString().trim(),taskSnapshot.getDownloadUrl().toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.setValue(uploadImage);
mDatabaseRef.child(uploadId).setValue(uploadImage);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(ImagesActivity.this,e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(ImagesActivity.this, "No File Selected", Toast.LENGTH_SHORT).show();
}
}
b.dismiss();
}
});
UploadImage selectedItem = mUploads.get(position);
final String selectedKey = selectedItem.getKey();
// Toast.makeText(this, "Update Clicked", Toast.LENGTH_SHORT).show();
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,PICK_IMAGE_REQUEST);
}
@Override
public void onDeleteClick(int position) {
UploadImage 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);
}
}
下面是一个名为UploadImage.java的set和get方法
public class UploadImage {
private String mName;
private String mDesc;
private String mImageUrl;
private String mKey;
public UploadImage()
{
//Empty Constructor Needed
}
public UploadImage(String name, String desc, String imageUrl)
{
if (name.trim().equals(""))
{
name = "No Name";
desc = "No Description";
}
mName = name;
mDesc = desc;
mImageUrl = imageUrl;
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public String getDesc() {
return mDesc;
}
public void setDesc(String desc) {
mDesc=desc;
}
public String getImageUrl() {
return mImageUrl;
}
public void setImageUrl(String imageUrl) {
mImageUrl=imageUrl;
}
@Exclude
public String getKey(){
return mKey;
}
@Exclude
public void setKey(String key){
mKey = key;
}
}
以下适配器
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private Context mContext;
private List<UploadImage> mUploads;
private OnItemClickListener mListener;
public ImageAdapter(Context context, List<UploadImage> 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) {
UploadImage uploadImageCurrent = mUploads.get(position);
holder.textViewName.setText(uploadImageCurrent.getName());
Picasso.with(mContext)
.load(uploadImageCurrent.getImageUrl())
.placeholder(R.drawable.ic_image_black_24dp)
.fit()
.centerCrop()
.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 ImageView imageView;
public ImageViewHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.text_view_name);
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){
//To Handle Normal Item Clicks
mListener.onItemClick(position);
}
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select Action");
MenuItem Update = menu.add(Menu.NONE, 1, 1, "Update");
MenuItem Delete = menu.add(Menu.NONE, 2, 2, "Delete");
Update.setOnMenuItemClickListener(this);
Delete.setOnMenuItemClickListener(this);
}
@Override
public boolean onMenuItemClick(MenuItem item) {
if (mListener != null)
{
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
//To Check Which Menu Item Was Clicked
switch (item.getItemId())
{
case 1:
mListener.onUpdateClick(position);
return true;
case 2:
mListener.onDeleteClick(position);
return true;
}
}
}
return false;
}
}
public interface OnItemClickListener{
void onItemClick(int position);
void onUpdateClick(int position);
void onDeleteClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
}
此解决方案如何更新。
答案 0 :(得分:0)
firebase存储中没有更新方法,因此需要解决方法: