I am trying to finish activity from adapter class while clicking Recyclerview item
using the code
public void onBindViewHolder(#NonNull CountryCodeAdapter.CountryViewHolder holder, int position{
CountryModel countryMode = countryModels.get(position);
final String cCode = countryModel.getName();
holder.llcountryCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(),RegisterActivity.class);
i.putExtra("countryCode", cCode);
v.getContext().startActivity(i);
((AppCompatActivity)context).finish();
}
}
}
Also tried this but didn't work
((Activity)context).finish();
And i get this error:
cannot be cast to android.support.v7.app.AppCompatActivity
Make an interface for the adapter (inside the adapter class)like this :
public interface YourAdapterInteraction {
void onClickCountryCode();
}
Make your Activity implement your interface, like this:
public class YourActivity extends AppCompatActivity implements YourAdapter.YourAdapterInteraction
Inside YourActivity :
#Override
public void onClickCountryCode() {
Intent i = new
Intent(this,RegisterActivity.class);
i.putExtra("countryCode", cCode);
startActivity(i);
finish();
}
fetch Activity instance in Adapter constructor:
public class MyAdapter extends IAdapter<RecyclerView.ViewHolder,MyDS> {
private Activity activity;
public MyAdapter(Activity activity) {
this.activity = activity;
}
}
Do this :
public void onBindViewHolder(#NonNull
CountryCodeAdapter.CountryViewHolder holder, int position{
CountryModel countryModel = countryModels.get(position);
final String name = countryModel.getName();
holder.llcountryCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context,RegisterActivity.class);
i.putExtra("countryCode", cCode);
context.startActivity(i);
((Activity)context).finish();
}
}
});
instaed of :
Public void onBindViewHolder(#NonNull
CountryCodeAdapter.CountryViewHolder holder, int position{
CountryModel countryModel = countryModels.get(position);
final String name = countryModel.getName();
holder.llcountryCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new
Intent(v.getContext(),RegisterActivity.class);
i.putExtra("countryCode", cCode);
v.getContext().startActivity(i);
((AppCompatActivity)context).finish();
}
}
});
Create an interface callback inside your recyclerView, implement the method in your activity and call the method when an item is clicked.
// in your recyclerView
public interface RecyclerViewCallback {
void onItemClick(Item item)
}
// in your activity
#Override
void onItemClicked(Item item) {
this.finish();
}
Related
I would like to show car specification information when button click. Illustration enclosed. The data from array list. So far my code :
#Override
public void onBindViewHolder(#NonNull final CardViewHolder holder, int position) {
Car car = listCar.get(position);
Glide.with(holder.itemView.getContext())
.load(car.getFoto())
.apply(new RequestOptions().override(350, 550))
.into(holder.imgFoto);
holder.tvCarName.setText(car.getName());
holder.tvCarSpecs.setText(car.getSpecs());
holder.btnSpec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent detailCar= new Intent(v.getContext(), DetailActivity.class);
v.getContext().startActivity(detailPage);
}
});
}
DetailActivity code
public class DetailActivity extends AppCompatActivity {
private ArrayList<Car> listCar;
public DetailActivity(ArrayList<Car> list) {
this.listCar = list;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Intent intent = getIntent();
listElang = (ArrayList<Elang>) intent.getSerializableExtra("DATA");
}
}
First you have to make Car class as parcelable then you can pass car object to another activity
Intent detailCar= new Intent(v.getContext(), DetailActivity.class);
detailCar.putExtra("item",car)
v.getContext().startActivity(detailCar);
in DetailActivity just get the object
onCreate(Bundle savedInstanceState){
if(getIntent()!=null && getIntent.getParcelableExtra("item")!=null){
Car car=(Car)getIntent().getParcelable("item")
}
}
for beginner tutorial check this link
To show car specification information when button click, you can use intent to pass data from one activity to another activity .
First of all create a Serializable model class
Like this:
public class DemoModel implements Serializable{
String name;
String number;
public DemoModel(String name, String number){
this.name=name;
this.number=number;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public String getNumber(){
return number;
}
public void setNumber(String number){
this.number=number;
}
}
OnItemClick
ArrayListdatalist;
Intent intent=new Intent(this,FirstActivity.class);
intent.putExtra("car_detail",datalist.get(i));
startActivity(intent);
SecondActivity
DemoModel cardetail= (DemoModel) getIntent().getSerializableExtra("car_detail");
Log.e("check_response", ""+cardetail.getName()));
I have a problem in updating textview in activity class whenever recyclerview item is deleted from it. getActivity() is not available here. Thanx in advance guys.
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView delete_from_cart;
public ViewHolder(final View itemView) {
super(itemView);
delete_from_cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// here I want to change the textview
DatabaseHelper dh = new DatabaseHelper(context);
dh.deleteCartDetail(product_name.getText().toString());
delete(getLayoutPosition());
}
});
}
}
There can be different ways to implement this. Below are some.
Use interface callbacks, which will be passed in constructor of that Adapter class. (Best for your requirement.)
Pass activity reference in Adapter class, and call activity method to update textview. Like activity.updateText();
You can use EventBus. That can communicate in all over your app.
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
public interface MyCallback{
public void updateText(String text);
}
final private MyCallback callback;
public MyAdapter(MyCallback callback){
this.callback = callback;
}
... Some Other code
delete_from_cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Do other stuff
callback.updateText("some text");
}
});
}
public class MyActivity extends Activity implements MyCallback{
#Override
public void updateText(String someText){
myTextView.setText(someText);
}
}
Currently using an Intent with startActivity() to switch between 2 activities which share an abstract superclass. However, whenever startActivity() is called the custom object inherited from the abstract superclass gets reset. Is there anyway to maintain this object between startActivity() calls? Serializing the object with OnSavedInstanceState does not work because this object contains a LinkedList.
Every time a class is created regardless if it extends a superclass (in this case an Activity), the superclass is recreated. You would extend the Activity to share common methods/functions and imports....
You want to stay away from Serializable, so you want your object class to implement Parcelable:
public class CustomObject implements Parcelable {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.name);
}
public CustomObject() {
}
protected CustomObject(Parcel in) {
this.name = in.readString();
}
public static final Parcelable.Creator<CustomObject> CREATOR = new Parcelable.Creator<CustomObject>() {
#Override
public CustomObject createFromParcel(Parcel source) {
return new CustomObject(source);
}
#Override
public CustomObject[] newArray(int size) {
return new CustomObject[size];
}
};
}
In the first activity you want to pass the List to the second Activity using an Intent:
public class StartActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
findViewById(R.id.btn1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(StartActivity.this, ReceiveDataActivity.class);
i.putParcelableArrayListExtra("KEY", getCustomObjectList());
startActivity(i);
}
});
}
private ArrayList<CustomObject> getCustomObjectList() {
ArrayList<CustomObject> itemList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
CustomObject customObject = new CustomObject();
customObject.setName("Name " + i);
itemList.add(customObject);
}
return itemList;
}
}
Then to get the list you would use getIntent():
public class ReceiveDataActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receive_data);
List<CustomObject> itemList = getIntent().getParcelableArrayListExtra("KEY");
Toast.makeText(this, "List size = " + itemList.size(), Toast.LENGTH_SHORT).show();
}
}
I have a delete button in my adapter call and when i press the delete button i want to
1. remove the value from list and,
2. Update the size of the list in the main activity
and . Have tried using Interface where i referred here but it's not working and i am so confused.
So can any one provide me an best way
My Adapter Code:
#Override
public void onBindViewHolder(final AddLineItem_Adapter.ViewHolder holder, final int position) {
final AddLineItem_ListView addLineItem_listView = addLineItem_listViews.get(position);
holder.tv_OrderID.setText(addLineItem_listView.getItemID());
holder.tv_ProductName.setText(addLineItem_listView.getProductName());
holder.tv_Quantity.setText(addLineItem_listView.getQuantity());
holder.tv_UnitPrice.setText(addLineItem_listView.getUnitPrice());
holder.tv_TotalAmount.setText(addLineItem_listView.getTotalAmount());
holder.btn_Delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addLineItem_listViews.remove(position);
notifyDataSetChanged();
}
});
}
I want to update the addLineItem_listView size on the main activity in TextView.
Create the interface..
Pass it to the adapter..
Call interface function after deleting (providing the size of list)
Create interface
public interface ShowDeleted {
void showDeleted(int size);
}
Initialize the interface anonymously in the activity like this
ShowDeleted showDeleted = new ShowDeleted() {
#Override
public void showDeleted(int size) {
// show the changed list size or update UI
}
};
Pass the interface to the recyclerAdapter
YourAdapter youradpter = new YourAdpater(context,list,showDeleted );
Initialize the constructor of recyclerAdapter like this:-
public YourAdapter(Context context, YourList yourList, ShowDeleted
showDeleted)
{
}
holder.onClick do this
holder.btn_Delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addLineItem_listViews.remove(position);
notifyDataSetChanged();
this.showDeleted.showDeleted(addLineItem_listViews.size());
}
});
try to use view.setTag(position)
#Override
public void onBindViewHolder(final AddLineItem_Adapter.ViewHolder holder, final int position) {
final AddLineItem_ListView addLineItem_listView = addLineItem_listViews.get(position);
holder.tv_OrderID.setText(addLineItem_listView.getItemID());
holder.tv_ProductName.setText(addLineItem_listView.getProductName());
holder.tv_Quantity.setText(addLineItem_listView.getQuantity());
holder.tv_UnitPrice.setText(addLineItem_listView.getUnitPrice());
holder.tv_TotalAmount.setText(addLineItem_listView.getTotalAmount());
holder.btn_Delete.setTag(position)
holder.btn_Delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addLineItem_listViews.remove((Integer)v.getTag());
notifyDataSetChanged();
}
});
}
Good Luck!
use this function
public void removeAt(int position) {
list.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, list.size());
}
I need to create an interface for checkbox clickListener in an adapter so i can implement it in a fragment.
The code below is in myadapter, i need to move the logic inside the clickListener in a Fragment that uses the adapter
holder.ivLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isLike) {
like(postsData.getNews_id());
realmResults.get(position).setChecked(true);
holder.tvNewsCountLike.setText("" + (Integer.parseInt(holder.tvNewsCountLike.getText().toString()) + 1));
holder.ivLike.setChecked(true);
isLike = true;
} else {
unlike(postsData.getNews_id());
holder.tvNewsCountLike.setText("" + (Integer.parseInt(holder.tvNewsCountLike.getText().toString()) - 1));
holder.ivLike.setChecked(false);
isLike = false;
}
}
});
You can use interface callback here.
Ex:
public class MyAdapter {
private MyListener mListener;
public void setListener(MyListener listener){
mListene r= listener;
}
//where ever you want to call back
if(mListener != null){
mListener.onNotify();
}
public interface MyListener{
void onNotify();
}
}
Activity/ Fargment
public class MyActivity extends Activity implements MyAdapter.MyListener{
myAdapter.setListener(this);
#Override
public void onNotify(){
//do your logic here
}
}
In your adapter, declare something like this as your Listener interface:
public class FooAdapter extends RecyclerView.Adapter<ViewHolder> {
public interface Listener {
void onItemClicked(); // Customize to your needs
}
private final List<Listener> listeners = new ArrayList<>();
public void addListener(Listener l) {
listeners.add(l);
}
// In your viewholder:
holder.ivLike.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
for(Listener l : listeners) l.onItemClicked();
}
});
}
Now, in your fragment, implement the listener and listen to the adapter:
public class FooFragment extends Fragment implements FooAdapter.Listener {
// In onCreate()
...
FooAdapter adapter = new FooAdapter();
adapter.addListener(this);
...
#Override public void onItemClicked() {
// Add your logic here.
}
}