Interface callback after startactivity - android

I have fragment that contains recyclerview and products inside of it. When click row opens a new activity (SuggestionActivity). This activity also contains recyclerview inside of suggested products. When I click this products selecting or deselecting. Under the recyclerview I have button and when clicked this button it should be listen first recyclerview adapter and notifying data.
Ex:
ProductsFragment -> RecyclerAdapter -> Click Row -> Open Activity -> Click one or multiple rows and select -> Click Button -> Close activity and notify fragment adapter
My first recyclerview inside fragment
public class MyView extends RecyclerView.ViewHolder {
public MyView(View view) {
super(view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SuggestionActivity x = new SuggestionActivity();
x.setTab2AdapterListener(new SuggestionActivity.Tab2AdapterListener() {
#Override
public void interfaceClicked() {
Log.d("interfaceClicked", "interfaceClicked"); // This line doesn't work!
}
});
Intent i = new Intent(mContext, SuggestionActivity.class);
i.putExtra("first", String.valueOf(tag));
i.putExtra("second", String.valueOf(getAdapterPosition()));
mContext.startActivity(i);
}
});
}
}
My Interface defined on SuggestionActivity
private Tab2AdapterListener tab2AdapterListener;
public interface Tab2AdapterListener {
void interfaceClicked();
}
public void setTab2AdapterListener(Tab2AdapterListener tab2AdapterListener) {
this.tab2AdapterListener = tab2AdapterListener;
}
And Button inside SuggestionActivity
btnSendSuggestions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String suggested = "";
for (int i = 0; i < suggestedProductsList.size(); i++) {
if (suggestedProductsList.get(i).getIsSelected())
suggested += suggestedProductsList.get(i).getProductId() + ",";
}
if ( suggested.length() > 0 ) {
suggested = suggested.substring(0, suggested.length() - 1);
}
if (tab2AdapterListener != null)
tab2AdapterListener.interfaceClicked();
// tab2AdapterListener comes null
}
});

Related

Card View Click on card to move to next activity

I am working on a project in android and i just learn about card view class.
I made a card who generates a toast when user clicks on it.
But i also want my card to call another activity when user clicks on it.
I am posting part of my code below.
btnProceed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showToast("Proceed to the next step");
Intent intent = new Intent(MyLocationUsingLocationAPI.this, click_picture.class);
startActivity(intent);
}
});
I have made changes in my code as you said but when i click on proceed button my app crashes.What is wrong with code?
the main idea here is to define your actionClickListener
1. create a custom recycleView Adapter
public class AdapterCustomList extends RecyclerView.Adapter<RecyclerView.ViewHolder>
2. define onItemClickListener interface
public interface OnItemClickListener {
void onItemClick( whateverArgsYouWant );
}
3. make an attribute of the interface and define a setter for it
private OnItemClickListener mOnItemClickListener;
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
4. append a listener to each item while its created in the adapter class
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
...
OriginalViewHolder vItem = (OriginalViewHolder) holder;
vItem.baseCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick( whateverArgsYouWant );
}
}
});
}
this method will be called when items of recycle view is created (in case you use card view inside a recycle view)
5. use your onClickListener in the Activity you want
AdapterCustomList mAdapter = new AdapterCustomList (getActivity(), recyclerView,yourListItemsHere));
recyclerView.setAdapter(mAdapter);
// on item list clicked
mAdapter.setOnItemClickListener(new AdapterPostList.OnItemClickListener() {
#Override
public void onItemClick( whateverArgsYouWant ) {
...
statements
...
}
});

After clicking a button view is updating on both items of recyclerview

I have a RecyclerView with post cards. So there is a like button in every post card. When I tap on a like button. Sometimes it works fine and updates on current item. But after some scroll when I tap on like button it updates on another item simultaneously.
It doesn't send that data to server. But, only the view is updated. Then when I scroll up and down again. The data goes back to normal.
Problem is in the following onClick method:-
FirebaseDatabase.getInstance().getReference().child("topics").child("likes").child(data.getId()).child(username).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child("like").exists()){
holder.like.setImageResource(R.drawable.ic_favorite_red_500_36dp);
holder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseDatabase.getInstance().getReference().child("topics").child("likes").child(data.getId()).child(username).child("like").removeValue();
}
});
}else if(dataSnapshot.child("dislike").exists()) {
holder.like.setImageResource(R.drawable.brokenheart);
holder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseDatabase.getInstance().getReference().child("topics").child("likes").child(data.getId()).child(username).child("dislike").removeValue();
}
});
}else{
holder.like.setImageResource(R.drawable.ic_favorite_border_red_500_36dp);
holder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseDatabase.getInstance().getReference().child("topics").child("likes").child(data.getId()).child(username).child("dislike").removeValue();
FirebaseDatabase.getInstance().getReference().child("topics").child("likes").child(data.getId()).child(username).child("like").setValue(true);
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
holder.like.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
FirebaseDatabase.getInstance().getReference().child("topics").child("likes").child(data.getId()).child(username).child("like").removeValue();
FirebaseDatabase.getInstance().getReference().child("topics").child("likes").child(data.getId()).child(username).child("dislike").setValue(true);
return true;
}
});
Full Adapter class https://pastebin.com/UnFGahWT
Try the following:-
Set Your on click listeners in the public ViewHolder(View itemView) method and make Your ViewHolder class implement the View.OnClickListener.
In Adapter add:
public Topic getItem(int position) {
return topics.get(position);
}
In ViewHolder's onClick method add:
int position = getAdapterPosition();
if (position == RecyclerView.NO_POSITION) return;
item = getItem(position);
Thus You will get the exact object You need to change or do something with it.

Selected Item has to be added to cart in android

Already I have some static data in expanded list view and from that list if any customer click on that multiple items they has to be selected and it has to be added into cart.So for that please give me some suggestions and if u have any implemented code please post here.
Thanks in advance.
Assume there is two button for add and remove item on cart screen so both have click event on adapter class below is just sample example
holder.imgAddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCartDetail mCartDetail;
if (Utility.mCartList.containsKey(mcategoryProductDetail.productdetails.get(0).psid)) {
mCartDetail = Utility.mCartList.get(mcategoryProductDetail.productdetails.get(0).psid);
int finalMmaxBuy = 0;
if (!mCartDetail.categoryProductDetail.max_buy_qty.equalsIgnoreCase(" ")) {
finalMmaxBuy = Integer.parseInt(mCartDetail.categoryProductDetail.max_buy_qty);
}
if (mCartDetail.addQuantity < finalMmaxBuy) {
mCartDetail.addQuantity++;
}
} else {
mCartDetail = new mCartDetail();
mCartDetail.categoryProductDetail = mcategoryProductDetail.productdetails.get(0);
mCartDetail.addQuantity = 1;
Utility.mCartList.put(mcategoryProductDetail.productdetails.get(0).psid, mCartDetail);
}
mCartDetail.totalprice = Float.parseFloat(mCartDetail.categoryProductDetail.our_price) * mCartDetail.addQuantity;
holder1.tvProductCounter.setText(String.valueOf(mCartDetail.addQuantity));
}
});
holder.imgRemoveItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Utility.mCartList.containsKey(mcategoryProductDetail.productdetails.get(0).psid)) {
mCartDetail mCartDetail = Utility.mCartList.get(mcategoryProductDetail.productdetails.get(0).psid);
mCartDetail.addQuantity--;
mCartDetail.totalprice = Float.parseFloat(mCartDetail.categoryProductDetail.our_price) * mCartDetail.addQuantity;
holder1.tvProductCounter.setText(String.valueOf(mCartDetail.addQuantity));
if (mCartDetail.addQuantity == 0) {
Utility.mCartList.remove(mCartDetail.categoryProductDetail.psid);
notifyDataSetChanged();
}
}
});
and below is my model class and hashmap for data storing and send to server
public static HashMap<String, CartDetail> mCartList;
public CartDetail mCartDetail;
Hope this concept will help you to implement in your scenario

How to move the first position of image to second position in listView on Button click in android

How to move the first position of image to second position in ListView on Button click,so that last position of image will comes to first position.
my tried codes below;
public class MainActivity extends AppCompatActivity {
private int[] images = {R.drawable.img1,R.drawable.img2,R.drawable.img3,R.drawable.img4,R.drawable.img5};
ArrayList<ImageModel> imageModels;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
imageModels = new ArrayList<ImageModel> ();
for (int i = 0; i < images.length; i++) {
ImageModel imgMode = new ImageModel ();
imgMode.setImageId (images[i]);
imageModels.add (imgMode);
Log.d ("chk",""+images[i]);
}
ListView lstView = (ListView)findViewById (R.id.lst_view);
lstView.setAdapter (new BaseAdapterr(MainActivity.this,imageModels));
Button btnClick = (Button)findViewById (R.id.btn_click);
btnClick.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick (View v) {
for (int i=0 ;i < imageModels.size ();i++){
}
}
});
}}
Try using getting the object index and then use setIndex or sth like that for changing index.
Tarik.
this is your btnClick Listener , try it :
Button btnClick = (Button)findViewById (R.id.btn_click);
btnClick.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick (View v) {
...
ImageView firstImage= listView.getChiledAt(0);// get the firstimage
ImageView secnodImage= listView.getChiledAt(1);// get the second image
listView.addView(firstImage,2);// we added the first image to the second index
listView.addView(secondImage,1);// we added the second image to the first index
myAdapter.notifyDataSetChanged();// to refresh the view
...
}
});
For a direct scroll:
lstView.setSelection(0);
For a smooth scroll:
lstView.smoothScrollToPosition(0);
so your code should be following
btnClick.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick (View v) {
lstView.clearFocus();
lstView.post(new Runnable() {
#Override
public void run() {
//int index=0; set your position
lstView.setSelection(index);
}
});
}
});

Custom Listener on Button click in ListView Item

I have created a Custom Listener interface for Button click in Adapter class, i followed this tutorial: http://www.c-sharpcorner.com/UploadFile/9e8439/create-custom-listener-on-button-in-listitem-listview-in-a/
Adapter:
holder.btnQtyIncrease.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onButtonClickListner(position);
}
cart = cartArrayList.get(position);
holder.textViewQuantity.setTag(cart);
if(cart.getQuantity() == 9) {
Toast.makeText(context, "Already reached", Toast.LENGTH_LONG).show();
return ;
}
else
{
cart.setQuantity(cart.getQuantity() + 1);
holder.textViewQuantity.setText(String.valueOf(cart.getQuantity()));
totalPrice = cart.getQuantity() * cart.getPrice();
CartArrayList.cartArraylist.get(position).setTotal(totalPrice);
holder.textViewTotal.setText(cart.getTotal());
}
}
});
.....
return convertView;
}
And I have implemented Listener in Activity like this:
public class CartActivity extends Activity implements customButtonListener {
......
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("CartActivity-onCreate", "onCreate");
setContentView(R.layout.activity_cart);
......
}
#Override
public void onResume()
{
super.onResume();
Log.d("CartActivity-onResume", "onResume");
}
#Override
public void onButtonClickListner(int position) {
totalPrice = CartArrayList.cartArraylist.get(position).getQuantity() * CartArrayList.cartArraylist.get(position).getPrice();
CartArrayList.cartArraylist.get(position).setTotal(totalPrice);
subTotal = subTotal + totalPrice;
}
}
As you can see inside for loop i am setting and getting total of each and every list item, and then calculating subTotal of ArrayList items...
But whenever i do tap on btnQtyIncrease it makes change in total of list item price, but it would not effect on subTotal amount
You should change you logic in some way that it calculates the subTotal in adapter only and then just pass the final value to interface which will simply set it in then textview
So your code should look like:
holder.btnQtyIncrease.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cart = cartArrayList.get(position);
holder.textViewQuantity.setTag(cart);
if(cart.getQuantity() == 9) {
Toast.makeText(context, "Already reached", Toast.LENGTH_LONG).show();
return ;
}
else
{
cart.setQuantity(cart.getQuantity() + 1);
holder.textViewQuantity.setText(String.valueOf(cart.getQuantity()));
totalPrice = cart.getQuantity() * cart.getPrice();
CartArrayList.cartArraylist.get(position).setTotal(totalPrice);
holder.textViewTotal.setText(cart.getTotal());
}
}
// calculate total here
if (customListner != null) {
customListner.onButtonClickListner(getTotalValue());
}
});
Define a method getTotalValue in adapter which will iterate through the array and find the subTotal value.
And then simply set it in the textView
#Override
public void onButtonClickListner(float subTotal ) {
txtView.setText(String.valueOf(subTotal));
}
Accordingly, change the interface signature as :
public void onButtonClickListner(float total);
How to update value in Activity when do change in Adapter class
To update data in Activity on btnQtyIncrease Button click. create custom event listener using interface which will trigger in Activity when any change made in Quantity.
See following example for creating custom Listener :
How to create our own Listener interface in android?

Categories

Resources