How to delete listview item in fragment? - java

I'm trying to delete an item from a listview, but there is a problem..i'm using a fragment and I don't know how to get the "delete image button" to add a onClickListener...
That's my xml of the delete button which is in payment_list_view.xml :
<ImageButton
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/trash_icon"
android:padding="10dp"
android:id="#+id/delete_payment_btn"
android:background="#android:color/white" />
Then, I have my PaymentFragment which contains my listview:
package com.nicola.baccillieri.splitpayment;
public class PaymentFragment extends Fragment {
private String descString;
private int price;
private String payedBy;
private ArrayList<String> descPayArray;
private ArrayList<Integer> priceArray;
private ArrayList<String> payedByArray;
int trash;
PaymentAdapter customAdapter;
private final static String SHARED_PREFS = "sharedPrefs";
FirebaseFirestore db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = FirebaseFirestore.getInstance();
trash = (R.drawable.trash_icon);
descPayArray = new ArrayList<>();
priceArray = new ArrayList<>();
payedByArray = new ArrayList<>();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView=inflater.inflate(R.layout.payments_fragment,container,false);
ProgressBar detailsPb = rootView.findViewById(R.id.details_pb);
detailsPb.getIndeterminateDrawable().setColorFilter(0XFF3F51B5,
PorterDuff.Mode.MULTIPLY);
detailsPb.setVisibility(View.VISIBLE);
final ListView listView = rootView.findViewById(R.id.paymentLv);
String email = getEmail();
String groupName = getActivity().getIntent().getStringExtra("title");
DocumentReference docRef = db.collection("users").document(email).collection("Group").document(groupName);
docRef.collection("Payments")
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for (QueryDocumentSnapshot document : queryDocumentSnapshots) {
//Extracting payment description from each document
descString = document.getId();
descPayArray.add(descString);
//Extracting cost and who payed from each document
price = document.getLong("cost").intValue();
priceArray.add(price);
payedBy = document.getString("payed by");
payedByArray.add(payedBy);
trash = R.drawable.trash_icon;
customAdapter = new PaymentAdapter(getActivity(), descPayArray, payedByArray, priceArray, trash);
listView.setAdapter(customAdapter);
ProgressBar detailsPb = rootView.findViewById(R.id.details_pb);
detailsPb.setVisibility(View.GONE);
// That's the line that cause the error
ImageButton deleteBtn = rootView.findViewById(R.id.delete_payment_btn);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String groupName = getActivity().getIntent().getStringExtra("title");
int positionToRemove = (int) v.getTag();
String email = getEmail();
String paymentToRemove = descPayArray.get(positionToRemove);
DocumentReference docRef = db.collection("users").document(email).collection("Group").document(groupName).collection("Payments").document(paymentToRemove);
docRef.delete();
descPayArray.remove(positionToRemove);
customAdapter.notifyDataSetChanged();
}
});
}
// If there isn't any payment display a blank activity
ProgressBar detailsPb = rootView.findViewById(R.id.details_pb);
detailsPb.setVisibility(View.GONE);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
ProgressBar detailsPb = rootView.findViewById(R.id.details_pb);
detailsPb.setVisibility(View.GONE);
Toast.makeText(getContext(), "Failed to load payments", Toast.LENGTH_LONG).show();
}
});
return rootView;
}
public String getEmail() {
SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
String email = (sharedPreferences.getString("email", ""));
return email;
}}
and finally the file group_detail_activity.xml contains my 2 fragment with a tab layout.
Now, the app crash when It has to show the PaymentFragment, because ImageButton deleteBtn = rootView.findViewById(R.id.delete_payment_btn); says
`java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference".
That's because my rootView contains payment_fragment.xml, and not the payment_list_view.xml. So It doesn't find the button.
I've tryed to add final View rootListView=inflater.inflate(R.layout.payment_list_view,container,false);
and then it shows the list view, but when I click on the delete button, it doesn't do anything.
What should I do?
That's my PaymentAdapter:
package com.nicola.baccillieri.splitpayment;
public class PaymentAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> payDesc;
private ArrayList<String> payedBy;
private ArrayList<Integer> price;
private int trash;
LayoutInflater inflater;
public PaymentAdapter(Context context, ArrayList<String> payDesc, ArrayList<String> payedBy, ArrayList<Integer> price, int trash) {
this.context = context;
this.payDesc = payDesc;
this.payedBy = payedBy;
this.price = price;
this.trash = trash;
inflater = (LayoutInflater.from(context));
}
#Override
public int getCount() {
return payDesc.size();
}
#Override
public Object getItem(int position) {
return payDesc.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.payment_list_view, null);
TextView paymentDesc = convertView.findViewById(R.id.payedDescTv);
TextView payedByTv = convertView.findViewById(R.id.payedByTv);
TextView priceTv = convertView.findViewById(R.id.priceTv);
ImageButton trashIcon = convertView.findViewById(R.id.delete_payment_btn);
paymentDesc.setText(payDesc.get(position));
payedByTv.setText("Payed by " + payedBy.get(position));
priceTv.setText(String.valueOf(price.get(position)) + "€");
trashIcon.setImageResource(trash);
trashIcon.setTag(position);
return convertView;
}}
The problem is that I need to delete the item both from the listview and from firebase...so I need the getEmail() method e the getExtra which is in PaymentFragment..If i put the listener on the adapter, how can I delete o Firebase?

Try this way. On list clicked you can delete item
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
payedByArray.remove(position);
adapter.notifyItemRemoved(position);
}
});
Other way is to put the Delete Button in your payment_list_view and then in Adapter you can get position on that button click and delete it

From Custom_adapater's viewholder get the view id , and you can easily delete the item by using
payedByArray.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, payedByArray.size());
How to delete list item ,a SO's question already answered.. Have a look...
that might solve your problem.

You can set a listener to link the delete image button action to your fragment. Then can the button is click you trigger the listener and do what your want in your fragment. Yo can send the position to remove the good element

Your adapter don't know that list is being modified. you need to provide latest list to adapter after deletion of item.
Make your payedByArray list public in adapter code.
This activity code.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
payedByArray.remove(position);
//payedByArray is activity list;
adapter.payedByArray = payedByArray;
adapter.notifyItemRemoved(position);
}
});

Related

Android: Sending a cardview from one fragment to another

I need some help for a summer project
This is my Events fragment
This is my MyList fragment
I'm using a RecyclerView+Cardview to display the Events. The idea is that the user can click the big plus on the right side of each card, and the card would be displayed in the MyList fragment. I would like to ask if it's possible to transfer a card directly from one fragment to another? Also, both fragments are contained within the same activity, which makes it a little trickier(I haven't found any available solutions).
If that is not possible, another way is to transfer the reference type object contained in the CardView to the MyList fragment. However, this is even less straightforward. This is because the button is inflated in the adapter, but there is no reference type object created here. I have seen many tutorials on using the Parcelable interface, however, I don't know how to implement it here when I'm unable to even create the object in the adapter. The reference object is created in another activity and stored in Firebase before it is read and displayed.
I'm going to attach my EventsAdapter.java and EventsItem.java and EventsFragment.java code below, but please let me know if I should include more code to describe the problem.
Thanks for reading my very long post!!
public class EventsAdapter extends RecyclerView.Adapter<EventsAdapter.EventsViewHolder> implements Filterable {
private ArrayList<EventsItem> mEventsList;
private ArrayList<EventsItem> mEventsListFull;
private EventsAdapter.OnItemClickListener mListener;
private Context mContext;
private DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.UK);
public interface OnItemClickListener {
void onItemClick(int position);
}
//the ViewHolder holds the content of the card
public static class EventsViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public ImageView mAddButton;
public TextView mTextView1;
public TextView mTextView2;
public TextView mTextView3;
public TextView mTextView4;
public TextView mTextView5;
public EventsViewHolder(Context context, View itemView, final EventsAdapter.OnItemClickListener listener) {
super(itemView);
final Context context1 = context;
mImageView = itemView.findViewById(R.id.imageView);
mAddButton = itemView.findViewById(R.id.image_add);
mTextView1 = itemView.findViewById(R.id.title);
mTextView2 = itemView.findViewById(R.id.event_description);
mTextView3 = itemView.findViewById(R.id.date);
mTextView4 = itemView.findViewById(R.id.location);
mTextView5 = itemView.findViewById(R.id.time);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
mAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str1 = mTextView1.getText().toString();
String str2 = mTextView2.getText().toString();
String str3 = mTextView3.getText().toString();
String str4 = mTextView4.getText().toString();
String str5 = mTextView5.getText().toString();
Bundle bundle = new Bundle();
bundle.putString("title", str1);
bundle.putString("event description", str2);
bundle.putString("date", str3);
bundle.putString("location", str4);
bundle.putString("time", str5);
MylistFragment mlf = new MylistFragment();
mlf.setArguments(bundle);
}
});
}
}
//Constructor for EventsAdapter class. This ArrayList contains the
//complete list of items that we want to add to the View.
public EventsAdapter(Context context, ArrayList<EventsItem> EventsList) {
mEventsList = EventsList;
mContext = context;
mEventsListFull = new ArrayList<>(EventsList); // copy of EventsList for SearchView
}
//inflate the items in a EventsViewHolder
#NonNull
#Override
public EventsAdapter.EventsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.event_item, parent, false);
EventsAdapter.EventsViewHolder evh = new EventsAdapter.EventsViewHolder(mContext, v, mListener);
return evh;
}
#Override
public void onBindViewHolder(#NonNull EventsAdapter.EventsViewHolder holder, int position) {
EventsItem currentItem = mEventsList.get(position);
holder.mImageView.setImageResource(currentItem.getProfilePicture());
holder.mTextView1.setText(currentItem.getTitle());
holder.mTextView2.setText(currentItem.getDescription());
holder.mTextView3.setText(df.format(currentItem.getDateInfo()));
holder.mTextView4.setText(currentItem.getLocationInfo());
holder.mTextView5.setText(currentItem.getTimeInfo());
}
#Override
public int getItemCount() {
return mEventsList.size();
}
public class EventsItem implements Occasion, Parcelable {
//fields removed for brevity
//constructor removed for brevity
}
public EventsItem() {
}
public EventsItem(Parcel in) {
profilePicture = in.readInt();
timeInfo = in.readString();
hourOfDay = in.readInt();
minute = in.readInt();
locationInfo = in.readString();
title = in.readString();
description = in.readString();
}
public static final Creator<EventsItem> CREATOR = new Creator<EventsItem>() {
#Override
public EventsItem createFromParcel(Parcel in) {
return new EventsItem(in);
}
#Override
public EventsItem[] newArray(int size) {
return new EventsItem[size];
}
};
//getter methods have been removed for brevity
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(profilePicture);
dest.writeString(timeInfo);
dest.writeString(locationInfo);
dest.writeString(title);
dest.writeString(description);
dest.writeString(df.format(dateInfo));
dest.writeInt(hourOfDay);
dest.writeInt(minute);
}
}
public class EventsFragment extends Fragment {
ArrayList<EventsItem> EventsItemList;
FirebaseDatabase mDatabase;
DatabaseReference mDatabaseReference;
ValueEventListener mValueEventListener;
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private EventsAdapter mAdapter;
private View rootView;
public FloatingActionButton floatingActionButton;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_events, container, false);
mDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mDatabase.getReference().child("Events");
createEventsList();
buildRecyclerView();
floatingActionButton = rootView.findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), EventsAdder.class);
startActivity(intent);
}
});
mValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
EventsItemList.add(snapshot.getValue(EventsItem.class));
}
EventsAdapter eventsAdapter = new EventsAdapter(getActivity(), EventsItemList);
mRecyclerView.setAdapter(eventsAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
mDatabaseReference.addValueEventListener(mValueEventListener);
setHasOptionsMenu(true);
Toolbar toolbar = rootView.findViewById(R.id.events_toolbar);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
return rootView;
}
public void createEventsList() {
EventsItemList = new ArrayList<>();
}
public void buildRecyclerView() {
mRecyclerView = rootView.findViewById(R.id.recyclerview);
mLayoutManager = new LinearLayoutManager(getContext());
mAdapter = new EventsAdapter(getActivity(), EventsItemList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
}
}
If you would like to see the same CardView within the MyListFragment, you could have the MyListFragment contain a RecyclerView, and reuse the same EventsAdapter and EventsViewHolder. The only difference is that rather than populating the adapter with all the children of the "Events" from your database, you would only populate it with the single Event that you want.
Also, since you have made your Event class implement parcelable, you do not need to manually create the bundle when clicking the plus button.
I am assuming you have a single Activity, and you simply want to replace the EventsFragment with the MyListFragment. Checkout the docs for replacing one fragment with another.
Step 1:
Extend your onItemClickListener to look like:
public interface OnItemClickListener {
void onItemClick(int position);
void onPlusButtonClick(int position);
}
and adjust the code in your EventsViewHolder constructor to look like this when the plus button is clicked:
mAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
// no need to manually create the bundle here
// you already have all the information you need
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onPlusButtonClick(position);
}
}
}
});
Step 2:
Implement our new method onPlusButtonClick. As per our discussion in the comments, it seems you do not implement this interface anywhere. You can implement it inside the constructor to your EventsAdapter:
public EventsAdapter(Context context, ArrayList<EventsItem> EventsList) {
mEventsList = EventsList;
mContext = context;
mEventsListFull = new ArrayList<>(EventsList); // copy of EventsList for SearchView
mListener = new OnItemClickListener() {
#Override
public void onItemClick() {
// handle clicking the entire view holder
// NOTE: inside your EventsViewHolder, it looks like you call this method on the entire itemView. This could 'swallow' the click on the plus button. You may need to adjust your code to handle this.
}
#Override
public void onPlusButtonClick(int position) {
MyListFragment myListFragment = new MyListFragment();
Event event = mEventsList.get(position);
Bundle bundle = new Bundle();
bundle.putExtra("event", event); // this will work due to implementing parcelable
myListFragment.setArguments(bundle);
// use mContext since im assuming we areinside adapter
// if in an Activity, no need to use context to get the fragment manager
FragmentTransaction transaction = mContext.getSupportFragmentManager().beginTransaction();
// Replace the EventsFragment with the MyListFragment
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, myListFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
}
}
Step 3:
Inside your MyListFragments onCreateView() method:
#Override
public View onCreateView (
LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState
) {
Bundle bundle = getArguments();
Event event = bundle.getExtra("event"); // again, will work due to implementing parcelable
// from here you should bind to a recycler view, and you can even reuse your adapter like so:
List<EventsItem> singleEventList = new List<EventsItem>();
singleEventList.add(event);
EventsAdapter adapter = new EventsAdapter(getActivity(), singleEventList);
// be sure to inflate and return your view here...
}
and you should be good to go!
I have left out bits of code here and there for simplicity.. but I hope this is understandable.
As a side note.. in your firebase database listener, it is bad practice to create a new EventsAdapter every single time your data is updated. Instead, you should update the data in the adapter with the new values. Do this by creating a public method inside the adapter such as replaceEvents(List<EventsItem> newEvents), and inside, replace mEventsList with the new events, then call notifyDataSetChanged().

Android - pass values from clicked item on ListView and display them on a new Actvity

I am an intern at this company and I have a task assigned to me by my team leader where I need to make an app that displays a list of items that I can add to and edit/delete the items on the list. I am following the requirements given to me on what the app needs to do.
The problem I'm having is that I need to pass values from an item when clicked on a ListView which uses a custom adapter, and have them sent to a new activity and displayed on the new activity's textviews and imageview. I have tried using putExtras() methods in the list click method and getting the values using getExtras() methods but they didn't work and I've already deleted those codes, so they are no longer there. If you need more of the classes/activities I'm using please let me know. I am using Android Studio 3.1.4
ItemListView.java
public class ItemListView extends AppCompatActivity {
DatabaseHelper myDB;
ArrayList<Item> itemList;
ListView listView;
Item item;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_list_view);
listView = (ListView) findViewById(R.id.listView);
myDB = new DatabaseHelper(this);
itemList = new ArrayList<>();
Cursor data = myDB.getListContents();
int numRows = data.getCount();
if(numRows == 0){
Toast.makeText(ItemListView.this, "There is nothing in the database.", Toast.LENGTH_LONG).show();
} else {
while(data.moveToNext()){
item = new Item(data.getString(1), data.getString(2), data.getString(3));
itemList.add(item);
}
Row_ListAdapter adapter = new Row_ListAdapter(this, R.layout.list_adapter_view, itemList);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(ItemListView.this, ViewItemClicked.class);
startActivity(intent);
}
});
}
ViewItemClicked.java
I want the values displayed onto the layout of this activity when a row is clicked.
public class ViewItemClicked extends AppCompatActivity {
ImageView image;
TextView name, desc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_item_clicked);
}
}
Other classes I used:
Row_ListAdapter.java
public class Row_ListAdapter extends ArrayAdapter<Item> {
private LayoutInflater mInflater;
private ArrayList<Item> items;
private int mViewResourceId;
ImageView image;
TextView name;
TextView description;
public Row_ListAdapter(Context context, int textViewResourceId, ArrayList<Item> items){
super(context, textViewResourceId, items);
this.items = items;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mViewResourceId = textViewResourceId;
}
public View getView(int position, View convertView, ViewGroup parents){
convertView = mInflater.inflate(mViewResourceId, null);
Item item = items.get(position);
if(item != null){
image = (ImageView) convertView.findViewById(R.id.iconIV);
name = (TextView) convertView.findViewById(R.id.nameTV);
description = (TextView) convertView.findViewById(R.id.descTV);
if(image != null){
image.setImageBitmap(item.getImage());
}
if(name != null){
name.setText(item.getName());
}
if(description != null){
description.setText(item.getDescription());
}
}
return convertView;
}
}
Link to GUI: https://i.stack.imgur.com/wHfgv.png
Before you pass the data, implement your Item Class with Serializable like this:
public class Item implements Serializable{
/*your class code here*/
}
Then pass the data in the listView.setOnItemClicklistener like this
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Item passItem = itemList.get(position);
Intent intent = new Intent(ItemListView.this, ViewItemClicked.class);
Bundle itemBundle = new Bundle();
itemBundle.putSerializable("dataItem",passItem)// put the data and define the key
intent.putExtras(itemBundle)
startActivity(intent);
}
});
and to open the data in the ViewItemClicked.Class
public class ViewItemClicked extends AppCompatActivity {
ImageView image;
TextView name, desc;
Item item;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
item = (Item) getIntent().getSerializableExtra("dataItem"); // use the key
setContentView(R.layout.activity_view_item_clicked);
/*now u can use the item data*/
}
}
Try the codes below:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(ItemListView.this, ViewItemClicked.class);
String name = itemList.get(position).getString(1);
String description = itemList.get(position).getString(2);
String something_else = itemList.get(position).getString(3);
intent.putExtra("name", name);
intent.putExtra("description", description);
intent.putExtra("something_else", something_else);
startActivity(intent);
}
In your Details Activity:
Intent intent = getIntent();
String name = intent.getStringExtra("name");
String description = intent.getStringExtra("description");
String something_else = intent.getStringExtra("something_else");
Now use the strings to show the values in the desired places.
as
edittext.setText(name);
WHAT FORMAT TYPE OF IMAGE YOUR ARE USING
Is it Base64 or Bitmap if it is Base64 try this code..
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(ItemListView.this, ViewItemClicked.class);
String name = list.get(position).getName();
String description = list.get(position).getDescription();
String image= list.get(position).getImage();
startActivity(intent);
}
In Your Second Activity use this code..
Intent intent = getIntent();
String name = intent.getStringExtra("name");
String description = intent.getStringExtra("description");
String image = intent.getStringExtra("image");
Convert here Base64 to Bitmap..
byte[] decodedString = Base64.decode(image, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,
decodedString.length);
Define an interface for listening item click event
public class Row_ListAdapter extends ArrayAdapter<Item> {
private LayoutInflater mInflater;
private ArrayList<Item> items;
private int mViewResourceId;
ImageView image;
TextView name;
TextView description;
OnItemListener mListener;
public Row_ListAdapter(Context context, int textViewResourceId, ArrayList<Item> items){
super(context, textViewResourceId, items);
this.items = items;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mViewResourceId = textViewResourceId;
}
public View getView(int position, View convertView, ViewGroup parents){
convertView = mInflater.inflate(mViewResourceId, null);
Item item = items.get(position);
if(item != null){
image = (ImageView) convertView.findViewById(R.id.iconIV);
name = (TextView) convertView.findViewById(R.id.nameTV);
description = (TextView) convertView.findViewById(R.id.descTV);
if(image != null){
image.setImageBitmap(item.getImage());
}
if(name != null){
name.setText(item.getName());
}
if(description != null){
description.setText(item.getDescription());
}
}
convertView.setOnClickListener((v) -> {
if(mListener != null) {
mListener.onItemClick(v, item);
}
})
return convertView;
}
public void setOnItemListener(OnItemListener listener) {
mListener = listener;
}
public interface OnItemClickListener {
void onItemClick(View v, Item item);
}
}
Then, implement OnItemClickListener in the activity and set it to the adapter:
Row_ListAdapter adapter = new Row_ListAdapter(this, R.layout.list_adapter_view, itemList);
adapter.setOnItemListener("your implement");

Android - How to handle multiple Elements in a singe ListViewItem?

i have a specific issue. Im creating a App which allows me to display recepts of certain dishes. I designed a custom Adapter which contains a TextView and RatingBar. So in my other Activity(ViewDatabase) i retrieve the dish-name from a JSON-File (method is called : showData) and display it on a ListView which gets the custom adapter.
My problem is now that dont know why i can only select either the name of my dish ( so the textview of my adapter ) or the ratingbar ( is also in my adapter).
I tried to put in the method : myListView.setItemsCanFocus(true); but still doesnt work.
Is i didnt implement a clicklistener to my text in the Adapter? I tried to implement one.I need a explicit intent which swaps the Activity but i cant
go from a Adapterclass to a other class in a intent.
In the ViewDatabse- Class is onItemClick my method for changing the activty if i click the text.
Here is my code :
Adapter:
a)
public UserInformationAdapter(Context context, List<UserInformation> objects) {
super(context, R.layout.rating_item, objects);
this.context = context;
table = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.rating_item, null);
}
TextView name = (TextView) v.findViewById(R.id.hauptgerichte);
RatingBar ratingBar = (RatingBar) v.findViewById(R.id.rate_bar);
UserInformation userInformation = table.get(position);
ratingBar.setOnRatingBarChangeListener(onRatingChangedListener(position));
ratingBar.setTag(position);
ratingBar.setRating(getItem(position).getRatingStar());
name.setText(userInformation.getName());
name.setTag(position);
return v;
}
private RatingBar.OnRatingBarChangeListener onRatingChangedListener(final int position) {
return new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
UserInformation item = getItem(position);
assert item != null;
item.setRatingStar(v);
Log.i("Adapter", "star: " + v);
}
};
}
}
This is the Item (for name and ratingbar):
public class UserInformation {
private String name;
private float ratingStar;
public UserInformation(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
void setRatingStar(float ratingStar) {
this.ratingStar = ratingStar;
}
float getRatingStar() {
return 0;
}
#Override
public String toString(){
return name;
}
}
This is the Activity which retrieves the Name:
Activity:
public class ViewDatabase extends AppCompatActivity {
private static final String TAG = "ViewDatabase";
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
private String userID;
private ArrayList<String> array;
private final List<UserInformation> arr = new ArrayList<>();
private UserInformationAdapter adapter2;
private ListView mListView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_database_layout);
array = new ArrayList<>();
mListView = (ListView) findViewById(R.id.list_karnivoure);
mListView.setItemsCanFocus(true);
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
FirebaseUser user = mAuth.getCurrentUser();
userID = user.getUid();
myRef.child("shakes").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
showData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showData(DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> children = dataSnapshot.getChildren();
for (DataSnapshot child: children){
UserInformation uInfo = child.getValue(UserInformation.class);
arr.add(uInfo);
adapter2 = new UserInformationAdapter(ViewDatabase.this, arr);
mListView.setAdapter(adapter2);
mListView.setItemsCanFocus(true);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mListView.setItemsCanFocus(true);
Object listItem = mListView.getItemAtPosition(position);
Intent i = new Intent(ViewDatabase.this,KarnivoureInput.class);
i.putExtra("name", listItem.toString());
startActivity(i);
}
});
}
https://stackoverflow.com/a/8955441/5608931
Try adding this attribue to TextView and RatingBar . It would be clickable but will not get Focused
android:focusable="false"

Passing RecyclerView CardView Clicked Item Data To Activity

I have a question about passing clicked cardview data to activity, and here the full story :
I have an Activity called "Details", which contains 2 TextViews in it's layout, Title & Description .
I have setup a fragment ( tab_1 ) which contain the recyclerview codes and the the items data, each item of those contain : title & description .
What i want :
When the user click the item, it will open the Details Activity, and change Details layout title, with clicked item title, and the same for description .
I've manged to create the other activity as an example, and made intent to start it, plus adding "addOnTouchlistener" thanks to Stackoverflow, i've found the way to make it .
So, how to make this alive? I've tried many ways of the available answers on Stackoverflow, but all of them not working, or not related to my request .
Here are my files :
itemsdata.java :
public class itemsdata {
int CatPic;
String title;
String Descr;
int Exapnd;
int expand_no;
tab_1.java ( fragment )
public class tab_1 extends Fragment implements SearchView.OnQueryTextListener {
private RecyclerView mRecyclerView;
public RecyclingViewAdapter adapter;
private Activity context;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.tab_1, container, false);
mRecyclerView = (RecyclerView)layout.findViewById(R.id.recycler_view);
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener
(getContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent i = new Intent(view.getContext(), DetailsActivity.class);
view.getContext().startActivity(i);
}
}));
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new RecyclingViewAdapter(getActivity(),Listed());
mRecyclerView.setAdapter(adapter);
return layout;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
}
#Override
public boolean onQueryTextChange(String query) {
final List<itemsdata> filteredModelList = filter(Listed(), query);
adapter.animateTo(filteredModelList);
mRecyclerView.scrollToPosition(0);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
private List<itemsdata> filter(List<itemsdata> models, String query) {
query = query.toLowerCase();
final List<itemsdata> filteredModelList = new ArrayList<>();
for (itemsdata model : models) {
final String text = model.title.toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
public List<itemsdata> Listed()
{
//Titles Strings
String sys_title1 = getString(R.string.system_item_title_1);
String sys_title2 = getString(R.string.system_item_title_2);
String sys_title3 = getString(R.string.system_item_title_3);
//Description Strings
String sys_descr1 = getString(R.string.system_item_desc_1);
String sys_descr2 = getString(R.string.system_item_desc_2);
String sys_descr3 = getString(R.string.system_item_desc_3);
//Adding New Cards
List<itemsdata> data = new ArrayList<>();
//Categories Icons New Items ** Make It The Same
int[] icons = {
R.drawable.facebook_icon ,
R.drawable.twitter_icon ,
R.drawable.twitter_icon
};
//Expand Button New Items
int[] expandbutton = {
R.drawable.expanded ,
R.drawable.expanded ,
R.drawable.expanded
};
//UnExpand Button New Items
int[] unexpandbutton = {
R.drawable.ca_expand ,
R.drawable.ca_expand ,
R.drawable.ca_expand
};
//Titles New Items
String[] titles = {
sys_title1 ,
sys_title2 ,
sys_title3
};
//Description New Items
String[] Description = {
sys_descr1 ,
sys_descr2 ,
sys_descr3
};
for(int i = 0;i<titles.length && i < icons.length && i < Description.length && i < unexpandbutton.length && i < expandbutton.length ; i++)
{
itemsdata current = new itemsdata();
current.CatPic = icons[i];
current.title = titles[i];
current.Descr = Description[i];
current.expand_no = unexpandbutton[i];
current.Exapnd = expandbutton[i];
data.add(current);
}
return data;
}
}
Details Activity :
public class DetailsActivity extends AppCompatActivity{
TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
title = (TextView)findViewById(R.id.details_title);
}
EDIT : I've made it, i have added a button which open the fragment, and passed the data, in the Adapter, but i want it via tab_1.java, not the Adapter, i mean i want to click on the item to open the fragment, not on a button, here a snap from my Adapter code ( i've added it in OnBindViewHolder )
I've setup a OnClick and implemented the Vew.setOnClick ..etc, but when i click the item, nothing happen.
#Override
public void onBindViewHolder(final MyRecycleViewHolder holder, int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(),DetailsActivity.class);
v.getContext().startActivity(i);
}
});
//Referencing Data
final itemsdata currentobject = mdata.get(position);
//Referencing Items
holder.ProbTitle.setText(currentobject.title);
holder.ProbDescr.setText(currentobject.Descr);
holder.CategoryPic.setImageResource(currentobject.CatPic);
holder.ExpandButton.setImageResource(currentobject.Exapnd);
holder.ExpandNoButton.setImageResource(currentobject.expand_no);
//What Happen When You Click Expand Button .
holder.ExpandButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), DetailsActivity.class);
i.putExtra("TitleKey",holder.ProbTitle.getText().toString());
v.getContext().startActivity(i);
}
}
);
public static class MyRecycleViewHolder extends RecyclerView.ViewHolder
{
SwipeLayout swipeLayout;
//Defining Items .
TextView ProbTitle;
ImageButton ExpandButton;
TextView ProbDescr;
ImageButton ExpandNoButton;
ImageView CategoryPic;
/*
TextView Card_Star;
TextView Card_UnStar;
*/
TextView Card_Share;
//Referencing Resources
public MyRecycleViewHolder(final View itemView) {
super(itemView);
ProbTitle = (TextView) itemView.findViewById(R.id.prob_title);
CategoryPic = (ImageView) itemView.findViewById(R.id.cat_pic);
ProbDescr = (TextView) itemView.findViewById(R.id.prob_descr);
ExpandButton = (ImageButton) itemView.findViewById(R.id.expand_button);
ExpandNoButton = (ImageButton) itemView.findViewById(R.id.expand_no_button);
/*
Card_Star = (TextView) itemView.findViewById(R.id.card_star);
Card_UnStar = (TextView) itemView.findViewById(R.id.card_unstar);
*/
Card_Share = (TextView) itemView.findViewById(R.id.card_share);
swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
}
create an Interface inside your adapter containing methods. And while implementing your Adapter, those methods will be implemented in your activity and you can perform whatever action you want.
public class Adapter extends RecyclerView.Adapter<MyRecycleViewHolder> {
public interface Callbacks {
public void onButtonClicked(String titleKey);
}
private Callbacks mCallbacks;
public Adapter() {
}
#Override
public MyRecycleViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_details, null);
return new MyRecycleViewHolder(v);
}
#Override
public void onBindViewHolder(final MyRecycleViewHolder holder, final int i) {
holder.ExpandButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCallbacks != null) {
mCallbacks.onButtonClicked(holder.ProbTitle.getText().toString());
}
}
});
}
#Override
public int getItemCount() {
return;
}
public void setCallbacks(Callbacks callbacks) {
this.mCallbacks = callbacks;
}
}
you may try do this on your onItemClick()
Intent i = new Intent(view.getContext(), DetailsActivity.class);
i.putExtra("title", yourTitle);
i.putExtra("description", yourDescription);
view.getContext().startActivity(i);
and when oncreate in your DetailActivity,do this
String title = getIntent().getStringExtra("title");
String description = getIntent().getStringExtra("description");
so you can pass title and description to DetailActivity
IMO, you implement setOnClickListener inside Adapter of RecyclerView. You can refer to my following sample code, then apply its logic to your code. Hope it helps!
public class MyRVAdapter extends RecyclerView.Adapter<MyRVAdapter.ViewHolder> {
Context mContext;
List<String> mStringList;
public MyRVAdapter(Context mContext, List<String> mStringList) {
this.mContext = mContext;
this.mStringList = mStringList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView1 = (TextView) v.findViewById(R.id.textView1);
TextView textView2 = (TextView) v.findViewById(R.id.textView2);
Bundle bundle = new Bundle();
bundle.putString("key1", textView1.getText().toString());
bundle.putString("key2", textView2.getText().toString());
passToAnotherActivity(bundle);
}
});
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// do something...
}
#Override
public int getItemCount() {
if (mStringList != null) {
return mStringList.size();
}
return 0;
}
private void passToAnotherActivity(Bundle bundle) {
if (mContext == null)
return;
if (mContext instanceof MainActivity) {
MainActivity activity = (MainActivity) mContext;
activity.passToAnotherActivity(bundle); // this method must be implemented inside `MainActivity`
}
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ViewHolder(View itemView) {
super(itemView);
// do something...
}
#Override
public void onClick(View v) {
}
}
}
First of all make your "itemsdata" object to implement Parcelable. You can check it here . In your onItemClick method you pass the object to your Details activity using intent.putExtra("key",listOfDataItems.get(position));
In your DetailsActivity you can get your custom object with getParcelable("key")
All above methods worked, but kinda long, so this one worked for me :
Cardview cardview;
cardView = (CardView)itemView.findViewById(R.id.cv);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent (view.getContext(), DetailsActivity.class);
i.putExtra("TitleKey",ProbTitle.getText().toString());
i.putExtra("DescrKey",ProbDescr.getText().toString());
view.getContext().startActivity(i);
}
});
And in Details.java :
TextView title;
TextView Descr;
title = (TextView)findViewById(R.id.details_title);
Descr = (TextView)findViewById(R.id.details_descr);
String titleresult = result.getExtras().getString("TitleKey");
String Descrresult = result.getExtras().getString("DescrKey");
title.setText(titleresult);
Descr.setText(Descrresult);

Android Refresh ListActivity from BaseAdapter

I have a ListActivity and a custom adapter that extends BaseAdapter.
On each row of the ListView, there is a button and a few more views. onClickListener is declared in the adapter.
How can I refresh list view after button is clicked ?
Here is the code
List Activity:
.........
super.onCreate(savedInstanceState);
here im reading content from a file and then creating adapter with that content
adapter = new UvArrayAdapter(this, strarray3, strarray2, intarray);
setListAdapter(adapter);
..........
Adapter:
.......
public class UvArrayAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater linflater;
private TextView txt_1, txt_2, txt_3;
private ProgressBar pr1;
private String[] str1;
private String[] str2;
private String[] str3;
private Integer[] int1;
private class OnItemClickListener implements OnClickListener{
private int mPosition;
OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View arg0) {
Log.v("TAG", "onItemClick at position" + mPosition);
}
}
public UvArrayAdapter(Context context, String[] s1, String[] s2, Integer[] i1) {
mContext = context;
str1 = s1;
str2 = s2;
int1 = i1;
linflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return str1.length;
}
#Override
public Object getItem(int arg0) {
return str1[arg0];
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = linflater.inflate(R.layout.uv_rowlayout, null);
}
convertView.setOnClickListener(new OnItemClickListener(position));
txt_1 = (TextView) convertView.findViewById(R.id.textView1);
pr1 = (ProgressBar) convertView.findViewById(R.id.progressBar1);
pr1.setProgress(int1[position]);
txt_1.setText(str1[position]);
txt_2 = (TextView) convertView.findViewById(R.id.textView2);
txt_2.setText(str2[position]+"mV");
Button btn = (Button) convertView.findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Log.v("onClickListener", "button - clicked at position " position);
do some changes in mentioned file and after that i need to update the list view with new data
}});
return convertView;
}
}
adapter.notifyDataSetChanged(); // to notify the adapter that your data has been updated
Note: If you get any errors with the above line, you could try the following code (where mListView is the name of my ListView object)
((BaseAdapter) mListView.getAdapter()).notifyDataSetChanged();
Another way would be to invalidate the List so that it is redrawn form the updated data set once again.
mListView=(ListView) findViewById(R.id.MyListView);
mListView.invalidate();
Use notifyDataSetChanged()
adapter = new UvArrayAdapter(this, strarray3, strarray2, intarray);
setListAdapter(adapter);
UvArrayAdapter.notifyDataSetChanged();
// To make the adapter aware of the changes

Categories

Resources