I tried to share the image in the chat app.But was not able to successfully share it.
It's selecting the image from the gallery but not appearing in the chat and not getting saved in the firebase also. Below is my Chat.xml file and UserChat.java file.
I am not able to find the solution for it.
//XML Code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Activity.UserChatActivity">
<LinearLayout
android:id="#+id/dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/profile_image"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_margin="20sp"
android:src="#drawable/user"
app:civ_border_color="#D21CB4F5"
app:civ_border_width="2dp" />
<TextView
android:id="#+id/receivername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:gravity="center"
android:layout_margin="10sp"
android:textColor="#color/black"
android:textSize="20dp"
android:textStyle="bold"
android:fontFamily="sans-serif-medium"/>
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/messageAdapter"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/mesbox"
android:layout_below="#+id/dp" />
<LinearLayout
android:id="#+id/mesbox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:layout_margin="2dp">
<androidx.cardview.widget.CardView
android:id="#+id/attachment"
android:layout_width="35dp"
android:layout_height="35dp"
app:cardCornerRadius="540dp"
android:layout_margin="3dp"
app:cardBackgroundColor="#0381C5">
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_gravity="center"
android:background="#drawable/clip"/>
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="35dp"
app:cardCornerRadius="540dp"
android:layout_margin="3dp"
app:cardBackgroundColor="#431CB4F5">
<EditText
android:id="#+id/editmessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Message"
android:paddingStart="10dp"
android:paddingLeft="10dp"
android:fontFamily="sans-serif-light"
android:background="#null"
android:layout_gravity="center_vertical"/>
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:id="#+id/sendbutton"
android:layout_width="35dp"
android:layout_height="35dp"
app:cardCornerRadius="540dp"
android:layout_margin="3dp"
app:cardBackgroundColor="#0381C5">
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_gravity="center"
android:background="#drawable/send"/>
</androidx.cardview.widget.CardView>
</LinearLayout>
// JAVA code
package com.example.chatapp.Activity;
import de.hdodenhof.circleimageview.CircleImageView;
public class UserChatActivity extends AppCompatActivity {
String ReceiverImage;
String ReceiverUID;
String ReceiverName;
String SenderUID;
String senderRoom;
String receiverRoom;
public static String sImage;
public static String rImage;
CircleImageView profile_image;
TextView receivername;
CardView attachment;
EditText editmessage;
CardView sendbutton;
FirebaseAuth fAuth;
FirebaseDatabase database;
RecyclerView messageAdapter;
ArrayList<Messages> messagesArrayList;
MessagesAdapter adapter;
private String checker = "", myURL = "";
private StorageTask uploadTask;
private Uri fileUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_user_chat);
fAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
ReceiverImage = getIntent().getStringExtra("ReceiverImage");
ReceiverName = getIntent().getStringExtra("name");
ReceiverUID = getIntent().getStringExtra("uid");
messagesArrayList = new ArrayList<>();
profile_image = findViewById(R.id.profile_image);
receivername = findViewById(R.id.receivername);
messageAdapter = findViewById(R.id.messageAdapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setStackFromEnd(true);
messageAdapter.setLayoutManager(linearLayoutManager);
adapter = new MessagesAdapter(UserChatActivity.this, messagesArrayList);
messageAdapter.setAdapter(adapter);
attachment = findViewById(R.id.attachment);
editmessage = findViewById(R.id.editmessage);
sendbutton = findViewById(R.id.sendbutton);
Picasso.get().load(ReceiverImage).into(profile_image);
receivername.setText("" + ReceiverName);
SenderUID = fAuth.getUid();
senderRoom = SenderUID + ReceiverUID;
receiverRoom = ReceiverUID + SenderUID;
DatabaseReference reference = database.getReference().child("user").child(fAuth.getUid());
DatabaseReference chatReference = database.getReference().child("chats").child(senderRoom).child("messages");
chatReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
messagesArrayList.clear();
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
Messages messages = dataSnapshot.getValue(Messages.class);
messagesArrayList.add(messages);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
sImage = snapshot.child("imageUri").getValue().toString();
rImage = ReceiverImage;
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
attachment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CharSequence options[] = new CharSequence[]
{
"Image", "Documents"
};
AlertDialog.Builder builder = new AlertDialog.Builder(UserChatActivity.this);
builder.setTitle("Select File");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0)
{
checker = "image";
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent.createChooser(intent, "Select Image"), 438);
}
if (i == 1)
{
checker = "pdf";
}
}
});
builder.show();
}
});
sendbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = editmessage.getText().toString();
if (message.isEmpty()) {
Toast.makeText(UserChatActivity.this, "Insert Message", Toast.LENGTH_SHORT).show();
return;
}
editmessage.setText("");
Date date = new Date();
Messages messages = new Messages(message, SenderUID, date.getTime());
database.getReference().child("chats")
.child(senderRoom)
.child("messages")
.push()
.setValue(messages).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
database.getReference().child("chats")
.child(receiverRoom)
.child("messages")
.push()
.setValue(messages).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
});
}
});
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 438 && requestCode == RESULT_OK && data != null && data.getData() != null)
{
fileUri = data.getData();
if (!checker.equals("image"))
{
}
else if (checker.equals("image"))
{
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Image Files").child(fAuth.getUid());;
}
else
{
Toast.makeText(this, "Nothing Selected", Toast.LENGTH_SHORT).show();
}
}
}
}
Please someone help me to solve it.
Related
Could you please assist in following issue:
I have incorrect displaying items in my messenger app.
My layout for items:
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="10dp"
android:layout_marginTop="10dp"
app:cardElevation="0dp">
<TextView
android:id="#+id/message_my_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:gravity="end"
android:textColor="#color/black"
android:textSize="14sp"
android:visibility="invisible"
/>
<TextView
android:id="#+id/message_your_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:gravity="start"
android:textColor="#color/black"
android:textSize="14sp"
android:visibility="invisible"
/>
</com.google.android.material.card.MaterialCardView>
My layout for dialog activity:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DialogActivity">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/dialog_appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/Theme.AnonymousAd.AppBarOverlay">
<include
android:id="#+id/dialog_app_bar"
layout="#layout/app_bar_layout"
>
</include>
</com.google.android.material.appbar.AppBarLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/dialog_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:clickable="true"
android:contentDescription="TODO"
android:focusable="true"
android:src="#drawable/ic_send"
android:visibility="invisible"
app:fabSize="mini"
tools:ignore="SpeakableTextPresentCheck" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/dialog_attach"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:clickable="true"
android:contentDescription="TODO"
android:focusable="true"
android:src="#drawable/ic_attach"
app:fabSize="mini"
tools:ignore="SpeakableTextPresentCheck" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/dialog_gift"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:clickable="true"
android:contentDescription="TODO"
android:focusable="true"
android:src="#drawable/ic_gift"
app:fabSize="mini"
tools:ignore="SpeakableTextPresentCheck" />
<EditText
android:id="#+id/dialog_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="#+id/dialog_send"
android:layout_toRightOf="#+id/dialog_gift"
android:autofillHints=""
android:backgroundTint="#color/teal_700"
android:hint="#string/dialog_enter_message"
android:inputType="textCapSentences|textMultiLine"
android:maxHeight="120dp"
android:maxLength="500"
android:minHeight="48dp"
android:textColorHint="#757575"
android:textSize="16sp" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/dialog_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/dialog_message"
android:layout_below="#+id/dialog_appbar"
android:layout_marginBottom="5dp"
android:focusedByDefault="true"
android:scrollbars="vertical" />
Class DialogActivity
public class DialogActivity extends AppCompatActivity {
private RecyclerView dialogRecyclerView;
private LinearLayoutManager layoutManager;
private final List<Message> messageList = new ArrayList<>();
private MessageAdapter messageAdapter;
private String idText;
private String userNameText;
private EditText dialogMessage;
private Toolbar toolbar;
private FloatingActionButton dialogSend;
private FloatingActionButton dialogAttach;
private String downloadedImageUrl;
private StorageTask uploadTask;
private Uri imageUri;
private DatabaseReference dialogsDataBase;
private ProgressDialog loadingBar;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference answersDataBase = db.collection("AnswersDataBase");
private StorageReference imageDataBase;
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
idText = getIntent().getExtras().get("idText").toString();
userNameText = getIntent().getExtras().get("userNameText").toString();
dialogsDataBase = FirebaseDatabase.getInstance().getReference().child("DialogsDataBase").child(idText);
imageDataBase = FirebaseStorage.getInstance().getReference().child("imageDataBase");
toolbar = findViewById(R.id.dialog_app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(userNameText);
messageAdapter = new MessageAdapter(this, messageList);
dialogRecyclerView = findViewById(R.id.dialog_recycler_view);
dialogRecyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
layoutManager.setStackFromEnd(true);
dialogRecyclerView.setLayoutManager(layoutManager);
dialogRecyclerView.setAdapter(messageAdapter);
loadingBar = new ProgressDialog(this);
dialogMessage = findViewById(R.id.dialog_message);
dialogAttach = findViewById(R.id.dialog_attach);
dialogAttach.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
//startActivityForResult(intent, 438);
someActivityResultLauncher.launch(intent);
}
});
dialogMessage.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(dialogMessage.getText().toString().length() > 0){
dialogAttach.setVisibility(View.INVISIBLE);
dialogSend.setVisibility(View.VISIBLE);
}
else {
dialogAttach.setVisibility(View.VISIBLE);
dialogSend.setVisibility(View.INVISIBLE);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
dialogSend = findViewById(R.id.dialog_send);
dialogSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(dialogMessage.getText().toString().length() > 0){
answersDataBase.document(idText).update("answer", dialogMessage.getText().toString());
dialogsDataBase.push().setValue(new Message(Paper.book().read("userName"), dialogMessage.getText().toString(), "text"));
dialogMessage.setText("");
}
}
});
}
#Override
protected void onStart() {
super.onStart();
dialogsDataBase.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
Message message = snapshot.getValue(Message.class);
messageList.add(message);
messageAdapter.notifyDataSetChanged();
dialogRecyclerView.smoothScrollToPosition(dialogRecyclerView.getAdapter().getItemCount());
}
#Override
public void onChildChanged(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot snapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
loadingBar.setTitle("Sending Image");
loadingBar.setMessage("Please wait, we are sending that image");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
// There are no request codes
Intent data = result.getData();
imageUri = data.getData();
StorageReference filePath = imageDataBase.child(System.currentTimeMillis() + ".jpg");
uploadTask = filePath.putFile(imageUri);
uploadTask.continueWithTask(new Continuation() {
#Override
public Object then(#NonNull Task task) throws Exception {
if(!task.isSuccessful()){
throw task.getException();
}
return filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if(task.isSuccessful()){
Uri downloadUrl = task.getResult();
downloadedImageUrl = downloadUrl.toString();
answersDataBase.document(idText).update("answer", "Photo");
dialogsDataBase.push().setValue(new Message(Paper.book().read("userName"), downloadedImageUrl, "image"));
loadingBar.dismiss();
recreate();
}
}
});
}
}
});
#Override
protected void onDestroy() {
super.onDestroy();
messageList.clear();
}
#Override
protected void onPause() {
super.onPause();
messageList.clear();
}
}
Adapter class
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageViewHolderNew> {
private Context context;
private List<Message> messagesList;
private Dialog dialog;
private String userNameString;
public MessageAdapter(Context context, List<Message> messagesList){
this.context = context;
this.messagesList = messagesList;
userNameString = Paper.book().read("userName");
}
public class MessageViewHolderNew extends RecyclerView.ViewHolder{
private TextView messageMyMessage;
private TextView messageYourMessage;
private ImageView messageMyImage;
private ImageView messageYourImage;
public MessageViewHolderNew(#NonNull View itemView) {
super(itemView);
messageMyMessage = (TextView) itemView.findViewById(R.id.message_my_message);
messageYourMessage = (TextView) itemView.findViewById(R.id.message_your_message);
messageMyImage = (ImageView) itemView.findViewById(R.id.message_my_image);
messageYourImage = (ImageView) itemView.findViewById(R.id.message_your_image);
}
}
#NonNull
#Override
public MessageViewHolderNew onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.message_items_layout, parent, false);
return new MessageViewHolderNew(view);
}
#Override
public void onBindViewHolder(#NonNull MessageViewHolderNew holder, int position) {
if(messagesList.get(position).getUserName().equals(userNameString)){
holder.messageMyMessage.setText(messagesList.get(position).getMessage());
holder.messageMyMessage.setVisibility(View.VISIBLE);
}
else{
holder.messageYourMessage.setText(messagesList.get(position).getMessage());
holder.messageYourMessage.setVisibility(View.VISIBLE);
}
}
#Override
public int getItemCount() {
return messagesList.size();
}
}
In this place I check user name.
if(messagesList.get(position).getUserName().equals(userNameString)){
holder.messageMyMessage.setText(messagesList.get(position).getMessage());
holder.messageMyMessage.setVisibility(View.VISIBLE);
}
else{
holder.messageYourMessage.setText(messagesList.get(position).getMessage());
holder.messageYourMessage.setVisibility(View.VISIBLE);
}
If user name is my name then I set message and visible to holder.messageMyMessage.
Else I set message and visible to holder.messageYourMessage.
But sometimes message and visible are set to both messages while scrolling or sent new message. .
See attached screenshot for details
Your problem's here:
if(messagesList.get(position).getUserName().equals(userNameString)){
holder.messageMyMessage.setText(messagesList.get(position).getMessage());
holder.messageMyMessage.setVisibility(View.VISIBLE);
} else {
holder.messageYourMessage.setText(messagesList.get(position).getMessage());
holder.messageYourMessage.setVisibility(View.VISIBLE);
}
You're only making stuff visible, you're never hiding the other thing.
So if a specific ViewHolder is used to display one kind of message, it'll be made visible in onBindViewHolder. The view in that ViewHolder's layout will be set to VISIBLE.
Then, if you scroll down the list and the same ViewHolder is reused to display the other kind of message, the other message view in the layout will be set to VISIBLE. The other message view hasn't changed, it's still in the same state, VISIBLE. So you see them both (depending on how the layout works, one might be covering the other).
When you're using a RecyclerView, because the ViewHolders are reused (recycled) you need to set them up correctly for each item, clearing all the previous state. So in your case, for each message display, you have to either make it visible or hide it. You can't do nothing, because that can leave you with old state from the previous item it was displaying, right?
So you need to do this:
if(messagesList.get(position).getUserName().equals(userNameString)){
holder.messageMyMessage.setText(messagesList.get(position).getMessage());
holder.messageMyMessage.setVisibility(View.VISIBLE);
// now you need to make sure the other is -not- visible!
holder.messageYourMessage.setVisibility(View.GONE);
} else {
holder.messageYourMessage.setText(messagesList.get(position).getMessage());
holder.messageYourMessage.setVisibility(View.VISIBLE);
// same thing - explicitly hide the other one, assume it could be visible
holder.messageMyMessage.setVisibility(View.GONE);
}
This is the number one thing you need to do with a RecyclerView - in onBindViewHolder, always set up everything that can change depending on the item. Assume it has old data or the wrong thing set, and explicitly initialise everything. It's like a whiteboard - when you start using it you need to clean it, because maybe there's some old stuff on there
Here is my recyclerView Adapter which shows a list from the database, View button is for downloading and the delete button deletes the file from device storage, it works perfectly. But how can I set Visibility of the delete button invisible/gone, if the file does not exist in the device storage.
MainActivity mainActivity;
ArrayList<DownModel> downModels;
public MyAdapter(MainActivity mainActivity, ArrayList<DownModel> downModels) {
this.mainActivity =mainActivity;
this.downModels = downModels;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater layoutInflater = LayoutInflater.from(mainActivity.getBaseContext());
View view = layoutInflater.inflate(R.layout.elements, viewGroup, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder myViewHolder, final int i) {
myViewHolder.mName.setText(downModels.get(i).getName());
myViewHolder.mDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(myViewHolder.mDownload.getContext(), PdfView.class);
intent.putExtra("pdf_url", downModels.get(i).getLink());
intent.putExtra("pdf_name",downModels.get(i).getName());
myViewHolder.mDownload.getContext().startActivity(intent);
}
});
myViewHolder.mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = myViewHolder.itemView.getContext();
String pdfName = downModels.get(i).getName()+".pdf";
File file = new File(context.getFilesDir(), pdfName);
try {
if (file.exists())
file.delete();
Log.e("file","file"+file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
public int getItemCount() {
return downModels.size();
}
}
RecyclerView
public class MainActivity extends AppCompatActivity {
FirebaseFirestore db;
RecyclerView mRecyclerView;
ArrayList<DownModel> downModelArrayList = new ArrayList<>();
MyAdapter myAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView= findViewById(R.id.recycle);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
db=FirebaseFirestore.getInstance();
dataFromFirebase();
}
#Override
protected void onResume() {
super.onResume();
myAdapter.notifyDataSetChanged();
}
private void dataFromFirebase() {
if(downModelArrayList.size()>0)
downModelArrayList.clear();
db.collection("chapter1").orderBy("value")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
for(DocumentSnapshot documentSnapshot: Objects.requireNonNull(task.getResult())) {
DownModel downModel= new DownModel(documentSnapshot.getString("name"),
documentSnapshot.getString("link"));
downModelArrayList.add(downModel);
}
myAdapter= new MyAdapter(MainActivity.this,downModelArrayList);
mRecyclerView.setAdapter(myAdapter);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Error ;-.-;", Toast.LENGTH_SHORT).show();
}
})
;
}
}
Layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp">
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:text="Name"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:orientation="horizontal"
android:weightSum="2"
>
<Button
android:id="#+id/down"
android:layout_width="0dp"
android:layout_height="30dp"
android:layout_marginEnd="10dp"
android:layout_weight="1"
android:background="#A00303"
android:elevation="7dp"
android:text="View"
android:textColor="#FFFFFF"
tools:visibility="visible" />
<Button
android:id="#+id/delete"
android:layout_width="0dp"
android:layout_height="30dp"
android:layout_marginStart="10dp"
android:layout_weight="1"
android:background="#A00303"
android:elevation="7dp"
android:text="Delete"
android:textColor="#FFFFFF"
tools:visibility="gone" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
Check if file exists in onBindViewHolder():
#Override
public void onBindViewHolder(#NonNull final MyViewHolder myViewHolder, final int i) {
//check if file exists
Context context = myViewHolder.itemView.getContext();
String pdfName = downModels.get(i).getName()+".pdf";
File file = new File(context.getFilesDir(), pdfName);
if(file.exits()){
//file exists, show delete button
myViewHolder.mDelete.setVisibility(View.VISIBLE);
}else{
//file doesn't exist, hide delete button
myViewHolder.mDelete.setVisibility(View.GONE);
}
.........
.........
.........
}
UPDATE:
After the download is complete call this method on the adapter:
adapter.notifyDataSetChanged();
UPDATE 2:
#Override
protected void onResume() {
super.onResume();
if(myAdapter != null){
myAdapter.notifyDataSetChanged();
}
}
public class MainActivity extends AppCompatActivity {
MaterialEditText edtNewUser, edtNewPassword, edtNewEmail; //pentru Sign up
MaterialEditText edtUser, edtPassword, edtEmail; //pentru Sign in
Button btnSignUp, btnSignIn;
FirebaseDatabase database;
DatabaseReference users;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Firebase
database = FirebaseDatabase.getInstance();
users = database.getReference("Users");
edtUser = (MaterialEditText)findViewById(R.id.edtUser);
edtPassword = (MaterialEditText)findViewById(R.id.edtPassword);
btnSignIn = (Button)findViewById(R.id.btn_sign_in);
btnSignUp = (Button)findViewById(R.id.btn_sign_up);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showSignUpDialog();
}
});
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn(edtUser.getText().toString(), edtPassword.getText().toString());
}
});
}
private void signIn(final String user, final String pwd) {
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(user).exists()){
if(!user.isEmpty()){
User login = dataSnapshot.child(user).getValue(User.class);
if(login.getPassword().equals(pwd))
Toast.makeText(MainActivity.this, "Login ok!", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "Parola incorecta!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this, "Va rog introduceti username!", Toast.LENGTH_SHORT).show();
}
}
else
Toast.makeText(MainActivity.this, "Username-ul nu exista!", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showSignUpDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle("Sign up");
alertDialog.setMessage("Introduceti informatiile necesare");
LayoutInflater inflater = this.getLayoutInflater();
View sign_up_layout = inflater.inflate(R.layout.sign_up_layout,null);
edtNewUser = (MaterialEditText)sign_up_layout.findViewById(R.id.edtNewUserName);
edtNewEmail = (MaterialEditText)sign_up_layout.findViewById(R.id.edtNewEmail);
edtNewPassword = (MaterialEditText)sign_up_layout.findViewById(R.id.edtNewPassword);
alertDialog.setView(sign_up_layout);
alertDialog.setIcon(R.drawable.ic_account_circle_black_24dp);
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
final User user = new User(edtNewUser.getText().toString(),
edtNewPassword.getText().toString(),
edtNewEmail.getText().toString());
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(user.getUserName()).exists())
Toast.makeText(MainActivity.this, "User-ul exista deja!",Toast.LENGTH_SHORT).show();
else{
users.child(user.getUserName()).setValue(user);
Toast.makeText(MainActivity.this, "Inregistrat cu success!",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
dialogInterface.dismiss();
}
});
alertDialog.show();
}
}
XML file
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" >
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/info_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
app:cardElevation="4dp"
>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/edtNewUserName"
android:hint="Username"
android:textColorHint="#color/colorPrimary"
android:textColor="#color/colorPrimary"
android:textSize="24sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:met_baseColor="#color/colorPrimary"
app:met_floatingLabel="highlight"
app:met_primaryColor="#color/colorPrimary"
app:met_singleLineEllipsis="true"
/>
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/edtNewPassword"
android:hint="Password"
android:textColorHint="#color/colorPrimary"
android:textColor="#color/colorPrimary"
android:textSize="24sp"
android:inputType="textPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:met_baseColor="#color/colorPrimary"
app:met_floatingLabel="highlight"
app:met_primaryColor="#color/colorPrimary"
app:met_singleLineEllipsis="true"
/>
</LinearLayout>
</android.support.v7.widget.CardView>
<LinearLayout
android:layout_below="#id/info_login"
android:orientation="horizontal"
android:weightSum="2"
android:layout_margin="8dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#id/btn_sign_up"
android:text="Sign up"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<Button
android:id="#id/btn_sign_in"
android:text="Sign in"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
Please help me! I've tried anything I knew but nothing works
The program I work in is ANDROID STUDIO. I need to solve this to finish my app.
signIn(edtUser.getText().toString(), edtPassword.getText().toString());
This is the line that gives me ERROR. If I comment this line the app works properly but I need it for the rest of the app.
Your edtUser MaterialEditText and edtPassword are not present in your xml file, you have to change the ids in xml file to match the Activity ids, or remplace
edtUser = (MaterialEditText)findViewById(R.id.edtUser);
edtPassword = (MaterialEditText)findViewById(R.id.edtPassword);
by :
edtUser = (MaterialEditText)findViewById(R.id.edtNewUserName);
edtPassword = (MaterialEditText)findViewById(R.id.edtNewPassword);
I am new in Android Studio.I want to connect layouts.But when I execute the project and select the profile page it does't display in Android Studio .I am not taking any error or warning when I execute the project.
It is the layout that I want to connect
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/linearlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/graylight"
android:orientation="vertical"
tools:context=".Profile">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/gradientbackground"
android:orientation="vertical">
<ImageView
android:id="#+id/profilePhoto"
android:layout_width="200dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal"
android:layout_margin="25dp"
android:contentDescription="#string/todo"
android:onClick="chooseImage"
android:src="#drawable/ic_account_circle_black_24dp"
tools:ignore="OnClick" />
<EditText
android:id="#+id/nameText"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:hint="#string/enter_your_name"
android:textColor="#fff"
android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="45dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="20dp">
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:contentDescription="#string/todo"
android:src="#drawable/email" />
<EditText
android:id="#+id/emailText"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:hint="#string/enter_your_email"
android:inputType="textEmailAddress"
android:paddingStart="20dp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="45dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="20dp">
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:contentDescription="#string/todo"
android:src="#drawable/phone" />
<EditText
android:id="#+id/phoneText"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:hint="#string/enter_your_phone"
android:inputType="phone"
android:paddingStart="20dp" />
</LinearLayout>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:background="#drawable/buttonstyle"
android:onClick="save"
android:text="#string/save"
tools:ignore="OnClick" />
public class profile_info extends ArrayAdapter<String> {
private final ArrayList<String> userName;
private final ArrayList<String> userEmail;
private final ArrayList<String> UserPhone;
private final ArrayList<String> userProfileImage;
private final Activity context;
public profile_info(ArrayList<String> userName, ArrayList<String> userEmail,
ArrayList<String> userPhone, ArrayList<String> userProfileImage, Activity
context) {
super(context,R.layout.custom_profileinfo,userEmail);
this.userName = userName;
this.userEmail = userEmail;
UserPhone = userPhone;
this.userProfileImage = userProfileImage;
this.context = context;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull
ViewGroup parent) {
LayoutInflater layoutInflater =context.getLayoutInflater();
View profileinfo
=layoutInflater.inflate(R.layout.custom_profileinfo,null,true);
EditText userNametext =profileinfo.findViewById(R.id.nameText);
EditText userEmailtext =profileinfo.findViewById(R.id.emailText);
EditText userPhonetext =profileinfo.findViewById(R.id.phoneText);
ImageView userImage = profileinfo.findViewById(R.id.profilePhoto);
userNametext.setText(userName.get(position));
userEmailtext.setText(userEmail.get(position));
userPhonetext.setText(UserPhone.get(position));
Picasso.with(context).load(userProfileImage.get(position)).into(userImage);
return profileinfo;
}
}
I want to connect custom_profileinfo to activity_profile
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.cat.haberuygulamasi.Profile">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
public class Profile extends AppCompatActivity {
ArrayList<String> userEmailFromFB;
ArrayList<String> userImageFromFB;
ArrayList<String> userNameFromFB;
ArrayList<String> userPhoneFromFB;
FirebaseDatabase firebaseDatabase;
DatabaseReference myRef;
private FirebaseAuth mAuth;
private StorageReference mStorageRef;
Uri selected;
profile_info adapter;
ListView listView;
EditText userName;
EditText userEmail;
EditText userPhone;
ImageView userImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
userName = findViewById(R.id.nameText);
userEmail = findViewById(R.id.emailText);
userPhone = findViewById(R.id.phoneText);
userImage = findViewById(R.id.profilePhoto);
firebaseDatabase = FirebaseDatabase.getInstance();
myRef = firebaseDatabase.getReference();
mAuth= FirebaseAuth.getInstance();
mStorageRef = FirebaseStorage.getInstance().getReference();
userEmailFromFB = new ArrayList<>();
userImageFromFB = new ArrayList<>();
userNameFromFB = new ArrayList<>();
userPhoneFromFB = new ArrayList<>();
adapter = new profile_info(userImageFromFB,userNameFromFB,userEmailFromFB,userPhoneFromFB,this);
listView = findViewById(R.id.listView);
listView.setAdapter(adapter);
getDataFromFirebase();
}
public void save (View view){
UUID uuidImage1 = UUID.randomUUID();
String imageName ="profilePhoto/"+uuidImage1+".jpg";
StorageReference storageReference1 = mStorageRef.child(imageName);
storageReference1.putFile(selected).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String downloadURLL = taskSnapshot.getDownloadUrl().toString();
FirebaseUser user = mAuth.getCurrentUser();
String userEmail2 = user.getEmail().toString();
String userName2 = userName.getText().toString();
String userPhone2 = userPhone.getText().toString();
UUID uuid1=UUID.randomUUID();
String uudString1 =uuid1.toString();
myRef.child("Profile").child("useremail").setValue(userEmail2);
myRef.child("Profile").child("username").setValue(userName2);
myRef.child("Profile").child("phone").setValue(userPhone2);
myRef.child("Profile").child("downloadurl").setValue(downloadURLL);
Toast.makeText(Profile.this, "İnformation Saved", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Profile.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public void getDataFromFirebase() {
DatabaseReference newReference = firebaseDatabase.getReference("Profile");
newReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()){
HashMap<String,String> hashMap = (HashMap<String,String>) ds.getValue();
userImageFromFB.add(hashMap.get("downloadurl"));
userEmailFromFB.add(hashMap.get("useremail"));
userNameFromFB.add(hashMap.get("username"));
userPhoneFromFB.add(hashMap.get("phone"));
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#RequiresApi(api = Build.VERSION_CODES.M)
public void chooseImage(View view){
if(checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[] {android.Manifest.permission.READ_EXTERNAL_STORAGE},1);
}else{
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,2);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == 1){
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,2);
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
I want my newfeed.java tab to allow users to choose an image from gallery and > upload it to the firebase storage. Also, how to retrieve these images and >display in a listview ?
Newfeed.java
import static android.app.Activity.RESULT_OK;
public class NewfeedTab extends Fragment {
private static final int PICK_IMAGE_REQUEST = 234;
private StorageReference mStorageRef;
private EditText story;
private ImageButton choose;
private ImageButton upload;
private Uri filePath;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.news_feed, container, false);
mStorageRef = FirebaseStorage.getInstance().getReference();
story = (EditText)rootView.findViewById(R.id.et_story);
choose = (ImageButton)rootView.findViewById(R.id.imageButton_choose);
upload = (ImageButton)rootView.findViewById(R.id.imageButton_upload);
choose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
});
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(filePath != null){
final ProgressDialog progressDialog = new ProgressDialog(getContext());
progressDialog.setTitle("Uploading");
progressDialog.show();
StorageReference picsRef = mStorageRef.child("images/pic.jpg");
picsRef.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(getContext(),"Story posted",Toast.LENGTH_SHORT);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getContext(),"Story couldn't be posted",Toast.LENGTH_SHORT);
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
//calculating progress percentage
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
//displaying percentage in progress dialog
progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
}
});
}
}
});
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
}
}
}
The app closes after selecting the image from gallery. NewfeedTab.java is a fragment of tabbed activity.
newsfeed.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.seven.pprs.bloodlink.TabActivity$PlaceholderFragment">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/et_story"
android:layout_toStartOf="#+id/imageButton_choose"
android:hint="Share your stories here" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#mipmap/ic_file_upload_black_24dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:id="#+id/imageButton_upload" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:dividerHeight="1dp"
android:divider="#android:color/holo_red_dark"
android:id="#+id/list_of_posts"
android:layout_marginBottom="16dp"
android:layout_below="#+id/et_story" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#mipmap/ic_add_a_photo_black_24dp"
android:layout_alignBottom="#+id/imageButton_upload"
android:layout_toStartOf="#+id/imageButton_upload"
android:id="#+id/imageButton_choose" />
Do you have read permission in your AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>