Retrieve images in recyclerview from Firebase Firestore - android

I am trying to retrieve images from Firebase Firestore. I am able to retrieve text in RecyclerView successfully however I'm not sure how to retrieve the images.
I had a look at similar questions unfortunately none helped.
ListActivity :
//initialize firestore
db = FirebaseFirestore.getInstance();
//initialize views
mRecyclerView = findViewById(R.id.resultRecycle);
//set recycler view properties
mRecyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(layoutManager);
//show data in recycler view
showData();
}
private void showData() {
db.collection("Item")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
//called when data is retrieved
//show data
for(DocumentSnapshot doc: task.getResult()){
Model model = new
Model(doc.getString("id"),
doc.getString("Title"),
doc.getString("Location"),
//STUCK HERE
);
modelList.add(model);
}
//adapter
adapter = new CustomAdapter(ListActivity.this, modelList);
//set adapter to recycler view
mRecyclerView.setAdapter(adapter);
}
});
CustomAdapter :
public void onItemClick(View view, int position) {
//this will be called when user clicks an item
//show data on toast when clicking
String title = modelList.get(position).getTitle();
String location = modelList.get(position).getLocation();
String url = modelList.get(position).getUrl();
}
#Override
public void onItemLongClick(View view, int position) {
//this will be called when user clicks long item
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int i) {
//bind views /set data
holder.mTitle.setText(modelList.get(i).getTitle());
holder.mLocation.setText(modelList.get(i).getLocation());
Picasso.get().load(modelList.get(i).getUrl()).into(holder.mUrl);
}
Please see the image below link, thank you

Use fileuploader code to upload the image in Firebase Database.
But make sure you put the Fileuploader run on the click of any button. Or it will throw nullpointer Exception if your edittext are empty.
private void Fileuploader(){
if(imguri != null ) {
StorageReference ref = mStorageRef.child("Item");
Toast.makeText(UploadActivity.this, "Upload in progress", Toast.LENGTH_LONG).show();
ref.putFile(imguri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(UploadActivity.this, "Image uploaded successfully!", Toast.LENGTH_LONG).show();
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
saveData(downloadUrl);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
The function will automatically start when file upload successfully done.
private void saveData(Uri imguri) {
Map<String, String> data = new HashMap<>();
EditText title = findViewById(R.id.etv_1);
EditText shortDesc = findViewById(R.id.etv_2);
TextView location = findViewById(R.id.etv_3);
String eTitle = title.getText().toString();
String eShortDesc = shortDesc.getText().toString();
String eLocation = location.getText().toString();
String eUrl = imguri.toString();
userid = FirebaseAuth.getInstance().getUid();
getCate();
data.put("Img", eUrl);
data.put("Title", eTitle);
data.put("Location", eLocation);
data.put("Short Description", eShortDesc);
data.put("Category", cate );
data.put("id", userid);
db.collection("Item").add(data);
Toast.makeText(this, "Successfully saved your item", Toast.LENGTH_SHORT).show();
Intent i = new Intent(this, Home.class);
startActivity(i);
}

I have an best example of Retrieve images in recyclerview from Firebase Firestore ..link is here ...
https://www.simplifiedcoding.net/firebase-storage-example/
in this website given best hint and tutorial here.. please do follow step by step ...

Hey I think this may hep using Picasso
Picasso.with(context).load(ImageURL).into(imageView);

Related

Recycler updates with duplicate values

I use wipe to delete method to delete a row, When i delete one row from the recycler list view it duplicates the value just below the one I had deleted.
If I delete "Test 3" from the list
it shows a duplicate of "Test 4" in 3rd and 4th position
my whole code used for list creation and deletion, can any one help me with this
public class fragmnetPendingAct extends Fragment {
private SwipeRefreshLayout refreshLayout;
private RecyclerView recyclerView;
ArrayList<String> activitynames;
FirebaseAuth mAuth;
View view;
List<modelclasspendingact> modelclasspendingactList = new ArrayList<>();
public fragmnetPendingAct() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pendingactivity,container,false);
refreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_activitypend);
recyclerView = v.findViewById(R.id.recyclerviewpendingact);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
new ItemTouchHelper(itemtouchHelpercalback).attachToRecyclerView(recyclerView);
//listen to swipe horizontal
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// Get new Instance ID token
FirebaseUser mUser = mAuth.getInstance().getCurrentUser();
mUser.getIdToken(true)
.addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
public void onComplete(#NonNull Task<GetTokenResult> task) {
if (task.isSuccessful()) {
String token = task.getResult().getToken();
// Send token to your backend via HTTPS
getdatafromserver(token);
} else {
// Handle error -> task.getException();
Log.w(TAG, "getInstanceId failed second", task.getException());
}
}
});
refreshitems();
}
});
// Get new Instance ID token
FirebaseUser mUser = mAuth.getInstance().getCurrentUser();
mUser.getIdToken(true)
.addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
public void onComplete(#NonNull Task<GetTokenResult> task) {
if (task.isSuccessful()) {
String token = task.getResult().getToken();
Log.d(TAG, "onComplete lead: "+token);
// Send token to your backend via HTTPS
getdatafromserver(token);
} else {
// Handle error -> task.getException();
Log.w(TAG, "getInstanceId failed second", task.getException());
}
}
});
return v;
}
public void getdatafromserver(String token){
//new code using curl
String serverurl="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, serverurl,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d(TAG, "activity list: "+response);
JSONObject alldata=response.getJSONObject("payload");
JSONArray assetaarray=alldata.getJSONArray("activities");
modelclasspendingactList.removeAll(modelclasspendingactList);
for(int i=0;i<assetaarray.length();i++)
{
JSONObject getactivity=assetaarray.getJSONObject(i);
String activityid = String.valueOf(getactivity.getInt("id"));
String activityname = getactivity.getString("title");
String activitydesc = getactivity.getString("description");
Log.d(TAG, "activity name: "+activityname);
//list crreation
modelclasspendingactList.add(new modelclasspendingact(activityname,activitydesc,activityid));
pendingactAdapter adapter = new pendingactAdapter(modelclasspendingactList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers=new HashMap<String,String>();
headers.put("Accept","*/*");
headers.put("Cache-Control","no-cache");
headers.put("cache-control","no-cache");
headers.put("token",token);
return headers;
}
};
singletonclasshttp.getInstance(getActivity()).addtorequestque(jsonObjectRequest);
}
private void refreshitems()
{
refreshLayout.setRefreshing(false);
}
//swipe function
ItemTouchHelper.SimpleCallback itemtouchHelpercalback = new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder viewHolder1) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int i) {
Log.d(TAG, "onSwiped: "+modelclasspendingactList.get(viewHolder.getAdapterPosition()).getPendid());
Log.d(TAG, "onSwiped: position "+viewHolder.getAdapterPosition());
String activeid = modelclasspendingactList.get(viewHolder.getAdapterPosition()).getPendid();
// Get new Instance ID token
FirebaseUser mUser = mAuth.getInstance().getCurrentUser();
mUser.getIdToken(true)
.addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
public void onComplete(#NonNull Task<GetTokenResult> task) {
if (task.isSuccessful()) {
String token = task.getResult().getToken();
//send token and activity id to update function
markascompleted(activeid,token);
} else {
// Handle error -> task.getException();
Log.w(TAG, "getInstanceId failed second", task.getException());
}
}
});
Log.d(TAG, "onSwiped: position "+viewHolder.getAdapterPosition());
Log.d(TAG, "onSwiped: first list size "+modelclasspendingactList.size());
pendingactAdapter adapter = new pendingactAdapter(modelclasspendingactList);
modelclasspendingactList.remove(viewHolder.getAdapterPosition());
recyclerView.removeViewAt(viewHolder.getAdapterPosition());
adapter.notifyItemRemoved(viewHolder.getAdapterPosition());
// adapter.notifyItemRangeChanged(viewHolder.getAdapterPosition(), modelclasspendingactList.size());
// adapter.notifyDataSetChanged();
Log.d(TAG, "onSwiped: list size "+modelclasspendingactList.size());
// pendingactAdapter adapter = new pendingactAdapter(modelclasspendingactList);
// modelclasspendingactList.remove(viewHolder.getAdapterPosition());
// adapter.notifyItemRemoved(viewHolder.getAdapterPosition());
}
};
private void markascompleted(String activeid,String token)
{
//send data to server
//curl function
String serverurl="xxxxxxxxxxxxxxxxxxxxxxx";
Map<String, Object> jsonParams = new ArrayMap<>();
jsonParams.put("id", activeid);
jsonParams.put("activityStatus", "COMPLETED");
jsonParams.put("targetEmployeeId", "1001");
jsonParams.put("score", "1");
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.PUT, serverurl,new JSONObject(jsonParams),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "response: "+response);
try {
if (response.optBoolean("success")==true)
{
Toast.makeText(getActivity(), response.getString("message"),Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getActivity(),"Data Not Updated",Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getActivity(),"Data Not Updated",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),"Data Not Saved",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
}
){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers=new HashMap<String,String>();
headers.put("Accept","*/*");
headers.put("Cache-Control","no-cache");
headers.put("Connection","keep-alive");
headers.put("Content-Type","application/json");
headers.put("cache-control","no-cache");
headers.put("token",token);
return headers;
}
};
singletonclasshttp.getInstance(getActivity()).addtorequestque(jsonObjectRequest);
}
}
First I'll explain why you get this behavior, then we'll get to solution.
In this code:
Problem #1:
pendingactAdapter adapter = new pendingactAdapter(modelclasspendingactList);
You are creating an adapter and pass it your current data. Note that the adapter will have its own copy of the list you passed in constructor.
modelclasspendingactList.remove(viewHolder.getAdapterPosition());
This list that you are removing Item from is different from the one you just sent in Adapter, so the Adapter still has old list.
Then you call removed and adapter tries to update values but your removed item is still in the list that adapter has.
Solution:
Create A Function/Method in Adapter that removes the item from the list in adapter.
Problem #2 with Solution:
You are creating a new Adapter instance/object every time a view is swiped, it is unnecessary. Create the Adapter in class instead of function and instantiate it in onCreateView().
A couple things.
First, the removeViewAt is a function of RecyclerView.LayoutManager. I imagine you meant to say recyclerView.LayoutManager.removeViewAt.
Second, the call to removeViewAt should not be necessary as RecyclerView does this automatically when notifyItemRemoved is called correctly.
Third, you do not need to re-bind the entire list when removing an item. You can remove the notifyItemRangeChanged.
Fourth, you do not need to invalidate the entire adapter when removing an item either. You can remove notifyDataSetChanged. In fact, this function should only be used as a last resort.
Initializing your RecyclerView:
pendingactAdapter adapter = new pendingactAdapter(modelclasspendingactList);
RecyclerView recyclerView = view.findViewById(R.id.my_recycler_view);
recyclerView.adapter = adapter;
recyclerView.layoutManager = LinearLayoutManager(getActivity());
So your removal sequence should be
modelclasspendingactList.remove(viewHolder.getAdapterPosition());
adapter.notifyItemRemoved(viewHolder.getAdapterPosition());

how to show all image urls along with username, title, uid,timestamp in adapter class

I'm trying to show all image URLs along with username, timestamp, and title but only one image is showing. I'm using recyclerview adapter. I want to show all image URLs with a long title, timestamp, and username in adapter like one post
This is how I'm storing in firebase database using blog class
ArrayList<Uri> arrayListImageDownloadUri = new ArrayList<>();
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 DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("posts/");
final String newPostKey = ref.push().getKey();
final String posttitle = desc.getText().toString();
final String CurrentUser = firebaseAuth.getCurrentUser().getUid();
userid = FirebaseDatabase.getInstance().getReference().child("Blog").child(CurrentUser).push();
ArrayList<String> arrayList = new ArrayList<>();
for(int i=0; i<blogimages.size();i++) {
arrayList.add( blogimages.get(i).toString());
Log.v("IMAGESADDING PHSE3", String.valueOf(arrayList));
}
Log.v("COCOCOCOCO", String.valueOf(arrayList));
n.put(String.valueOf("img"), blogimages.get(i).toString());*/
Blog blog = new Blog();
long millis = System.currentTimeMillis();
int timestamp = ((int) (millis/1000))* -1;
blog.setTitle(posttitle);
blog.setUrl(arrayList);
blog.setUid(firebaseAuth.getCurrentUser().getUid());
mdatabaseReference.child(CurrentUser).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();
}
});
you can use this in on success listener when you get blog data:
rootRef.child("Blog").child("blogId").child(url).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
urlList.add(dataSnapshot.getValue()); //you will receive single element
//every time in this listener you can store it in list then you can give it to your adapter out side this listener
}
...
NOTE: you must implement method on Child Changed,Removed...

One one image uploading with different postkeys but i want to store all images under one postkey in Firebase Database

One one image uploading with different postkeys but i want to store all images under one postkey
This is the code where im uploading all the images to firebase storage and databse with post key but one one images are storing with different post key and i want to store all the uploaded images into one post key under blog in firebase databse. Please help me _This is th issue im facing from past few days and i want to retrieve all the uploaded images under one postkey
upload.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
UploadTask uploadTask;
if( selectedImageGridView.getChildCount()!= 0)
{
for ( int i = 0; i < selectedImages.size(); i++) {
blogimages = new ArrayList<>();
Uri uri = Uri.parse("file://"+selectedImages.get(i));
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) {
}
}).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 key = mdatabaseReference.push().getKey();
final String posttitle = desc.getText().toString();
final String CurrentUser = firebaseAuth.getCurrentUser().getUid();
int l = 0;
while (l < blogimages.size()){
Log.v("BLOGIMAGESSIZE", String.valueOf(blogimages.size()));
Map n = new HashMap();
int countingImage = 0;
n.put(String.valueOf("img" + countingImage), blogimages.get(l).toString());
Log.v("MapCount", String.valueOf(n));
mdatabaseReference.child(key).child("images").updateChildren(n).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
Toast.makeText(PhotoUploadActivity.this, "got download url", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(PhotoUploadActivity.this, "Failed to put in db", Toast.LENGTH_SHORT).show();
}
}
});
l++;
countingImage++;
}
}
}) .addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
}
}
}
});
you have to change this line
StorageReference reference = mstorageReference.child("Blog_pics/users").child(uri.getLastPathSegment());
to this lines: you have to put those lines befor the for loop
String userId = firebaseAuth.getCurrentUser().getUid();
StorageReference reference = mstorageReference.child("Blog_pics/users").child(userId);
then inside the loop
refrence.child(uri.getLastPathSegment());
uploadTask = reference.putFile(uri);
...

get data from Arraylist with index 0

I would like to get first data inside Arraylist but my code getting issue that String img contain null data. here is my code :
private List<String> imagedUploaded = new ArrayList<>();
....
private void uploadImageFile(List<Uri> imgUrl) {
for (Uri uri : imgUrl) {
StorageReference fileToUpload = storageRef.child(productID).child(getFileName(uri));
fileToUpload.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
listImageSelectedAdapter.notifyDataSetChanged();
imagedUploaded.add(taskSnapshot.getDownloadUrl().toString()); // get image downloadurl
**defImg = imagedUploaded.get(0);**
productImage = product_Ref.child("product_image").child(productID);
productImage.setValue(imagedUploaded);
selectedImages.clear();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(), "Upload Image Failed", Toast.LENGTH_SHORT).show();
}
});
}
}
here when i want to call index result
uploadProduct() {
product = product_Ref.child(path1).child(path2).child(path3).child(productID);
DataUploadProduct data = new DataUploadProduct();
data.setName(etProductName.getText().toString());
data.setPrice(etPrice.getText().toString());
**data.setDef_image(defImg);**
data.setWeight(etWeight.getText().toString());
data.setDescription(etDescription.getText().toString());
product.setValue(data);
}
in this case imagedUploaded contain :
0 = http://www.url.com1
1 = http://www.url.com2
2 = http://www.url.com3
3 = http://www.url.com4
i want to get data only index 0, how i can do that?

How to retrieve image from firebase based on click

I am using Firebase for my android app. I have uploaded few images in Storage section of firebase and displayed in listview. Now when I click on particular image of recyclerview, I want to move to next activity and show the image which I clicked on in imageview of next activity. How to retrieve that particular image? Please help.
I have created a photos folder in storage of my firebase and all images are stored in that folder.
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
public static final String ANONYMOUS = "anonymous";
public static final int DEFAULT_MSG_LENGTH_LIMIT = 1000;
public static final String FRIENDLY_MSG_LENGTH_KEY = "friendly_msg_length";
public static final int RC_SIGN_IN = 1;
private static final int RC_PHOTO_PICKER = 2;
private ListView mMessageListView;
private MessageAdapter mMessageAdapter;
private ProgressBar mProgressBar;
private ImageButton mPhotoPickerButton;
private EditText mMessageEditText;
private Button mSendButton;
private String mUsername;
// Firebase instance variables
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mMessagesDatabaseReference;
private ChildEventListener mChildEventListener;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private FirebaseStorage mFirebaseStorage;
private StorageReference mChatPhotosStorageReference;
private FirebaseRemoteConfig mFirebaseRemoteConfig;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUsername = ANONYMOUS;
// Initialize Firebase components
mFirebaseDatabase = FirebaseDatabase.getInstance();
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseStorage = FirebaseStorage.getInstance();
mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
mMessagesDatabaseReference = mFirebaseDatabase.getReference().child("messages");
mChatPhotosStorageReference = mFirebaseStorage.getReference().child("photos");
// Initialize references to views
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mMessageListView = (ListView) findViewById(R.id.messageListView);
mPhotoPickerButton = (ImageButton) findViewById(R.id.photoPickerButton);
mMessageEditText = (EditText) findViewById(R.id.messageEditText);
mSendButton = (Button) findViewById(R.id.sendButton);
// Initialize message ListView and its adapter
List<FriendlyMessage> friendlyMessages = new ArrayList<>();
mMessageAdapter = new MessageAdapter(this, R.layout.item_message, friendlyMessages);
mMessageListView.setAdapter(mMessageAdapter);
// Initialize progress bar
mProgressBar.setVisibility(ProgressBar.INVISIBLE);
// ImagePickerButton shows an image picker to upload a image for a message
mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
}
});
// Enable Send button when there's text to send
mMessageEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().trim().length() > 0) {
mSendButton.setEnabled(true);
} else {
mSendButton.setEnabled(false);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
mMessageEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(DEFAULT_MSG_LENGTH_LIMIT)});
// Send button sends a message and clears the EditText
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FriendlyMessage friendlyMessage = new FriendlyMessage(mMessageEditText.getText().toString(), mUsername, null);
mMessagesDatabaseReference.push().setValue(friendlyMessage);
// Clear input box
mMessageEditText.setText("");
}
});
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
onSignedInInitialize(user.getDisplayName());
} else {
// User is signed out
onSignedOutCleanup();
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setProviders(
AuthUI.EMAIL_PROVIDER,
AuthUI.GOOGLE_PROVIDER)
.build(),
RC_SIGN_IN);
}
}
};
// Create Remote Config Setting to enable developer mode.
// Fetching configs from the server is normally limited to 5 requests per hour.
// Enabling developer mode allows many more requests to be made per hour, so developers
// can test different config values during development.
FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
.setDeveloperModeEnabled(BuildConfig.DEBUG)
.build();
mFirebaseRemoteConfig.setConfigSettings(configSettings);
// Define default config values. Defaults are used when fetched config values are not
// available. Eg: if an error occurred fetching values from the server.
Map<String, Object> defaultConfigMap = new HashMap<>();
defaultConfigMap.put(FRIENDLY_MSG_LENGTH_KEY, DEFAULT_MSG_LENGTH_LIMIT);
mFirebaseRemoteConfig.setDefaults(defaultConfigMap);
fetchConfig();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
// Sign-in succeeded, set up the UI
Toast.makeText(this, "Signed in!", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
// Sign in was canceled by the user, finish the activity
Toast.makeText(this, "Sign in canceled", Toast.LENGTH_SHORT).show();
finish();
}
} else if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
// Get a reference to store file at chat_photos/<FILENAME>
StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());
// Upload file to Firebase Storage
photoRef.putFile(selectedImageUri)
.addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// When the image has successfully uploaded, we get its download URL
Uri downloadUrl = taskSnapshot.getDownloadUrl();
// Set the download URL to the message box, so that the user can send it to the database
FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUrl.toString());
mMessagesDatabaseReference.push().setValue(friendlyMessage);
}
});
}
}
#Override
protected void onResume() {
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
#Override
protected void onPause() {
super.onPause();
if (mAuthStateListener != null) {
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
}
mMessageAdapter.clear();
detachDatabaseReadListener();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.sign_out_menu:
AuthUI.getInstance().signOut(this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void onSignedInInitialize(String username) {
mUsername = username;
attachDatabaseReadListener();
}
private void onSignedOutCleanup() {
mUsername = ANONYMOUS;
mMessageAdapter.clear();
detachDatabaseReadListener();
}
private void attachDatabaseReadListener() {
if (mChildEventListener == null) {
mChildEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
FriendlyMessage friendlyMessage = dataSnapshot.getValue(FriendlyMessage.class);
mMessageAdapter.add(friendlyMessage);
}
public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
public void onChildRemoved(DataSnapshot dataSnapshot) {}
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
public void onCancelled(DatabaseError databaseError) {}
};
mMessagesDatabaseReference.addChildEventListener(mChildEventListener);
}
}
private void detachDatabaseReadListener() {
if (mChildEventListener != null) {
mMessagesDatabaseReference.removeEventListener(mChildEventListener);
mChildEventListener = null;
}
}
// Fetch the config to determine the allowed length of messages.
public void fetchConfig() {
long cacheExpiration = 3600; // 1 hour in seconds
// If developer mode is enabled reduce cacheExpiration to 0 so that each fetch goes to the
// server. This should not be used in release builds.
if (mFirebaseRemoteConfig.getInfo().getConfigSettings().isDeveloperModeEnabled()) {
cacheExpiration = 0;
}
mFirebaseRemoteConfig.fetch(cacheExpiration)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// Make the fetched config available
// via FirebaseRemoteConfig get<type> calls, e.g., getLong, getString.
mFirebaseRemoteConfig.activateFetched();
// Update the EditText length limit with
// the newly retrieved values from Remote Config.
applyRetrievedLengthLimit();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// An error occurred when fetching the config.
Log.w(TAG, "Error fetching config", e);
// Update the EditText length limit with
// the newly retrieved values from Remote Config.
applyRetrievedLengthLimit();
}
});
}
/**
* Apply retrieved length limit to edit text field. This result may be fresh from the server or it may be from
* cached values.
*/
private void applyRetrievedLengthLimit() {
Long friendly_msg_length = mFirebaseRemoteConfig.getLong(FRIENDLY_MSG_LENGTH_KEY);
mMessageEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(friendly_msg_length.intValue())});
Log.d(TAG, FRIENDLY_MSG_LENGTH_KEY + " = " + friendly_msg_length);
}
}
When you upload the image a download URL is created by Firebase.
From your code, it's clear that you have the image download URL as created by Firebase.
Even if you dont have the Download URL you can get it using the
storageReferenceObj.getDownloadUrl();
In order to load that image in an ImageView you can use the Picasso library.
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
replace the URL with your download URL and specify your image view. But First add this line to your Gradle file in order to include Picasso library.
compile 'com.squareup.picasso:picasso:2.5.2'
More info: http://square.github.io/picasso/
Implement an onclick listener for the recycleview and pass the image URL in intent on the new activity as follows
intent.putExtra("IMAGE_URL", "url of the image");
startActivity(intent);
Use the following code to get the URL on the second activity
String url = getIntent().getStringExtra("IMAGE_URL");

Categories

Resources