Adapter overwrite the values of 5th row and so on - android

Why Adapter overwrites the value of seekbar, all values are set normally but when 5 item value set it will replace the next item value( firstly value is set normal on the item row but after few millisecond values replace with next item).
1:-want to set all values on its normal positions.
2:-reason why value replaces after few milliseconds.
extends RecyclerView.Adapter<GuaranteeAdapter.MyViewHolder> {
private RangeSeekBar mRangeSeekBarPrice;
ArrayList<int[]> listOfGuarantees1 = new ArrayList<int[]>();
int[] values;
int tripsCompleted;
public static int[] diversvalues;
private List<ModelWeeklyGuarantee> GauranteeList;
Context context;
public ArrayList<Integer> weklyGuarantees = new ArrayList<Integer>();
JSONArray jsonArray;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView year, serverMessage, completeRides, incompleteRides;
public LinearLayout MainLL;
public MyViewHolder(View view) {
super(view);
year = (TextView) view.findViewById(R.id.year);
serverMessage = (TextView) view.findViewById(R.id.messagefromserver);
completeRides = (TextView) view.findViewById(R.id.txt_complete_ride);
incompleteRides = (TextView) view.findViewById(R.id.txt_left_rides);
mRangeSeekBarPrice = (RangeSeekBar) view.findViewById(R.id.range_seek_bar_price);
MainLL = (LinearLayout) view.findViewById(R.id.parent_layout);
//These txt view values are placed on its normal positions
}
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
public GuaranteeAdapter(List<ModelWeeklyGuarantee> GauranteeList, Context context) {
this.GauranteeList = GauranteeList;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.guarantee_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
ModelWeeklyGuarantee ModelGuarantee = GauranteeList.get(position);
this.tripsCompleted = ModelGuarantee.tripsCompleted;
holder.year.setText(ModelGuarantee.getDate());
holder.completeRides.setText(String.valueOf(ModelGuarantee.getTripsCompleted()));
holder.incompleteRides.setText(String.valueOf(String.valueOf(ModelGuarantee.getTripsLeft())));
holder.serverMessage.setText(String.valueOf(ModelGuarantee.getWeeklyDataList()));
jsonArray = ModelGuarantee.getWeeklyDataList();
Log.d("getWeeklyDataList", "" + jsonArray);
weklyGuarantees = new ArrayList<Integer>();
weklyGuarantees.clear();
for (int i = 0, count = jsonArray.length(); i < count; i++) {
try {
weklyGuarantees.add(i, Integer.valueOf(String.valueOf(jsonArray.get(i).toString())));
} catch (JSONException e) {
e.printStackTrace();
}
}
if (weklyGuarantees.size() > 0) {
diversvalues = null;
diversvalues = new int[Collections.max(weklyGuarantees) + 1];
Log.d("weklyGuaranteesss", "" + weklyGuarantees);
for (int i = 0; i <= Collections.max(weklyGuarantees); i++) {
try {
diversvalues[i] = i;
//i++;
Log.d("ivalue", "" + i);
} catch (Exception e) {
e.printStackTrace();
}
}
Log.d("devider", "" + diversvalues.toString());
mRangeSeekBarPrice.setAdapter(new DemoRangeAdapter11(1,Collections.max(weklyGuarantees) + 1,diversvalues,position));
}
Log.d("posa ", " " + position);
mRangeSeekBarPrice.setSelectedMinValue(ModelGuarantee.tripsCompleted + 1);
mRangeSeekBarPrice.setDailyarrayListValues(weklyGuarantees);
mRangeSeekBarPrice.setbothtripscompleted(tripsCompleted);
Log.d("callednow", " va " + weklyGuarantees);
mRangeSeekBarPrice.setbothtripscompleted(tripsCompleted);
mRangeSeekBarPrice.setNotifyWhileDragging(true);
}
#Override
public int getItemCount() {
return GauranteeList.size();
}

Related

Custom Adapter not Changing Layout According to Condition

I am working on a chat app and I am very new to using ListViews and ArrayAdapters, as well as Custom Adapters. I am having a problem that causes all my items in my list to be of one layout, even they are supposed to change according to a booleans(true would be an outgoing chat bubble, and false would be an incoming chat bubble).
Here is my code for the retreival of the chat(It isn't the whole file, just a snippet):
Variable declarations:
final ArrayList<chatBubble> objects = new ArrayList<>();
final CustomAdapter customAdapter = new CustomAdapter(this, objects);
listView.setAdapter(customAdapter);
Code to get messages and add to list:
mDatabase.child("chat").child("publicDump").child("dumpedMessages").child("message" + i).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String message = dataSnapshot.getValue(String.class);
if (message != null) {
final String extract = message.substring(message.lastIndexOf("<") + 1, message.indexOf(">"));
mDatabase.child("users").child("c").child("emailToUsername").child(mAuth.getCurrentUser().getEmail().replace(".", ",")).child("username").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String username = dataSnapshot.getValue(String.class);
if (username != null) {
if (username.equals(extract)) {
Log.i("Extract", extract);
int semicnt = 0;
int num = 0;
//Log.i("Loop", "Yes");
for (int i = 0; i < message.length(); i++) {
//Log.i("Loop", "y");
if (String.valueOf(message.charAt(i)).equals(":")) {
semicnt++;
//Log.i("cnt", String.valueOf(semicnt));
if (semicnt == 3) {
num = i;
i = message.length() - 1;
String time = message.substring(0, (Math.min(message.length(), num)));
String finalM = message.replace(time + ": ", "").replace("<" + extract + "> ", "");
chatBubble chat = new chatBubble(finalM, "From: " + extract + " At: " + time, true);
objects.add(chat);
}
}
}
} else {
int semicnt = 0;
int num = 0;
// Log.i("Loop", "Yes");
for (int i = 0; i < message.length(); i++) {
//Log.i("Loop", "y");
if (String.valueOf(message.charAt(i)).equals(":")) {
semicnt++;
//Log.i("cnt", String.valueOf(semicnt));
if (semicnt == 3) {
num = i;
i = message.length() - 1;
String time = message.substring(0, (Math.min(message.length(), num)));
String finalM = message.replace(time + ": ", "").replace("<" + extract + "> ", "");
chatBubble chat = new chatBubble(finalM, "From: " + extract + " At: " + time, false);
objects.add(chat);
}
}
}
}
customAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here is my code for my chatBubble:
package com.tejasmehta.codeychat;
public class chatBubble {
private String msg;
private String date;
private boolean myMessage;
public chatBubble(String msg, String date, boolean myMessage) {
this.msg = msg;
this.date = date;
this.myMessage = myMessage;
}
public String Msg() {
return msg;
}
public String Date() {
return date;
}
public boolean myMessage() {
return myMessage;
}
}
And here is my code for my customAdapter(which shows that if the boolean, myMessage, is true, it will load a different layout, and a different one for false):
public class CustomAdapter extends BaseAdapter {
private LayoutInflater inflater;
private ArrayList<chatBubble> objects;
private class ViewHolder {
TextView msg;
TextView date;
}
public CustomAdapter(Context context, ArrayList<chatBubble> objects) {
inflater = LayoutInflater.from(context);
this.objects = objects;
}
public int getCount() {
return objects.size();
}
public chatBubble getItem(int position) {
return objects.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int layoutResource; // determined by view type
chatBubble ChatBubble = getItem(position);
if (ChatBubble.myMessage()) {
layoutResource = R.layout.right_bubble;
} else {
layoutResource = R.layout.left_bubble;
}
if(convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(layoutResource, null);
holder.msg = convertView.findViewById(R.id.txt_msg);
holder.date = convertView.findViewById(R.id.date);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.msg.setText(objects.get(position).Msg());
holder.date.setText(objects.get(position).Date());
return convertView;
}
}
Thank You for all of your help!
the problem is your getview
The view is being recycled so convertview already has a layout. so its not being reinflated to the correct layout.
you need to use getViewType() and getViewTypeCount() to tell the listview you want to use different layouts
http://android.amberfog.com/?p=296
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
return getItem(position).myMessage()?0:1;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int layoutResource; // determined by view type
chatBubble ChatBubble = getItem(position);
if (ChatBubble.myMessage()) {
layoutResource = R.layout.right_bubble;
} else {
layoutResource = R.layout.left_bubble;
}
if(convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(layoutResource, null);
holder.msg = convertView.findViewById(R.id.txt_msg);
holder.date = convertView.findViewById(R.id.date);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.msg.setText(objects.get(position).Msg());
holder.date.setText(objects.get(position).Date());
return convertView;
}

i would like to update my cart, for this i have used spinner in RecyclerView after scrolling down cart count is same as initial

I'm using RecyclerView to display a list of marks, and each mark of the value is shown as a CardView.
But some contents of the cards are lost after the scrolling the RecyclerView down and scrolling back, as shown in the two screenshots below.
The contents of the red rectangle are lost after scrolling.
public class Shop_Products_adapter extends
RecyclerView.Adapter<Shop_Products_adapter.MyViewHolder> {
public static HashMap<String, String> cartHasmap = new HashMap<String, String>();
private List<Shop_Products> ServiceModels = new ArrayList<>();
private Context mContext;
private int count = 0;
public Shop_Products_adapter(List<Shop_Products> ServiceModels, Context mContext) {
this.ServiceModels = ServiceModels;
Log.e("Shop_Products_adapter", ServiceModels.toString());
this.mContext = mContext;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.shop_products, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
final Shop_Products serviceModel = ServiceModels.get(position);
Log.e("onBindViewHolder", serviceModel.getName1());
holder.name1.setText(serviceModel.getName1());
holder.cost1.setText("\u20B9 " + serviceModel.getCost());
holder.kgs1.setText(serviceModel.getKgs() + " kgs");
String urlOfImage = serviceModel.getImage1();
Picasso.with(mContext).load(urlOfImage).into(holder.image1);
final List quantity = new ArrayList<Integer>();
for (int i = 0; i <= 10; i++) {
quantity.add(Integer.toString(i));
}
ArrayAdapter<Integer> spinnerArrayAdapter = new ArrayAdapter<Integer>(mContext, android.R.layout.simple_spinner_item, quantity);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.quatity_spinner.setAdapter(spinnerArrayAdapter);
//holder.quatity_spinner.setSelection(position,true);
holder.quatity_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (holder.quatity_spinner.getSelectedItem().equals("0")) {
cartHasmap.put(serviceModel.getId(), serviceModel.getQty());
cartHasmap.values().removeAll(Collections.singleton(serviceModel.getQty()));
Log.e("cartHasmap Remove Valeu", "onItemSelected() returned: " + cartHasmap);
} else {
count = count + 1;
serviceModel.setCount(String.valueOf(count));
String qty = holder.quatity_spinner.getSelectedItem().toString();
serviceModel.setQty(qty);
SharedPreferences pref = mContext.getSharedPreferences("cart_data", 0);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("count", count);
editor.putString("qty", qty);
editor.putString("product_id", serviceModel.getId());
editor.commit();
cartHasmap.put(serviceModel.getId(), serviceModel.getQty());
Log.e("cartHasmap", "onItemSelected() returned: " + cartHasmap);
Log.e("*******", "onitem get id " + serviceModel.getId());
JSONObject object = new JSONObject();
try {
object.put("", serviceModel.getQty());
object.put("", serviceModel.getId());
Log.i("+++++++++", "onItemSelected: " + object);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public int getItemCount() {
return ServiceModels.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public void setFilter(ArrayList<Shop_Products> filter) {
ServiceModels = new ArrayList<>();
ServiceModels.addAll(filter);
notifyDataSetChanged();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name1;
public TextView cost1;
public TextView kgs1;
public ImageView image1;
public Spinner quatity_spinner;
public MyViewHolder(View view) {
super(view);
name1 = (TextView) view.findViewById(R.id.name1);
cost1 = (TextView) view.findViewById(R.id.cost);
kgs1 = (TextView) view.findViewById(R.id.kgs);
image1 = (ImageView) view.findViewById(R.id.img1);
quatity_spinner = (Spinner) view.findViewById(R.id.quatity_spinner);
}
}
}

How to merged same named header in expandable RecyclerView

I have a expandable recycler view as like this
I want to merged same named header(Such as "Nov 17,2016" ). and add their child at one place.
and icon position must be remain same. How to do this?
Here is my json response:
{"Table":
[{"filedate":"Oct 25, 2016","clientid":4},
{"filedate":"Nov 17, 2016","clientid":4},
{"filedate":"Nov 16, 2016","clientid":4}],
"Table1":
[{"filedate":"Oct 25, 2016","file1":"12.txt","category":"Category : Bank Statement"},
{"filedate":"Nov 16, 2016","file1":"Readme.docx","category":"Category : Bank Statement"},
{"filedate":"Nov 17, 2016","file1":"hts-log.txt","category":"Category : Bills"},
{"filedate":"Nov 17, 2016","file1":"cookies.txt","category":"Category : Others",},
{"filedate":"Nov 17, 2016","file1":"readme.txt","category":"Category : Invoice",}]}
Here is my code for getting json response:
private void prepareListData() {
// Volley's json array request object
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Log.d(TAG, response.toString());
// hidePDialog();
JSONObject object = null;
try {
object = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray jsonarray = null;
JSONArray jsonarray1 = null;
try {
jsonarray = object.getJSONArray("Table1");
jsonarray1 = object.getJSONArray("Table1");
} catch (JSONException e) {
e.printStackTrace();
}
// JSONArray jsonarray1 = object.getJSONArray("Table2");
for (int i = 0; i < jsonarray.length(); i++) {
try {
JSONObject obj = jsonarray.getJSONObject(i);
// Movie movie = new Movie();
// movie.setFiledate(obj.getString("filedate"));
String str = obj.optString("filedate").trim();
Log.d("test", str);
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.HEADER, str));
// Toast.makeText(getApplicationContext(), lth, Toast.LENGTH_LONG).show();
for (int j = 0; j < jsonarray1.length(); j++) {
try {
JSONObject obj1 = jsonarray1.getJSONObject(j);
String str1 = obj1.optString("filedate").trim();
String str2 = obj1.optString("file1").trim();
String str3 = obj1.optString("filename").trim();
String str4 = obj1.optString("category").trim();
Toast.makeText(getApplicationContext(), "server data respone", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "test"+str1, Toast.LENGTH_LONG).show();
if (str == str1) {
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, str4));
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, str2));
}
Toast.makeText(getApplicationContext(), str1, Toast.LENGTH_LONG).show();
//if condition
} catch (JSONException e) {
// Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
// adding movie to movies array
} catch (JSONException e) {
Log.e("gdshfsjkg", "JSON Parsing error: " + e.getMessage());
}
} Log.d("test", String.valueOf(data));
// notifying list adapter about data changes
// so that it renders the list view with updated data
// adapterheader.notifyDataSetChanged();
recyclerview.setAdapter(new ExpandableListAdapter(data));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// VolleyLog.d(TAG, "Error: " + error.getMessage());
// hidePDialog();
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(CLIENT, "4");
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(stringRequest);
}
Adapeter class
public class ExpandableListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int HEADER = 0;
public static final int CHILD = 1;
private List<Item> data;
public ExpandableListAdapter(List<Item> data) {
this.data = data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int type) {
View view = null;
Context context = parent.getContext();
float dp = context.getResources().getDisplayMetrics().density;
int subItemPaddingLeft = (int) (18 * dp);
int subItemPaddingTopAndBottom = (int) (5 * dp);
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
switch (type) {
case HEADER:
view = inflater.inflate(R.layout.list_header, parent, false);
ListHeaderViewHolder header = new ListHeaderViewHolder(view);
return header;
case CHILD:
view = inflater.inflate(R.layout.listchild, parent, false);
ListChildViewHolder child = new ListChildViewHolder(view);
return child;
}
return null;
}
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final Item item = data.get(position);
switch (item.type) {
case HEADER:
final ListHeaderViewHolder itemController = (ListHeaderViewHolder) holder;
itemController.refferalItem = item;
itemController.header_title.setText(item.text);
if (item.invisibleChildren == null) {
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_minus);
} else {
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_plus);
}
itemController.btn_expand_toggle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (item.invisibleChildren == null) {
item.invisibleChildren = new ArrayList<Item>();
int count = 0;
int pos = data.indexOf(itemController.refferalItem);
while (data.size() > pos + 1 && data.get(pos + 1).type == CHILD) {
item.invisibleChildren.add(data.remove(pos + 1));
count++;
}
notifyItemRangeRemoved(pos + 1, count);
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_plus);
} else {
int pos = data.indexOf(itemController.refferalItem);
int index = pos + 1;
for (Item i : item.invisibleChildren) {
data.add(index, i);
index++;
}
notifyItemRangeInserted(pos + 1, index - pos - 1);
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_minus);
item.invisibleChildren = null;
}
}
});
break;
case CHILD:
boolean showIcon = position > 1 && getItemViewType(position) == CHILD && getItemViewType(position - 2) == HEADER;
final ListChildViewHolder itemController1 = (ListChildViewHolder) holder;
itemController1.refferalItem = item;
itemController1.header_title1.setText(item.text);
itemController1.btn_expand_toggle1.setVisibility((showIcon) ? View.VISIBLE : View.GONE);
break;
}
}
#Override
public int getItemViewType(int position) {
return data.get(position).type;
}
#Override
public int getItemCount() {
return data.size();
}
private static class ListHeaderViewHolder extends RecyclerView.ViewHolder {
public TextView header_title;
public ImageView btn_expand_toggle;
public Item refferalItem;
public ListHeaderViewHolder(View itemView) {
super(itemView);
header_title = (TextView) itemView.findViewById(R.id.header_title);
btn_expand_toggle = (ImageView) itemView.findViewById(R.id.btn_expand_toggle);
}
}
private static class ListChildViewHolder extends RecyclerView.ViewHolder {
public TextView header_title1;
public ImageView btn_expand_toggle1;
public Item refferalItem;
public ListChildViewHolder(View itemView) {
super(itemView);
header_title1 = (TextView) itemView.findViewById(R.id.header_title1);
btn_expand_toggle1 = (ImageView) itemView.findViewById(R.id.btn_expand_toggle1);
}
}
public static class Item {
public int type;
public String text;
public List<Item> invisibleChildren;
public Item() {
}
public Item(int type, String text) {
this.type = type;
this.text = text;
}
}
}
You can use the library SectionedRecyclerViewAdapter to group your Item objects under the same header.
First create a Section class:
class MySection extends StatelessSection {
Item item;
public MySection(Item item) {
// call constructor with layout resources for this Section header, footer and items
super(R.layout.section_header, R.layout.section_item);
this.item = item;
}
#Override
public int getContentItemsTotal() {
return item.invisibleChildren.size(); // number of items of this section, TODO: check if invisibleChildren is null and return 0
}
#Override
public RecyclerView.ViewHolder getItemViewHolder(View view) {
// return a custom instance of ViewHolder for the items of this section
return new MyItemViewHolder(view);
}
#Override
public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
MyItemViewHolder itemHolder = (MyItemViewHolder) holder;
// bind your view here
itemHolder.tvItem.setText(item.invisibleChildren.get(position).text);
}
#Override
public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
return new SimpleHeaderViewHolder(view);
}
#Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
MyHeaderViewHolder headerHolder = (MyHeaderViewHolder) holder;
// bind your header view here
headerHolder.tvItem.setText(item.text);
}
}
Then you set up the RecyclerView with your Sections:
// Create an instance of SectionedRecyclerViewAdapter
SectionedRecyclerViewAdapter sectionAdapter = new SectionedRecyclerViewAdapter();
// Add your Sections to the adapter
sectionAdapter.addSection(new MySection(data.get(0));
sectionAdapter.addSection(new MySection(data.get(1)); //TODO: add a for loop and add all Item objects from data list
// Set up your RecyclerView with the SectionedRecyclerViewAdapter
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(sectionAdapter);
To make it expandable, follow the example here.

Android RecycleView adapter sometime doesnt call

I have an issue in RecycleView. My screen has two tabs, both tabs contain recycleview.It call normally most of the time but sometimes give empty screen. Just I wrote log & system.out and found this issue. I will paste my adapter class code here.
public class ExpandableListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int HEADER = 0;
public static final int CHILD = 1;
List<ContentTitle> titles;
Context context;
private List<Item> titleData = new ArrayList<Item>();
public ExpandableListAdapter(List<Item> data) {
this.titleData = data;
System.out.println("===this.titleData===" + this.titleData.size());
}
public void replaceContentFragment(String title,int id,int bookmarked) {
try {
SkillsApp SkillsApp = (SkillsApp) context.getApplicationContext();
Fragment fragment = new ContentActivityFragment();
FragmentManager fragmentManager = skillsUSAApp.mainActivity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
SkillsApp.subtitleID = id;
SkillsApp.isbookmark = (bookmarked == 0)? false:true;
SkillsApp.mainActivity.getSupportActionBar().setTitle(title);
SkillsApp.selectedSubtitleID = id;
}catch (Exception e){
e.printStackTrace();
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int type) {
View view = null;
try{
context = parent.getContext();
final SkillsApp skillsApp = (SkillsAApp)context.getApplicationContext();
if(!skillsApp.isDrawer){
switch (type) {
case HEADER:
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.main_title, parent, false);
ListHeaderViewHolder header = new ListHeaderViewHolder(view);
return header;
case CHILD:
LayoutInflater inflater1 = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater1.inflate(R.layout.sub_title, parent, false);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("Child", "child");
TextView text = (TextView) view.findViewById(R.id.header_title);
}
});
return new RecyclerView.ViewHolder(view) {
};
}
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
try{
System.out.println("==========##########");
final Item item = titleData.get(position);
final SkillsAApp skillsAApp = (SkillsAApp)context.getApplicationContext();
System.out.println("===onBindViewHolder item===" + item.mainTitle.title);
switch (item.type) {
case HEADER:
final ListHeaderViewHolder itemController = (ListHeaderViewHolder) holder;
itemController.refferalItem = item;
itemController.header_title.setText(item.mainTitle.title);
if (item.invisibleChildren == null) {
itemController.btn_expand_toggle.setImageResource(R.drawable.right_filled_arrow);
} else {
itemController.btn_expand_toggle.setImageResource(R.drawable.right_filled_arrow);
}
itemController.layoutItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
if(!skillsAApp.isDrawer){
if (item.invisibleChildren == null) {
item.invisibleChildren = new ArrayList<Item>();
int count = 0;
int pos = titleData.indexOf(itemController.refferalItem);
while (titleData.size() > pos + 1 && titleData.get(pos + 1).type == CHILD) {
item.invisibleChildren.add(titleData.remove(pos + 1));
count++;
}
notifyItemRangeRemoved(pos + 1, count);
notifyDataSetChanged();
itemController.btn_expand_toggle.setImageResource(R.drawable.right_filled_arrow);
} else {
int pos = titleData.indexOf(itemController.refferalItem);
int index = pos + 1;
for (Item i : item.invisibleChildren) {
titleData.add(index, i);
index++;
}
notifyItemRangeInserted(pos + 1, index - pos - 1);
notifyDataSetChanged();
itemController.btn_expand_toggle.setImageResource(R.drawable.down_arrow);
item.invisibleChildren = null;
}
}
}catch (Exception e){
e.printStackTrace();
}
}
});
break;
case CHILD:
View itemTextView = (View) holder.itemView;
TextView view = (TextView) itemTextView.findViewById(R.id.header_title);
view.setText(titleData.get(position).subtitle.title);
final int pos = position;
itemTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
if(!skillsUSAApp.isDrawer){
TextView text = (TextView) view.findViewById(R.id.header_title);
FlurryAgent.logEvent("Sub Category Item");
replaceContentFragment(text.getText().toString(), titleData.get(pos).subtitle.subtitleId, titleData.get(pos).subtitle.bookMarked);
}
}catch (Exception e){
e.printStackTrace();
}
}
});
break;
}
}catch (Exception e){
e.printStackTrace();
}
}
#Override
public int getItemViewType(int position) {
return titleData.get(position).type;
}
#Override
public int getItemCount() {
return titleData.size();
}
#Override
public long getItemId(int position) {
return position;
}
private static class ListHeaderViewHolder extends RecyclerView.ViewHolder {
public TextView header_title;
public ImageView btn_expand_toggle;
public Item refferalItem;
public RelativeLayout layoutItem;
public ListHeaderViewHolder(View itemView) {
super(itemView);
try{
header_title = (TextView) itemView.findViewById(R.id.header_title);
btn_expand_toggle = (ImageView) itemView.findViewById(R.id.btn_expand_toggle);
layoutItem = (RelativeLayout) itemView.findViewById(R.id.ll_title);
}catch (Exception e){
e.printStackTrace();
}
}
}
public static class Item {
public int type;
public String text;
public ContentTitle mainTitle;
public ContentSubTitle subtitle;
public List<Item> invisibleChildren;
public Item(int type, String text, List<Item> children) {
this.type = type;
this.text = text;
this.invisibleChildren = children;
}
public Item(int type, ContentTitle title,ContentSubTitle stitle) {
this.type = type;
this.mainTitle = title;
this.subtitle=stitle;
}
public Item(int type, String text) {
this.type = type;
this.text = text;
}
}
}
Here is a calling adapter from tab fragment
recyclerview = (RecyclerView) v.findViewById(R.id.recyclerview);
recyclerview.setLayoutManager(new LinearLayoutManager(v.getContext(), LinearLayoutManager.VERTICAL, false));
// recyclerview.setLayoutManager(new LinearLayoutManager(v.getContext()));
ExpandableListAdapter adapter = new ExpandableListAdapter(items);
recyclerview.setAdapter(adapter);
adapter.notifyDataSetChanged();
could you please advice me what is an issue? I didn't get any console error message.Could you please help me anyone here

Add new cardview dynamically on button click in android

I am using a cardview with recyclerview with hardcoded values such as string arrays. But now i want to add new cardview on each button click with user enter values and user select image and keep remain all cardviews on app exit.I mean to say that cardview should be added one by one only.Any solution plz guide me.
cardview Adapter class
public class CardViewDataAdapter extends RecyclerView.Adapter<CardViewDataAdapter.ViewHolder> {
private static ArrayList<FeddProperties> dataSet;
private static Context context;
public CardViewDataAdapter(Context context, ArrayList<FeddProperties> os_versions) {
this.context = context;
dataSet = os_versions;
}
#Override
public CardViewDataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.card_view, null);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(CardViewDataAdapter.ViewHolder viewHolder, int i) {
FeddProperties fp = dataSet.get(i);
viewHolder.vehicleNumber.setText(fp.getTitle());
viewHolder.iconView.setImageResource(fp.getThumbnail());
viewHolder.feed = fp;
}
#Override
public int getItemCount() {
return dataSet.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView vehicleNumber;
public ImageView iconView;
public FeddProperties feed;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
vehicleNumber = (TextView) itemLayoutView
.findViewById(R.id.vehiclenumber);
iconView = (ImageView) itemLayoutView
.findViewById(R.id.iconId);
itemLayoutView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), InformingUser.class);
v.getContext().startActivity(intent);
((MainActivity) context).getSupportFragmentManager().beginTransaction().replace
(R.id.containerView, new InformingUser()).commit();
//Toast.makeText(v.getContext(), "os version is: " + feed.getTitle(), Toast.LENGTH_SHORT).show();
}
});
}
}
Java file....
private void initContrls()
{
SharedPreferences prefs = context.getSharedPreferences(MY_PREFS_NAME, 0);
vehiclecatory = prefs.getString("vehicle_category", "");
vehicletype = prefs.getString("vehicle_type", "");
String versions = prefs.getString("city", "")+" "+prefs.getString("dis", "")+" "+prefs.getString("number", "");
String vehicleCompany = prefs.getString("company", "")+" "+prefs.getString("model", "");
if(vehiclecatory.equals("1"))
{
if (vehicletype.equals("1"))
{
icons = R.drawable.contwowheel;
}
else if (vehicletype.equals("2"))
{
icons = R.drawable.comfourwheel;
}
else if (vehicletype.equals("3"))
{
icons = R.drawable.comheavy;
}
}
else if (vehiclecatory.equals("2"))
{
if (vehicletype.equals("1"))
{
icons = R.drawable.nontwowheel;
}
else if (vehicletype.equals("2"))
{
icons = R.drawable.nonfourwheel;
}
else if (vehicletype.equals("3"))
{
icons = R.drawable.nonheavy;
}
}
os_versions = new ArrayList<FeddProperties>();
for (int i = 0; i < 2; i++) {
FeddProperties feed = new FeddProperties();
feed.setTitle(versions);
feed.setVehicleCompany(vehicleCompany);
feed.setThumbnail(icons);
os_versions.add(feed);
}
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
mAdapter = new CardViewDataAdapter(context,os_versions);
recyclerView.setAdapter(mAdapter);
}
here there is an example to add cardview dinamically
In this example cardview are create with for:
for (int index = 0; index < 20; index++) {
DataObject obj = new DataObject("Some Primary Text " + index,
"Secondary " + index);
results.add(index, obj);
}
but you can inser into onClick action :)

Categories

Resources