Share Image intent File not supported - android

I'm facing issue in image intent when I click share button for share image it says file doesn't support.
Here is my code:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private Context context;
private List<Upload> uploads;
Upload upload;
public MyAdapter(Context context, List<Upload> uploads) {
this.uploads = uploads;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.layout_images, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
upload = uploads.get(position);
holder.textViewName.setText(upload.getName());
Glide.with(context).load(upload.getUrl()).into(holder.imageView);
}
#Override
public int getItemCount() {
return uploads.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView textViewName;
public ImageView imageView,shareImage;
public ViewHolder(View itemView) {
super(itemView);
textViewName = (TextView) itemView.findViewById(R.id.textViewName);
imageView = (ImageView) itemView.findViewById(R.id.imageView);
shareImage=(ImageView)itemView.findViewById(R.id.share);
shareImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(upload.getUrl()));
shareIntent.setType("image/*");
context.startActivity(Intent.createChooser(shareIntent, "Share your memoir via:"));
}
});
}
}
}
Here is my showImageActivity.java
public class ShowImagesActivity extends Activity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private DatabaseReference mDatabase;
private ProgressDialog progressDialog;
//list to hold all the uploaded images
private List<Upload> uploads;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recycler_view);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
progressDialog = new ProgressDialog(this);
final FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
uploads = new ArrayList<>();
//displaying progress dialog while fetching images
progressDialog.setMessage("Loading your memories ...");
progressDialog.show();
mDatabase = FirebaseDatabase.getInstance().getReference(Constants.DATABASE_PATH_UPLOADS);
//adding an event listener to fetch values
mDatabase.child(currentFirebaseUser.getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
//dismissing the progress dialog
progressDialog.dismiss();
//iterating through all the values in database
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Upload upload = postSnapshot.getValue(Upload.class);
uploads.add(upload);
}
//creating adapter
adapter = new MyAdapter(ShowImagesActivity.this, uploads);
//adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
}
}
I'm using firebase. In upload.getUrl image url is saved on firebase Database while image actually saved in firebase Storage.
Here I'm storing images
final FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
TitleName=title.getText().toString();
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
progressDialog.setMessage("Uploading .....");
progressDialog.show();
Uri uri = data.getData();
StorageReference filePath = storageReference.child(Constants.STORAGE_PATH_UPLOADS).child(currentFirebaseUser.getUid()).child(uri.getLastPathSegment());
filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadPath = taskSnapshot.getDownloadUrl();
Glide.with(MainActivity.this).load(downloadPath).fitCenter().into(imageView);
Toast.makeText(getApplicationContext(), "Memory Uploaded", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
//creating the upload object to store uploaded image details
Upload upload = new Upload(taskSnapshot.getDownloadUrl().toString(), TitleName);
//adding an upload to firebase database
String uploadId = mDatabase.push().getKey();
mDatabase.child(currentFirebaseUser.getUid()).child(uploadId).setValue(upload);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}

You need to save your image before sharing it. There's a sample code for saving imageview's drawing cache and sharing it. Hope it helps.
Just edit your code like this:
shareImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
share(imageview);
}
});
public Bitmap capture(View view) {
view.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
return bitmap;
}
public void share(View view) {
Context context = view.getContext();
Bitmap bitmap = capture(view);
try {
File file = new File(context.getExternalCacheDir(), DateUtil.format(new Date(), "yyyyMMdd_HHmm") + ".png");
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("image/png");
Uri uri = Uri.fromFile(file);
i.putExtra(Intent.EXTRA_STREAM, uri);
context.startActivity(Intent.createChooser(i, "Share"));
} catch (IOException e) {
e.printStackTrace();
}
}

Related

Images are not being shown in recyclerview

I'm trying to make an app where users are able to signup for an account and they can upload images. I got the uploading part down pack but I want to retrieve those images to the user on their profile page but I don't know how to. Can someone show me how I can retrieve those images I want to use a recycler view for this. Thanks in advance. Below is my code
// Upload Image class
public class UploadImageActivity extends AppCompatActivity implements View.OnClickListener {
int PICK_IMAGE_REQUEST=234;
private Button upload,button2;
private ImageView imageView;
private Uri filepath;
FirebaseAuth firebaseAuth;
FirebaseUser firebaseUser;
FirebaseDatabase firebaseDatabase;
TextView next;
FirebaseStorage firebaseStorage;
StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_ad);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
firebaseStorage=FirebaseStorage.getInstance();
storageReference=firebaseStorage.getReference();
next=findViewById(R.id.next0);
firebaseUser= firebaseAuth.getInstance().getCurrentUser();
firebaseDatabase.getInstance().getReference();
upload=findViewById(R.id.button_upload);
button2=findViewById(R.id.submit);
imageView=findViewById(R.id.view_image);
upload.setOnClickListener(this);
}
private void showFileChooser(){
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Choose an image"),PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode== PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null
&& data.getData() != null){
next.setTextColor(Color.parseColor("#FF4500"));
next.setEnabled(true);
filepath=data.getData();
try {
// Bitmap bitmap=new Compressor(this).setMaxHeight(200) //Set height and width
// .setMaxWidth(200)
//.setQuality(100) // Set Quality
//.compressToBitmap(file);
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),filepath);
imageView.setImageBitmap(bitmap);
// build alert dialog
} catch (IOException e) {
e.printStackTrace();
}
}
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(filepath != null) {
final ProgressDialog progressDialog=new ProgressDialog(UploadAdActivity.this);
progressDialog.setTitle("Uploading");
progressDialog.show();
int aNumber = (int) (20 * Math.random()) + 1;
//StorageReference riversRef=storageReference.child(firebaseUser.getUid()+"/"+"image.png");
// StorageReference=firebaseStorage.getInstance().getReferenceFromUrl()
StorageReference riversRef = storageReference.child(System.currentTimeMillis()+"."+getExtension(filepath));
//final String url=riversRef.getDownloadUrl().getResult().toString();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference("Users");
final DatabaseReference update = rootRef.child(uid).child("images");
riversRef.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(UploadAdActivity.this,"Uploaded successfully",Toast.LENGTH_LONG).show();
storageReference.getDownloadUrl();
taskSnapshot.getStorage().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String download_url=uri.toString();
update.child("images").setValue(download_url);
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(UploadAdActivity.this,"Failed to upload",Toast.LENGTH_LONG).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+"%"); }
});
}
}
});
}
private String getExtension(Uri filepath) {
ContentResolver contentResolver=getContentResolver();
MimeTypeMap mimeTypeMap=MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(filepath));
};
#Override
public void onClick(View v) {
if(v==upload){
showFileChooser();
//uploadImage();
next.setTextColor(Color.parseColor("#FF4500"));
/*
Intent i = new Intent(UploadAdActivity.this, ActionActivity.class);
//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
*/
}
}
}
//Users profile
public class ProfileActivity extends AppCompatActivity implements View.OnClickListener {
private RecyclerView recyclerView;
private ImageAdapter mAdapter;
private DatabaseReference databaseReference;
private List<Upload> mUploads;
FirebaseAuth firebaseAuth;
FirebaseUser firebaseUser;
int PICK_IMAGE_REQUEST=234;
private Button upload,button2;
private ImageView imageView;
private Uri filepath;
FirebaseDatabase firebaseDatabase;
FirebaseStorage firebaseStorage;
StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
overridePendingTransition(R.anim.slide_right, R.anim.slide_left);
mUploads=new ArrayList<>();
mAdapter=new ImageAdapter(ProfileActivity.this, mUploads);
recyclerView=findViewById(R.id.recyclerView);
//recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(mAdapter);
firebaseStorage=FirebaseStorage.getInstance();
storageReference=firebaseStorage.getReference();
firebaseUser= firebaseAuth.getInstance().getCurrentUser();
firebaseDatabase.getInstance().getReference();
upload=findViewById(R.id.button_upload);
button2=findViewById(R.id.submit);
imageView=findViewById(R.id.view_image);
upload.setOnClickListener(this);
String uid=FirebaseAuth.getInstance().getCurrentUser().getUid();
databaseReference=FirebaseDatabase.getInstance().getReference();
//databaseReference.child("images");
databaseReference.orderByChild(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot postsnapshot:dataSnapshot.getChildren()){
Upload upload=postsnapshot.getValue(Upload.class);
mUploads.add(upload);
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ProfileActivity.this,databaseError.getMessage(),Toast.LENGTH_LONG).show();
}
});
recyclerView.setAdapter(mAdapter); //Again set adapter to recyclerview
}
//Adapter class
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder>{
private Context mContext;
private List<Upload> mUploads;
public ImageAdapter(Context context,List<Upload> uploads){
mContext = context;
mUploads = uploads;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View V = LayoutInflater.from(mContext).inflate(R.layout.cardview, parent, false);
return new ImageViewHolder(V);
}
#Override
public void onBindViewHolder(#NonNull ImageViewHolder holder, int position) {
Upload uploadCurrent=mUploads.get(position);
Picasso.get().load(uploadCurrent.getmImageUrl()).fit().centerCrop().into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder{
public ImageView imageView;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
imageView=itemView.findViewById(R.id.imageview);
}
}
}
//Upload class
public class Upload {
private String images;
public Upload(){
//Empty constructor needed
}
public Upload (String imageUrl){
images=imageUrl;
}
public String getmImageUrl() {
return images;
}
public void setmImageUrl(String images) {
this.images = images;
}
}
Put recyclerView.setAdapter(mAdapter);
after
databaseReference.orderByChild(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot postsnapshot:dataSnapshot.getChildren()){
Upload upload=postsnapshot.getValue(Upload.class);
mUploads.add(upload);
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ProfileActivity.this,databaseError.getMessage(),Toast.LENGTH_LONG).show();
}
});
create a refresh function in adaptor
public void refresh(List<Upload> uploads){
this.uploads=uploads;
notifyDataSetChanged();
}
call this where you get the data from server or firebase using adaptor like this
mAdapter.refresh(mUploads);

Android RecyclerView duplicating images from Firebase

I'm writing a small group chat application in Android Studio and using Firebase as the backend. I'm trying to allow the users to post images however everytime I send an image to firebase storage and retrieve it in order to post into a recycler view using Glide, it duplicates in the recycler view. I've confirmed the image in the firebase storage is NOT duplicating, it's just on the recycler view on the app itself. I've been struggling with this issue for days and cannot for the life of me find why it's duplicating.
Here's my code:
Uploads and Retrieves the image URL in Firebase
public void uploadImage(final Uri filePath) {
if (filePath != null) {
final String pathToImage = "chatImages/" + user.getUid()+"/"+ UUID.randomUUID();
StorageReference storeRef = storageReference.child(pathToImage);
UploadTask uploadTask = storeRef.putFile(filePath);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG, "Upload Failed");
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.e(TAG, "Upload Successful");
//now that the image has been uploaded, send to chat
storageReference.child(pathToImage).getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//adds photo, username and message to the arraylists\
imagePath = uri.toString();
Log.e(TAG, "done");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG, "Failed to Retrieve Image Message");
}
});
}
});
}
}
Adds the image and other post info to the recycler view
db.collection("chats").document("0fv4XvLpi8dWivyohQbk").collection("chatMessages")
.orderBy("TimeStamp")
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.e(TAG, "Listen Failed", e);
return;
}
//temporay arraylists
final ArrayList<String> uIdAL = new ArrayList<>();
//gets any updates
for (DocumentChange newdoc : queryDocumentSnapshots.getDocumentChanges()) {
if (newdoc.getType() == DocumentChange.Type.ADDED) {
Log.e(TAG, "new message" + newdoc.getDocument().getData());
//saves userIDs for later use in getting profile pics
uIdAL.add((String) newdoc.getDocument().getData().get("userID"));
//temporary profile picture
if(chatPhotoUrl != null && ((String) newdoc.getDocument().getData().get("userID")).equals(user.getUid()))
{
messageAvatars.add(chatPhotoUrl.toString());
}
else
{
messageAvatars.add("https://pictures.digitalrev.com/image/upload/v1454493563/gzev2fhfpoizg3bpozjr.jpg");
}
//get usernames and messages
userNames.add((String) newdoc.getDocument().getData().get("userName"));
messages.add((String) newdoc.getDocument().getData().get("message"));
imageMessages.add((String) newdoc.getDocument().getData().get("imageMessage"));
//add to recycler view
adapter.notifyItemInserted(userNames.size());
rv.scrollToPosition(userNames.size() - 1);
Log.e(TAG, "here");
}
}
}
});
}
Recycler View Adapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
private static final String TAG = "RecyclerViewAdapter";
private ArrayList<String> messageAvatars = new ArrayList<>();
private ArrayList<String> userNames = new ArrayList<>();
private ArrayList<String> messages = new ArrayList<>();
private ArrayList<String> imageMessages = new ArrayList<>();
private Context context;
public RecyclerViewAdapter(ArrayList<String> messageAvatars, ArrayList<String> userNames, ArrayList<String> messages, ArrayList<String> imageMessages, Context context) {
this.messageAvatars = messageAvatars;
this.userNames = userNames;
this.messages = messages;
this.imageMessages = imageMessages;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerviewitem,parent, false);
ViewHolder viewholder = new ViewHolder(view);
return viewholder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Log.e(TAG, "onBindViewHolder: called");
//sets the fields in the recyclerview item
Glide.with(context).asBitmap().load(messageAvatars.get(position)).into(holder.messageImage);
holder.userName.setText(userNames.get(position));
holder.messageText.setText(messages.get(position));
Glide.with(context).asBitmap().load(imageMessages.get(position)).into(holder.imageMessage);
//triggers if the recyclerview item is clicked
holder.parentLayout.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view)
{
Log.e(TAG, "onClick: clicked");
}
});
}
#Override
public int getItemCount() {
return userNames.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public class ViewHolder extends RecyclerView.ViewHolder{
CircleImageView messageImage;
TextView userName;
TextView messageText;
ImageView imageMessage;
ConstraintLayout parentLayout;
public ViewHolder(View itemView) {
super(itemView);
messageImage = itemView.findViewById(R.id.chatImageView);
userName = itemView.findViewById(R.id.usernametextView);
messageText = itemView.findViewById(R.id.messagetextView);
imageMessage = itemView.findViewById(R.id.imageView);
parentLayout = itemView.findViewById(R.id.parentlayout);
}
}
Any and all help would be appreciated!

How to Update Images and Text in Firebase and Retrieve Them In RecyclerView

I followed a Tutorial and was Successfully able to Load the data in Firebase and also retrieve it back in RecyclerView and also Learned How to Delete data but now I'm Stuck that how to update this data in the Firebase and show it in RecyclerView.I have used Picasso for the Images.
This is my Gallery.java file
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);
}
}
This below one is the ImagesActivity which is for the recyclerview, here the delete operation works, as I mentioned and I have used the AlertDialog to open and update the details I tried to Mimic some things from gallery.java but was not able to figure out how they should be Arranged.
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);
}
}
This below one is for set and get methods named as UploadImage.java
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;
}
}
The following one for the Adapter
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;
}
}
Any Solution for this how can I update it.
There is no update method in firebase storage, So for a workaround:
get the name the file you want to delete
delete the file you want to update
upload the new file
rename file with the previous file name

Getting Photos From Firebase Storage based on UID

I'm facing an issue.
I'm getting photos through UID,
but issue is in firebase database where images are replacing
if I use the push then application didn't get images from firebase
Firebase Database Image
If I remove push from database then images will be show, but as you can see that images will overlap everytime user upload image
Here is my code for onActivityResult
#Override
protected void onActivityResult ( int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
final FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
TitleName=title.getText().toString();
progressDialog.setMessage("Uploading .....");
progressDialog.show();
Uri uri = data.getData();
StorageReference filePath = storageReference.child("Photos").child(currentFirebaseUser.getUid()).child(uri.getLastPathSegment());
filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadPath = taskSnapshot.getDownloadUrl();
Glide.with(MainActivity.this).load(downloadPath).centerCrop().into(imageView);
Toast.makeText(getApplicationContext(), "DONE" + TitleName, Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
//creating the upload object to store uploaded image details
Upload upload = new Upload(taskSnapshot.getDownloadUrl().toString(), TitleName);
//adding an upload to firebase database
// String uploadId = mDatabase.push().getKey();
mDatabase.child(currentFirebaseUser.getUid())***.push().***setValue(upload);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
If i remove push from
mDatabase.child(currentFirebaseUser.getUid())***.push().***setValue(upload);
then images will be show on recyclerView.
Any suggestions?
ShowImagesActivity
public class ShowImagesActivity extends AppCompatActivity {
//recyclerview object
private RecyclerView recyclerView;
//adapter object
private RecyclerView.Adapter adapter;
//database reference
private DatabaseReference mDatabase;
//progress dialog
private ProgressDialog progressDialog;
//list to hold all the uploaded images
private List<Upload> uploads;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recycler_view);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
progressDialog = new ProgressDialog(this);
uploads = new ArrayList<>();
//displaying progress dialog while fetching images
progressDialog.setMessage("Loading your memories ...");
progressDialog.show();
mDatabase = FirebaseDatabase.getInstance().getReference(Constants.DATABASE_PATH_UPLOADS);
//adding an event listener to fetch values
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
//dismissing the progress dialog
progressDialog.dismiss();
//iterating through all the values in database
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Upload upload = postSnapshot.getValue(Upload.class);
uploads.add(upload);
}
//creating adapter
adapter = new MyAdapter(getApplicationContext(), uploads);
//adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
}
}
Constants.java
public static final String DATABASE_PATH_UPLOADS = "uploads";
public static final String STORAGE_PATH_UPLOADS = "uploads/";
Adapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private Context context;
private List<Upload> uploads;
public MyAdapter(Context context, List<Upload> uploads) {
this.uploads = uploads;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.layout_images, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Upload upload = uploads.get(position);
holder.textViewName.setText(upload.getName());
Glide.with(context).load(upload.getUrl()).into(holder.imageView);
}
#Override
public int getItemCount() {
return uploads.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView textViewName;
public ImageView imageView;
public ViewHolder(View itemView) {
super(itemView);
textViewName = (TextView) itemView.findViewById(R.id.textViewName);
imageView = (ImageView) itemView.findViewById(R.id.imageView);
}
}
}
upload.java
public class Upload{
public String name;
public String url;
// Default constructor required for calls to
// DataSnapshot.getValue(User.class)
public Upload() {
}
public Upload( String url, String name) {
this.name = name;
this.url= url;
}
public String getName() {
return name;
}
public String getUrl() {
return url;
}

How do I share images from RecyclerView?

My target is to share the image from ImageView inside RecyclerView to the others apps.The image is loaded from Firebase storage using Picasso lib.
I have added a Share button below each item but cant proceed further.
This is my MainActivity.
public class MainActivity extends AppCompatActivity {
private RecyclerView mBlogList;
private DatabaseReference mDatabase;
private LinearLayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
mDatabase.keepSynced(true);
mBlogList = (RecyclerView) findViewById(R.id.blog_List);
mBlogList.setHasFixedSize(true);
mBlogList.setLayoutManager(new LinearLayoutManager(this));
mLayoutManager = new LinearLayoutManager(MainActivity.this);
mLayoutManager.setReverseLayout(true); // THIS ALSO SETS setStackFromBottom to true
mBlogList.setLayoutManager(mLayoutManager);
mLayoutManager.setStackFromEnd(true);
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Blog, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
Blog.class,
R.layout.blog_row,
BlogViewHolder.class,
mDatabase
) {
#Override
protected void populateViewHolder(BlogViewHolder viewHolder, Blog model,int position) {
viewHolder.setTitle(model.getTitle());
viewHolder.setImage(getApplicationContext(), model.getImage());
}
};
mBlogList.setAdapter(firebaseRecyclerAdapter);
}
public static class BlogViewHolder extends RecyclerView.ViewHolder {
View mView;
public BlogViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setTitle(String title) {
TextView post_title = (TextView) mView.findViewById(R.id.post_title);
post_title.setText(title);
}
public void setImage(final Context ctx, final String image) {
final ImageView post_image = (ImageView) mView.findViewById(R.id.post_image);
Picasso.with(ctx).load(image).networkPolicy(NetworkPolicy.OFFLINE).into(post_image, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
//Try again online if cache failed
Picasso.with(ctx)
.load(image)
.error(R.drawable.header)
.into(post_image, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Log.v("Picasso", "Could not fetch image");
}
});
}
});
}
}
You need to convert imageView to Bitmap first then share it.
// Can be triggered by a view event such as a button press
public void onShareItem(View v) {
// Get access to bitmap image from view
ImageView ivImage = (ImageView) findViewById(R.id.post_image);
// Get access to the URI for the bitmap
Uri bmpUri = getLocalBitmapUri(ivImage);
if (bmpUri != null) {
// Construct a ShareIntent with link to image
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/*");
// Launch sharing dialog for image
startActivity(Intent.createChooser(shareIntent, "Share Image"));
} else {
}
}
// Returns the URI path to the Bitmap displayed in specified ImageView
public Uri getLocalBitmapUri(ImageView imageView) {
// Extract Bitmap from ImageView drawable
Drawable drawable = imageView.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable){
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
return null;
}
// Store image to default external storage directory
Uri bmpUri = null;
try {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
How to setup the share button in viewholder.
protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) {
viewHolder.setTitle(model.getTitle());
viewHolder.setImage(getApplicationContext(), model.getImage());
viewHolder.mShareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onShareItem(view);
}
});
}
};
mBlogList.setAdapter(firebaseRecyclerAdapter);
}
public static class BlogViewHolder extends RecyclerView.ViewHolder {
View mView;
Button mShareButton;
public BlogViewHolder(View itemView) {
super(itemView);
mView = itemView;
mShareButton = (Button) mView.findViewById(R.id.btn_share);
}
You can use below code to share with available options (twitter, facebook, gmail, whatsapp, etc...):
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, "image text");
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(filePath));
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share image via:"));
I didnt try it but basically works like this. facebook may not allow sharing from other apps. then u can use facebook sdk (GraphApi)
EDIT
Refer to the official doc
https://developer.android.com/training/sharing/index.html

Categories

Resources