How to upload images to firebase storage from tabbed actvity? - java

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"/>

Related

Incorrect displaying items in RecyclerView while scrolling

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

Not able to send Image in chat Application

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.

How can I hide Delete button from recyclerview, when the file is not exist?

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();
}
}

Android - Retrieve a path of an picked image

I have java code to pick an image from gallery or camera. In this code when user picks an image then it gets cropped into 200x200 size. I am looking for absolute path of that cropped image and I want to move that cropped image into SD card. But I am not getting the path with file extension. When I tried to get path then it is returning path with file name including random number like below.
/storage/media/865412
I am unable to move this file. I need the absolute path with the file extension.
ProfileInfo.java
public class ProfileInfo extends Activity {
private Uri mImageCaptureUri;
private ImageView mImageView;
private static final int PICK_FROM_CAMERA = 1;
private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_info);
final String [] items = new String [] {"Take from camera", "Select from gallery"};
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) { //pick from camera
if (item == 0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else { //pick from file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
}
} );
final AlertDialog dialog = builder.create();
mImageView = (ImageView) findViewById(R.id.profile_pic);
mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
switch (requestCode) {
case PICK_FROM_CAMERA:
doCrop();
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
doCrop();
break;
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
mImageView.setImageBitmap(photo);
Toast.makeText(getApplicationContext(),
photo.getWidth()+"x"+photo.getHeight()+"\n"+photo.getByteCount()+"\n",
0).show();
}
File f = new File(mImageCaptureUri.getPath());
if (f.exists()) f.delete();
Toast.makeText(getApplicationContext(),mImageCaptureUri.getPath(), 0).show();
break;
}
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );
int size = list.size();
if (size == 0) {
Toast.makeText(this, "Can not find image crop app", Toast.LENGTH_SHORT).show();
return;
} else {
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
} else {
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
co.appIntent= new Intent(intent);
co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Crop App");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
#Override
public void onCancel( DialogInterface dialog ) {
if (mImageCaptureUri != null ) {
getContentResolver().delete(mImageCaptureUri, null, null );
mImageCaptureUri = null;
}
}
} );
AlertDialog alert = builder.create();
alert.show();
}
}
}
}
profile_info.xml
<RelativeLayout 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"
android:background="#color/activity_bg_color"
android:paddingBottom="0dp"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.beproject.ourway.ProfileInfo" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:alpha="0.7"
android:text="Tap on image to change (Optional)"
android:textColor="#FFFFFF" />
<ImageView
android:id="#+id/profile_pic"
android:layout_width="156dp"
android:layout_height="156dp"
android:layout_gravity="center_horizontal"
android:layout_margin="10dp"
android:adjustViewBounds="true"
android:src="#drawable/user" />
<EditText
android:id="#+id/your_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout1"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:gravity="center_horizontal"
android:hint="Your name..."
android:textAlignment="center"
android:textColorHint="#DFDFDF" >
</EditText>
</LinearLayout>
<Button
android:id="#+id/skip_image_upload"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="22dp"
android:background="#drawable/flat_button_selector"
android:text="Skip"
android:textColor="#FFFFFF" />
<Button
android:id="#+id/image_upload"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/linearLayout1"
android:layout_alignParentBottom="true"
android:layout_marginBottom="73dp"
android:background="#drawable/flat_button_selector"
android:onClick="uploadImage"
android:text="Upload"
android:textColor="#FFFFFF" />
</RelativeLayout>
CropOptionAdapter.java
public class CropOptionAdapter extends ArrayAdapter<CropOption> {
private ArrayList<CropOption> mOptions;
private LayoutInflater mInflater;
public CropOptionAdapter(Context context, ArrayList<CropOption> options) {
super(context, R.layout.crop_selector, options);
mOptions = options;
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup group) {
if (convertView == null)
convertView = mInflater.inflate(R.layout.crop_selector, null);
CropOption item = mOptions.get(position);
if (item != null) {
((ImageView) convertView.findViewById(R.id.iv_icon)).setImageDrawable(item.icon);
((TextView) convertView.findViewById(R.id.tv_name)).setText(item.title);
return convertView;
}
return null;
}
}
CropOption.java
public class CropOption {
public CharSequence title;
public Drawable icon;
public Intent appIntent;
}
crop_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:gravity="center_vertical">
<ImageView
android:id="#+id/iv_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/>
</LinearLayout>
You don't necessarily need the absolute file path in order to copy the file, because you can open an InputStream from the Uri directly and copy the contents from that:
void copyFileFromUri(Uri sourceUri, String destFilePath) throws IOException
{
InputStream in = getContentResolver().openInputStream(sourceUri);
File outFile = new File(destFilePath);
OutputStream out = new FileOutputStream(outFile);
copyFile(in, out);
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
copyFile() function copied from answer to this question

Why am I not able to press the buttons when I come into the page?

public class Uploads extends Activity implements OnClickListener {
ImageView btnAllShops, btnFavourites, btnUploads, btnSettings, btnBuys,
btnTakePhoto;
GridView gvUploads;
PhotoDbAdapter ourHelper;
private String description, category, price, imagepath;
final static int cameraData = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_uploads);
findViewById();
onBackPressed();
sdcard();
}
private void findViewById() {
gvUploads = (GridView) findViewById(R.id.gvUploads);
btnAllShops = (ImageView) findViewById(R.id.btnAllShops);
btnFavourites = (ImageView) findViewById(R.id.btnFavourites);
btnUploads = (ImageView) findViewById(R.id.btnUploads);
btnSettings = (ImageView) findViewById(R.id.btnSettings);
btnBuys = (ImageView) findViewById(R.id.btnBuys);
btnTakePhoto = (ImageView) findViewById(R.id.btnTakePhoto);
btnAllShops.setOnClickListener(this);
btnFavourites.setOnClickListener(this);
btnUploads.setOnClickListener(this);
btnSettings.setOnClickListener(this);
btnBuys.setOnClickListener(this);
btnTakePhoto.setOnClickListener(this);
}
#Override
public void onBackPressed() {
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap bmp = (Bitmap) extras.get("data");
Intent goMain = new Intent(getApplicationContext(),
EditUploads.class);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, bs);
goMain.putExtra("byteArray", bs.toByteArray());
startActivity(goMain);
}
}
private void sdcard() {
setContentView(R.layout.activity_uploads);
// Set up an array of the Thumbnail Image ID column we want
String[] projection = { MediaStore.Images.Thumbnails._ID };
// Create the cursor pointing to the SDCard
cursor = managedQuery(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection, // Which
// columns
// to
// return
null, // Return all rows
null, MediaStore.Images.Thumbnails.IMAGE_ID);
// Get the column index of the Thumbnails Image ID
columnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
GridView gvuploads = (GridView) findViewById(R.id.gvUploads);
gvuploads.setAdapter(new ImageAdapter(this));
}
private class ImageAdapter extends BaseAdapter {
private Context context;
public ImageAdapter(Context localContext) {
context = localContext;
}
public int getCount() {
return cursor.getCount();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView picturesView;
if (convertView == null) {
picturesView = new ImageView(context);
// Move cursor to current position
cursor.moveToPosition(position);
// Get the current value for the requested column
int imageID = cursor.getInt(columnIndex);
// Set the content of the image based on the provided URI
picturesView.setImageURI(Uri.withAppendedPath(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, ""
+ imageID));
picturesView.setScaleType(ImageView.ScaleType.FIT_XY);
picturesView.setPadding(10, 10, 10, 10);
picturesView
.setLayoutParams(new GridView.LayoutParams(266, 266));
} else {
picturesView = (ImageView) convertView;
}
return picturesView;
}
}
private Cursor cursor;
// Column index for the Thumbnails Image IDs.
private int columnIndex;
#Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.btnAllShops:
Intent iA = new Intent(getApplicationContext(), AllShops.class);
startActivity(iA);
break;
case R.id.btnFavourites:
Intent iF = new Intent(getApplicationContext(), Favourites.class);
startActivity(iF);
break;
case R.id.btnUploads:
Intent iU = new Intent(getApplicationContext(), Uploads.class);
startActivity(iU);
break;
case R.id.btnSettings:
Intent iS = new Intent(getApplicationContext(),
SettingsActivity.class);
startActivity(iS);
break;
case R.id.btnBuys:
Intent iBuy = new Intent(getApplicationContext(), Buys.class);
startActivity(iBuy);
break;
case R.id.btnTakePhoto:
Intent i = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, cameraData);
break;
}
}
}
before i added the grid-view layout i was able to use the button functions. However, after i inserted the grid-view layout, all i can do is just scroll through the images on the grid-view. What do i do so that i can both scroll through the images and also use the buttons? Thanks
public class Mobile extends Activity {
PhotoDbAdapter ourHelper;
ImageView grid_item_image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mobile);
grid_item_image = (ImageView) findViewById(R.id.grid_item_image);
PhotoDbAdapter getImage = new PhotoDbAdapter(this);
getImage.open();
String getImagepathe = getImage.getImagePath();
Toast.makeText(this, getImagepathe, Toast.LENGTH_LONG).show();
int id = getResources().getIdentifier(getImagepathe, null, null);
grid_item_image.setImageResource(id);
Intent mobile = new Intent(getApplicationContext(), Uploads.class);
startActivity(mobile);
}
}
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusableInTouchMode="true"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="5"
android:src="#drawable/sh_uploads" />
<ImageView
android:id="#+id/btnTakePhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/hbtn_camera" />
</LinearLayout>
<GridView
android:id="#+id/gvUploads"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/bottomBar"
android:layout_below="#+id/linearLayout1"
android:numColumns="3"
tools:listitem="#layout/mobile" >
</GridView>
<LinearLayout
android:id="#+id/bottomBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal" >
<ImageView
android:id="#+id/btnAllShops"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1.0"
android:contentDescription="#null"
android:src="#drawable/sbtn_home" />
<ImageView
android:id="#+id/btnFavourites"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1.0"
android:contentDescription="#null"
android:src="#drawable/sbtn_fave" />
<ImageView
android:id="#+id/btnBuys"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1.0"
android:contentDescription="#null"
android:src="#drawable/sbtn_buys" />
<ImageView
android:id="#+id/btnUploads"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1.0"
android:contentDescription="#null"
android:src="#drawable/sbtn_uploads" />
<ImageView
android:id="#+id/btnSettings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1.0"
android:contentDescription="#null"
android:src="#drawable/sbtn_settings" />
</LinearLayout>
If the images are into the grid, maybe this helps:
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
if(v.getId() == btnFavourites.getId()){
//Something happen
}
}
});

Categories