I am a beginner in android. I am creating an application where data will be shown through recyclerview, but I want that only some items should display in recyclerview.
However when the user clicks the "View All" button then only whole items should display. Can anyone tell me how can I do this?
viewtext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), AppviewActivity.class);
intent.putExtra("mylist","newmodel");
getContext().startActivity(intent);
}
});
DetailsActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_appview);
ArrayList<String> mylist = (ArrayList<String>) getIntent().getSerializableExtra("mylist");
}
NewModel class
public class NewModel {
Drawable sociallogo;
String socailtext;
String href;
public NewModel(Drawable sociallogo, String socailtext, String href){
this.sociallogo = sociallogo;
this.socailtext= socailtext;
this.href = href;
}
public Drawable getSociallogo(){
return sociallogo;
}
public String getSocailtext(){
return socailtext;
}
public String getHref(){
return href;
}
}
getItemCount method work for limitation.
If you bind with the below code then it shows limited data.
private final int limit = 10;
#Override
public int getItemCount() {
if(arrayList.size() > limit){
return limit;
}
}
When clicking on the "View All" button then redirect to the new activity and bind data in recyclerview adapter:
If you bind with the below code then it shows All data.
#Override
public int getItemCount() {
if(arrayList.size() > limit){
return ad_list.size();
}
}
Implement your model class like below code:
public class NewModel implements Serializable {
Now pass your data with below code:
viewtext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), AppviewActivity.class);
intent.putExtra("mylist", newmodel);
getContext().startActivity(intent);
}
});
Get your data in the new activity like:
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
ArrayList<NewModel> mylist = (ArrayList<NewModel>) bundle.getSerializable("mylist");
}
You can add a parameter in class Recycler View Adapter to set a limit data. That's the function to display data recycler view with limit data. You make 2 constructors in that class.
public class ArrayDataAdapter extends RecyclerView.Adapter<ArrayDataAdapter.ArrayDataViewHolder> {
private int limit = 0;
private ArrayData<ModelData> listData;
// Constructor 1: To display all data
public class ArrayDataAdapter(ArrayList<ModelData> listData) {
this.listData = listData;
this.limit = listData.size;
}
// Constructor 2: To display data with limit data
public class ArrayDataAdapter(ArrayList<ModelData> listData, int limit) {
this.listData = listData;
this.limit = limit;
}
}
So, when you click "View All", you call class Recycler View Adapter with constructor type 1. For viewing limited items , Call constructor type 2 ,then you set method getItemCount with "limit" variable.
Related
I Have a problem with my Adapter, First I want to display a different Array of data for every item in RecyclerView when clicking on it like this...
Item 1 "display" Array one
Item 2 "display" Array two
And so on... My data will be display in ViewPager on Activity, so I want to pass the data from the RecyclerView Adapter that have the items to the Activity that will display the data "The Activity has Viewpager that will get the data"
So that's what I tried before but it is just open the activity and not display the data.
First Her's My RecyclerView Adapter that has the items And the data
RecyclerViewItems.java
public class RecyclerViewQuran extends RecyclerView.Adapter<RecyclerViewQuran.ViewHolder> {
private ArrayList<QuranListDetail> item;
/* My data "Arrays" */
// first Array for First item
public static int[] mImageIds = new int[]
{
R.drawable.test_heart, R.drawable.test_home,
R.drawable.test_image, R.drawable.test_image, R.drawable.test_video,
};
// second Array for second item
public static int[] mImageIds2 = new int[]
{
R.drawable.nabawe_image_full, R.drawable.nabawe_image_full,
R.drawable.nabawe_image_full, R.drawable.nabawe_image_full, R.drawable.nabawe_image_full,
};
public RecyclerViewQuran(FragmentActivity activity, ArrayList<QuranListDetail> items) {
this.item = items;
}
#Override
public RecyclerViewQuran.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
return new ViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_quran, viewGroup, false));
}
#Override
public void onBindViewHolder(RecyclerViewQuran.ViewHolder holder, final int position) {
holder.itemTitle.setText(item.get(position).getSurahName());
holder.itemDetail.setText(item.get(position).getSurahDetail());
holder.itemNumber.setText(item.get(position).getSurahNumber());
// click listener to open new activity "shurah"
holder.itemClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
// Array 1
if (position == 0) {
int image = mImageIds[position];
Intent intent = new Intent(context, QuranSurahDisplay.class);
intent.putExtra("imageDisplay", image);
context.startActivity(intent);
}
// Array 2
else if (position == 1) {
int image = mImageIds2[position];
Intent intent = new Intent(context, QuranSurahDisplay.class);
intent.putExtra("imageDisplay", image);
context.startActivity(intent);}
}
});
}
#Override
public int getItemCount() {
return item.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView itemTitle;
private TextView itemDetail;
private TextView itemNumber;
private View itemClick;
public ViewHolder(View view) {
super(view);
itemTitle = view.findViewById(R.id.surah_name);
itemDetail = view.findViewById(R.id.surah_detail);
itemNumber = view.findViewById(R.id.surah_number);
itemClick = view.findViewById(R.id.item_click);
}
}
.
Second my ViewPagerAdapter.java
public class ViewPagerSurahAdapter extends PagerAdapter {
private Context mContext;
private int[] mImageIds;
public ViewPagerSurahAdapter(Context context, int[] mImageIds) {
mContext = context;
this.mImageIds = mImageIds;
}
#Override
public int getCount() {
return 0;
}
#Override
public boolean isViewFromObject(#NotNull View view, #NotNull Object object) {
return view == object;
}
#NotNull
#Override
public Object instantiateItem(ViewGroup container, int position) {
// PhotoView to zoom in the image "Instaded of ImageView"
PhotoView imageView = new PhotoView (mContext);
imageView.setImageResource(mImageIds[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
container.addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, #NotNull Object object) {
container.removeView((ImageView) object);
}
}
Third My Activity that will display the data in the ViewPager, My problem here I don't know how to pass the data in the ViewPager, Her's what I did.
public class QuranSurahDisplay extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_surah);
final Intent intent = getIntent();
if (intent.hasExtra("imageDisplay")) {
ViewPager viewPager = findViewById(R.id.view_pager_quran_fateha);
int[] url = intent.getIntArrayExtra("imageDisplay");
//ViewPager
ViewPagerSurahAdapter adapter = new ViewPagerSurahAdapter(this,url);
viewPager.setAdapter(adapter);
}
}
}
If you have any questions u can write it in the comments and I will be explaining to you.
I'm making an order taking cashier application. Using a recycler view to show the order queue. However, I'm having trouble passing ArrayList values between classes, and also, updating the recycler view. In this case, I won't have a massive recycler view so performance wouldn't be that much of an issue, but an optimized method of doing this would be greatly appreciated. I just don't know how to tackle this problem.
I've attempted to create a set method in the MainActivty class, I've also tried the intent put extra, but I don't believe I fully understand put extra quite yet.
MainActivity Class:
public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
public ArrayList<String> orderList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// set up the RecyclerView
recyclerView = findViewById(R.id.recyle_view_activity);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new MyRecyclerViewAdapter(this, orderList);
((MyRecyclerViewAdapter) mAdapter).setClickListener(this);
recyclerView.addItemDecoration(new DividerItemDecoration(this,
DividerItemDecoration.VERTICAL));
recyclerView.setAdapter(mAdapter);
}
//This is the set method I attempted:
public void setOrderAdd(ArrayList<String> data){
if (data != null){
mAdapter = new MyRecyclerViewAdapter(this,data); //Error refrences here
}
}
}
Other Class:
public class regularCoffee extends AppCompatActivity implements AdapterView.OnItemSelectedListener, Serializable {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_regular_coffee);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
addToOrder();
}
public void addToOrder(){
//Reg Addons:
final CheckBox leaveRoomReg = findViewById(R.id.leave_room_reg);
final CheckBox cinnamonReg = findViewById(R.id.cinnamon_reg);
final CheckBox chocolateSyrupReg = findViewById(R.id.chocolate_syrup_reg);
final CheckBox whiteChocolateSyrupReg = findViewById(R.id.white_chocolate_syrup_reg);
final CheckBox caramelReg = findViewById(R.id.caramelReg);
final CheckBox hazelnutReg = findViewById(R.id.hazel_nut_reg);
final CheckBox[] RegCoffeeAddOns = {leaveRoomReg,cinnamonReg,chocolateSyrupReg,whiteChocolateSyrupReg,caramelReg,hazelnutReg};
//Decaf Addons:
final Button leaveRoomDecaf = findViewById(R.id.leave_room_decaf);
final Button cinnamonDecaf = findViewById(R.id.cinnamon_decaf);
final Button chocolateSyrupDecaf = findViewById(R.id.chocolate_syrup_decaf);
final Button whiteChocolateDecaf = findViewById(R.id.white_chocolate_syrup_decaf);
final Button caramelDecaf = findViewById(R.id.caramel_decaf);
final Button hazelnutDecaf = findViewById(R.id.hazel_nut_decaf);
final Button[] DecafCoffeeAddOns = {leaveRoomDecaf,cinnamonDecaf,caramelDecaf,chocolateSyrupDecaf,whiteChocolateDecaf,hazelnutDecaf};
Button addToOrderButton = findViewById(R.id.addToOrderReg);
addToOrderButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity addToOrderArea = new MainActivity();
String forOrder;
ArrayList<String> tempArray = new ArrayList<>();
if (regCoffeeQuantity > 0){
forOrder = "Regular Coffee (x" + regCoffeeQuantity + ") \n ";
for (int i = 0; i < RegCoffeeAddOns.length; i++){
if (RegCoffeeAddOns[i].isChecked()){
forOrder = forOrder + "| " + RegCoffeeAddOns[i].getText().toString() + " ";
System.out.println(forOrder);
}
}
addToOrderArea.setOrderAdd(tempArray); //Error refrences here
}
}
});
}
RecyclerView Adapter:
package com.example.holygroundsapplication;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
private List<String> mData;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
MyRecyclerViewAdapter(Context context, List<String> data) {
this.mInflater = LayoutInflater.from(context); //Error refrences here.
this.mData = data;
}
// inflates the row layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextView in each row
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String animal = mData.get(position);
holder.myTextView.setText(animal);
}
// total number of rows
#Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;
ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.tvAnimalName);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
String getItem(int id) {
return mData.get(id);
}
// allows clicks events to be caught
void setClickListener(MainActivity itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
This is the error:
java.lang.IllegalStateException: System services not available to Activities before onCreate()
at android.app.Activity.getSystemService(Activity.java:5774)
at android.view.LayoutInflater.from(LayoutInflater.java:233)
at com.example.holygroundsapplication.MyRecyclerViewAdapter.<init>(MyRecyclerViewAdapter.java:21)
at com.example.holygroundsapplication.MainActivity.setOrderAdd(MainActivity.java:89)
at com.example.holygroundsapplication.regularCoffee$8.onClick(regularCoffee.java:262)
...
In your onClick function you have
MainActivity addToOrderArea = new MainActivity();
You shouldn't create activity instances by your self. This is something the Android system does. Because you create the activity by yourself it is not initialized (i.e. onCreate() is not called). The adapter which is created in the setOrderAdd() requires that the Activity is initialized and therefore throws an exception.
To prevent these problems you need to create your Activity with startActivity(). You can pass your data to the new Activity by adding extras to the starting Intent.
I think you logically need to replace
MainActivity addToOrderArea = new MainActivity();
with
MainActivity addToOrderArea = MainActivity.this;
But since you are not in the same class you need to pass the reference accordingly.
As long the MainActivity is still active and the other class is just a helper that wouldn't be a problem. Just add MainActivity to all the constructors... Somewhat like this:
OtherClass{
private MainClass addToOrderArea;
public OtherClass(MainClass addToOrderArea){
this.addToOrderArea=addToOrderArea;
}
// ...
abstract class MyOnclicklistener extends View.OnClickListene{
private MainClass addToOrderArea;
public MyOnclicklistener(MainClass addToOrderArea){
this.addToOrderArea=addToOrderArea;
}
}
// ...
addToOrderButton.setOnClickListener(new MyOnclicklistener(this.addToOrderArea) {
#Override
public void onClick(View v) {
String forOrder;
ArrayList<String> tempArray = new ArrayList<>();
if (regCoffeeQuantity > 0){
forOrder = "Regular Coffee (x" + regCoffeeQuantity + ") \n ";
for (int i = 0; i < RegCoffeeAddOns.length; i++){
if (RegCoffeeAddOns[i].isChecked()){
forOrder = forOrder + "| " + RegCoffeeAddOns[i].getText().toString() + " ";
System.out.println(forOrder);
}
}
addToOrderArea.setOrderAdd(tempArray); //Error refrences here
}
}
});
}
Attention: i guess this might still get you into another error, since you try to edit one activity from another...
Propably only store the variable between both activities, that seems okay. Updating the recycler view directly from another activity however might get you into some android view or security errors. I would say just pass the variable and update the recyclerview in the onResume function later. Something like this:
private ArrayList<String> _data;
public void setOrderAdd(ArrayList<String> data){
if (data != null){
// only store variable
_data = data;
}
}
#Override
protected void onResume() {
super.onResume();
// make update of your viewing components here
if(_data!=null){
mAdapter = new MyRecyclerViewAdapter(this,_data);
}
}
Now it should work i guess
I have ActivityCourses and ActivityNewCourse. ActivityCourses include a list (recyclerview) of custom courses that user make, and ActivityNewCourse obviously is the activity where the user makes those custom courses.
ActivityNewCourse contains primitive data (course name and number of holes)
those are the data, which I pass to ActivityCourses, and make new item there in its recyclerview (so the new items name is that course name which is passed from ActivityNewCourse).
The problem I have is that ActivityNewCourse also contains recyclerview, and that contains obviously unique items. I need to get all those items, from ActivityNewCourse, and get them STORED (not shown) in that same item, where I send primitive data in ActivityCourses.
I've tried to use interface in my NewCourseAdapter, to pass those items from ActivityNewCourse recyclerview, to my ActivityCourses item, but the problem is that I need all of them items, not just 1. and also that button "Save Course" which user clicks to obviously save all the data from ActivityNewCourse, is outside of the recyclerview, where those items are located.
HERE IS MY NEW COURSE ADAPTER
public class NewCourseAdapter extends RecyclerView.Adapter<NewCourseAdapter.NewCourseViewHolder> {
private ArrayList<NewCourseItem> mNewCourseList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onMinusClick(int position);
void onPlusClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public static class NewCourseViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView1, mTextView2;
public ImageView mImageView1, mImageView2;
public NewCourseViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
mTextView1 = itemView.findViewById(R.id.hole_number);
mTextView2 = itemView.findViewById(R.id.par_number);
mImageView1 = itemView.findViewById(R.id.item_minus_btn);
mImageView2 = itemView.findViewById(R.id.item_plus_btn);
mImageView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onMinusClick(position);
}
}
}
});
mImageView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onPlusClick(position);
}
}
}
});
}
}
public NewCourseAdapter(ArrayList<NewCourseItem> newCourseList) {
mNewCourseList = newCourseList;
}
#NonNull
#Override
public NewCourseViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.new_course_item, parent, false);
NewCourseViewHolder evh = new NewCourseViewHolder(v, mListener);
return evh;
}
#Override
public void onBindViewHolder(#NonNull NewCourseViewHolder holder, int position) {
NewCourseItem currentItem = mNewCourseList.get(position);
holder.mTextView1.setText(currentItem.getText1());
holder.mTextView2.setText(currentItem.getText2());
holder.mImageView1.setImageResource(currentItem.getImageMinus());
holder.mImageView2.setImageResource(currentItem.getImagePlus());
}
#Override
public int getItemCount() {
return mNewCourseList.size();
}
}
HERES HOW I PASS PRIMITIVE DATA FROM ACTIVITYNEWCOURSE TO ACTIVITYCOURSES
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
courseName = findViewById(R.id.course_name_input);
number = findViewById(R.id.number_of_holes_number);
String intentCourseName = courseName.getText().toString().trim();
String holeNumber = number.getText().toString().trim();
Intent intent = new Intent(ActivityNewCourse.this, ActivityCourses.class);
intent.putExtra("COURSENAME", intentCourseName);
intent.putExtra("HOLENUMBER", holeNumber);
startActivity(intent);
}
});
HERES HOW ACTIVITYCOURSES RESIVE THE DATA
public void addItem() {
if (getIntent().getStringExtra("COURSENAME") != null) {
mCourselist.add(new CoursesItem(getIntent().getStringExtra("COURSENAME"), "Holes:", getIntent().getStringExtra("HOLENUMBER"), R.drawable.ic_delete));
}
}
I'm not sure if this code helped or not...
Am I somehow be able to send the whole arraylist from ActivityNewCourse, when save button been clicked? I don't know, I'm kinda dead end and I have no clue what to do, so any suggestions on what to do in this situation would help...
Have you tried using intent.putStringArrayListExtra("ARRAYNAME", arrayName);
try putting your data in an ArrayList and send it like this:
Intent intent = new Intent(ActivityNewCourse.this, ActivityCourses.class);
intent.putStringArrayListExtra("ARRAYNAME", arrayName);
startActivity(intent);
and the retrieve it like this:
ArrayList<String> listOfData = getIntent().getStringArrayListExtra("ARRAYNAME");
Hope it helps.
updated
Using Serializable:
first extend NewCourseItem to Serializable then:
Bundle bundle = new Bundle();
bundle.putSerializable("KEYNAME", new NewCourseItem("str1", "str2", "imglink", "imglink"));
intent.putExtras(bundle);
startActivity(intent);
retrieve it like this:
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
NewCourseItem item = (NewCourseItem)bundle.getSerializable("KEYNAME");
I want to put an array of names(NomUser) in the first item of the RecyclerView. So I know I need to change the String of the constructor putting String[] but then how I can put the information when I do a new PendingTrajectPOJO?
I want the names of Joan and Ousmane on the first item
Like this
Here is where I put the information
listPendingTraject.add(new PendingTrajectPOJO(nomUser,"Surname","Origin","Destination",Data));
adapter = new AdapterPendingTraject(listPendingTraject);
recyclerPendingTraject.setAdapter(adapter);
This is my constructor
public PendingTrajectPOJO(String name, String surName, String origin, String destination, String date) {
Name = name;
SurName = surName;
Origin = origin;
Destination = destination;
Date = date;
}
My adapter
public class AdapterPendingTraject extends RecyclerView.Adapter<AdapterPendingTraject.ViewHolderPendingTraject>{
ArrayList<PendingTrajectPOJO> listPendingTraject;
public AdapterPendingTraject(ArrayList<PendingTrajectPOJO> listPendingTraject) {
this.listPendingTraject = listPendingTraject;
}
#Override
public ViewHolderPendingTraject onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.pending_traject_item,null,false);
return new ViewHolderPendingTraject(view);
}
#Override
public void onBindViewHolder(ViewHolderPendingTraject holder, int position) {
holder.Name.setText(listPendingTraject.get(position).getName());
holder.Surname.setText(listPendingTraject.get(position).getSurName());
holder.Origin.setText(listPendingTraject.get(position).getOrigin());
holder.Destination.setText(listPendingTraject.get(position).getDestination());
holder.Date.setText(listPendingTraject.get(position).getDate());
holder.itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, Journey.class);
//intent.putExtra("FileName", list.get(position));
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return listPendingTraject.size();
}
public class ViewHolderPendingTraject extends RecyclerView.ViewHolder {
TextView Name,Surname,Origin,Destination,Date;
public ViewHolderPendingTraject(View itemView) {
super(itemView);
Name=(TextView)itemView.findViewById(R.id.tvptName);
Surname=(TextView)itemView.findViewById(R.id.tvptSurName);
Origin=(TextView)itemView.findViewById(R.id.tvptOrigin);
Destination=(TextView)itemView.findViewById(R.id.tvptDestination);
Date=(TextView)itemView.findViewById(R.id.tvptDate);
}
}
}
What you want to do is create a public method in your adapter to pass in a new item. In this method, you need to notify the adapter that you have updated the items. I would recommend using the DiffUtil to find out which items have changed like this:
public void addNewItem(PendingTrajectPOJO p) {
ArrayList<PendingTrajectPOJO> old = new ArrayList<PendingTrajectPOJO>(listPendingTraject)
this.listPendingTraject = new ArrayList<PendingTrajectPOJO>()
this.listPendingTraject.add(p)
this.listPendingTraject.addAll(old)
DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new MyDiffCallback(old, this.listPendingTraject));
diffResult.dispatchUpdatesTo(this);
}
This way, when you add items, it will animate them and slide the old ones down (Since you mentioned you wanted the top item to be the new one)
Note: I have to test this later, I wrote this on the fly
In your adapter, create a custom method that accepts PendingTrajectPOJO as parameter, then update your listPendingTraject
Example:
public void addNewItem(PendingTrajectPOJO p) {
listPendingTraject.add(p);
notifyDataSetChanged();
}
I have two tabs in my app and there are listviews in this tabs.
I set List data to each listvew.
I want to delete form list, and from listview when I click [x] image.
Item deleted from list In my code , but I dont know how to update listview,I use notifyDataSetChanged() in my customadapter, but not update.
Activity for first tab:
public static List<Product> mCartList;
mCartList = AllProducts.getCartList();
listViewCatalog = (ListView) findViewById(R.id.my_order_list);
mProductAdapter = new CustomListAdapter(MyOrders.this, mCartList, "", true);
listViewCatalog.setAdapter(mProductAdapter);
my Custom List Adapter:
public class CustomListAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
private Context mContext;
private List<Product> mProductList;
private String mType;
private boolean mShowQuantity;
public CustomListAdapter(Context context, List<Product> list, String type, boolean showQuantity) {
layoutInflater = LayoutInflater.from(context);
mContext = context;
mProductList = list;
mShowQuantity = showQuantity;
mType = type;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public Object getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder item;
final int finalMPosition = position;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_row, null);
item = new ViewHolder();
item.imageView = (ImageView) convertView.findViewById(R.id.product_image);
item.name = (TextView) convertView.findViewById(R.id.name);
item.pid = (TextView) convertView.findViewById(R.id.pid);
item.price = (TextView) convertView.findViewById(R.id.price);
item.description = (TextView) convertView.findViewById(R.id.description);
item.removeProduct = (ImageView) convertView.findViewById(R.id.removeProduct);
item.addToCart = (TextView) convertView.findViewById(R.id.addtocard);
item.productQuantity = (TextView) convertView.findViewById(R.id.textViewQuantity);
convertView.setTag(item);
} else {
item = (ViewHolder) convertView.getTag();
}
final Product curProduct = mProductList.get(position);
item.imageView.setImageDrawable(curProduct.imageView);
item.name.setText(curProduct.name);
item.pid.setText(curProduct.pid);
int length = curProduct.description.length();
int start = 0, end = length;
if (length >= 40) {
start = 0;
end = 40;
}
String s = curProduct.description.substring(start, end);
item.description.setText(s + "...");
item.price.setText(curProduct.price + mContext.getString(R.string.currency));
if (mShowQuantity) {
item.addToCart.setVisibility(View.GONE);
// item.productQuantity.setText("Quantity: " + AllProducts.getProductQuantity(curProduct));
item.productQuantity.setVisibility(View.GONE);
} else {
item.productQuantity.setVisibility(View.GONE);
item.removeProduct.setVisibility(View.GONE);
}
item.removeProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder ab = new AlertDialog.Builder(mContext);
ab.setTitle("Delete ");
ab.setMessage("This product will be deleted from list.").setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
curProduct.selected = false;
AllProducts.removeProduct(curProduct);
notifyDataSetChanged();
notifyDataSetInvalidated();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
ab.create().show();
}
});
item.addToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent productDetailsIntent = new Intent(mContext, ProductDetail.class);
productDetailsIntent.putExtra(AllProducts.PRODUCT_INDEX, finalMPosition);
productDetailsIntent.putExtra("type", mType);
mContext.startActivity(productDetailsIntent);
}
});
return convertView;
}
public class ViewHolder {
TextView pid;
TextView addToCart;
TextView name;
TextView price;
TextView description;
ImageView imageView;
ImageView removeProduct;
TextView productQuantity;
}
}
You can introduce notifyDataSetChanged() in the list view or you can reset the setAdapter() which the new list values , but later one will be costly
You have 2 different List, try doing this:
Create a constructor without passing a List i mean:
CustomListAdapter(MyOrders.this, "", true);
Then in the CustomListAdapter create an List Local variable and instatiate it in the constructor:
private List<Product> mProductList;
public CustomListAdapter(Context context, String type, boolean showQuantity) {
layoutInflater = LayoutInflater.from(context);
mContext = context;
mProductList = new ArrayList<Product>();
mShowQuantity = showQuantity;
mType = type;
}
then create an Add or Delete method in the CustomListAdapter:
public void AddItem(Product product){
if(null != product){
mProductList.add(product);
}
}
Then an updateMethod too:
public void update(){
mProductList.notifyDataSetChanged();
}
if notifyDatasetChanged is not working try to use this
yourlist.invalidateviews();
You need to remove that particular item from arraylist by calling
AllProducts.remove(position);
notifyDatasetChanged();
write this methode in your adapter and use it to remove perticular Item from adapter.
public void remove(int position){
mProductList.remove(position);
notifyDatasetChanged();
}
I resolved my problem.
public static void setTab(int i){
if(i==0){
mTabHost.setCurrentTab(i+1);
mTabHost.setCurrentTab(i);
}
else{
mTabHost.setCurrentTab(i-1);
mTabHost.setCurrentTab(i);
}
}
and
#Override
public void onClick(DialogInterface dialog, int which) {
curProduct.selected = false;
AllProducts.removeProduct(curProduct);
MyTabActivity.setTab(0);
}
and for second listview:
MyTabActivity.setTab(1);
The only reason it is not working for you now, is because you have two different lists. You are removing from wrong list.
So first of all, do not delete from your list. Write a method in your adapter where you remove it from list you have stored in that Adapter, and then call notifyDatasetChanged in that method.
Working with tabs in android 2.x, I found a bug in the emulator: The tabs are not correctly refreshed or removed. Alternatives is to use support library v7 which as support for action bar tabs.
Use following code to update ListView.
In order to update ListView you must have to call notifyDataSetChanged(); menthod on Adapter. See Below code.
What you did.
notifyDataSetChanged();
notifyDataSetInvalidated();
What you have to do is,
yourAdapter.notifyDataSetChanged();
Or you may use following code to refresh your list.
private List<Object> mCarlistitem= new ArrayList<Object>();
public void refreshlist()
{
mCarlistitem.clear();
for(int i=0; i< mCartList.size(); i++)
{
Object object = new Object();
mCarlistitem.add(object);
}
mProductAdapter = new CustomListAdapter(MyOrders.this, mCartList, "",true);
listViewCatalog.setAdapter(mProductAdapter);
}