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.
Related
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();
}
This is the method where i am getting the data from the server and show in the listview
I want to show the list alphabetically accordingly to the i am setting the name with the help of model class. pojoRestaurant.setRestroName(jsonObject.getString("RestaurantName"));
I want to show the list accordingly RestaurantName.can anyone tell me how can i do this ??
public void requestRestaurantSearchByFilter_list() {
mProgressDialog.show();
StringRequest restrolistrequestfilter = new StringRequest(Request.Method.POST, GlobalData.SEARCHBYFILTERURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
mProgressDialog.dismiss();
mPaymentMethodList.clear();
mDataList.clear();
mAllList.clear();
mAdapter.notifyDataSetChanged();
Log.e("responcefilterlist....", response);
JSONObject jObject = new JSONObject(response);
if (jObject.getString("status").equals("1")) {
JSONArray jsonArray = jObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
PojoRestaurant pojoRestaurant = new PojoRestaurant();
pojoRestaurant.setRestroName(jsonObject.getString("RestaurantName"));
pojoRestaurant.setDeliveryTime(jsonObject.optString("DeliveryTime"));
pojoRestaurant.setPaymentOption(jsonObject.getString("PaymentOptions"));
pojoRestaurant.setMinimumOrder(jsonObject.getString("MinimumOrder"));
if (jsonObject.getString("ImageUrl").equals("") || jsonObject.getString("ImageUrl") == "null") {
} else {
pojoRestaurant.setRestroImage(jsonObject.getString("ImageUrl"));
}
id = jsonObject.getString("ID");
mPaymentMethodList.add(jsonObject.getString("PaymentOptions"));
getpaymentId.add(id);
getListViewId.add(id);
if (jsonObject.getString("OpenStatus").equals("true")) {
pojoRestaurant.setOpenClose("Open");
} else {
pojoRestaurant.setOpenClose("Close");
}
mAllList.add(pojoRestaurant);
mDataList.add(pojoRestaurant);
//mDeliveryList.add(jsonObject.getString("DeliveryTime"));
// mCuisineTypeList.add(jsonObject.getString("RestaurantName"));
}
mListView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("error", "" + volleyError.getMessage());
if (volleyError.getMessage() == null)
requestRestaurantSearchByFilter_list();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
String foodid = getArguments().getString("FOODID");
String areaid = getArguments().getString("AREAID");
Log.e("foodid", "" + foodid);
Log.e("areaid", "" + areaid);
params.put("DeliveryAreaID", areaid);
params.put("ProvideOffers", "0");
params.put("NewRestaurant", "0");
params.put("PaymentMethod", "0");
params.put("OpenRestaurant", "0");
params.put("FoodID", foodid);
return params;
}
};
RequestQueue restrolistqueuefilter = Volley.newRequestQueue(getContext());
restrolistrequestfilter.setShouldCache(false);
restrolistqueuefilter.add(restrolistrequestfilter);
}
This is my Adpater Class
public class RestroListBaseAdapter extends BaseAdapter {
private ArrayList<PojoRestaurant> mList;
private Context mContext;
private ViewHolder viewHolder;
private ArrayList<PojoRestaurant> suggestion = new ArrayList<>();
public RestroListBaseAdapter(Context mContext, ArrayList<PojoRestaurant> mList) {
this.mContext = mContext;
this.mList = mList;
}
#Override
public int getCount() {
if (mList != null) {
return mList.size();
}
return 0;
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int lastPosition = -1;
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.restaurant_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.RestroName = (TextView) convertView.findViewById(R.id.tv_restro_name);
viewHolder.OpenClose = (TextView) convertView.findViewById(R.id.tvOpenClose);
viewHolder.MinimumOrder = (TextView) convertView.findViewById(R.id.tv_minimun_order);
viewHolder.DeliveryTime = (TextView) convertView.findViewById(R.id.tv_delivery_time);
viewHolder.PaymentOption = (TextView) convertView.findViewById(R.id.tv_Payment);
viewHolder.RestroImage = (ImageView) convertView.findViewById(R.id.img_restro_list);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Animation animation = AnimationUtils.loadAnimation(mContext, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
convertView.startAnimation(animation);
lastPosition = position;
convertView.setTag(viewHolder);
PojoRestaurant pojoRestaurant = (PojoRestaurant) getItem(position);
viewHolder.RestroName.setText(pojoRestaurant.getRestroName());
viewHolder.DeliveryTime.setText(pojoRestaurant.getDeliveryTime());
viewHolder.MinimumOrder.setText(pojoRestaurant.getMinimumOrder());
viewHolder.OpenClose.setText(pojoRestaurant.getOpenClose());
viewHolder.PaymentOption.setText(pojoRestaurant.getPaymentOption());
Picasso.with(mContext).load(pojoRestaurant.getRestroImage()).into(viewHolder.RestroImage);
return convertView;
}
private class ViewHolder {
private TextView RestroName, OpenClose, MinimumOrder, DeliveryTime, PaymentOption;
private ImageView RestroImage;
}
}
You just need to sort that list returned from server by alphabetically order and then add this list directly to your listview.
For example you have a model class:
public class Restaurant {
String restaurantName;
int restaurantStar;
}
You should implements Comparator interface for this class:
public class Restaurant implements Comparator<Restaurant> {
String restaurantName;
int restaurantStar;
#Override
public int compare(Schedule s1, Schedule s2) {
// because class String has already implemented Comparator. just get that
return s1.restaurantName.compare(s2.restaurantName);
}
}
Finally you can sort this list of restaurants:
// get somewhere on network
List<Restaurant> restaurants;
Collection.sort(restaurants);
Finally you can assign directly this list to listview. For example:
adapter.setData(restaurants);
// refresh listview so listview will display new sorted data
adapter.notifyDataSetChanged();
Here is an another example that using Comparator:
comparator tutorial
First, you need to sort the list(depending upon your logic i.e. alphabetically) which you have already used to set to the adapter and then notify the list adapter.
You can use your own comparator for sorting the list.
Sample code for Comparator:
Comparator comparator = new Comparator() {
public int compare(PojoRestaurant restro1, PojoRestaurant restro2) {
String restroName1 = restro1.getRestroName.toUpperCase();
String restroName2 = restro2.getRestroName.toUpperCase();
//ascending order
return restroName1.compareTo(restroName2);
//descending order
//return restroName2.compareTo(restroName1);
}
};
Then, you can use following code to sort the list
Collections.sort(yourList, collection)
I am using this liabray for swipe gestures. https://github.com/nikhilpanju/RecyclerViewEnhanced.
In the MainAdapter.java class recyclerView contains List but i want to replace this to List> type. When i do this, so many errors appear. Kindly guide me how can i do this or suggest me any tutorial to do that.
MainAdapter.java
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.MainViewHolder> {
LayoutInflater inflater;
List<RowModel> modelList;
public MainAdapter(Context context, List<RowModel> list) {
inflater = LayoutInflater.from(context);
modelList = new ArrayList<>(list);
}
#Override
public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.recycler_row, parent, false);
return new MainViewHolder(view);
}
#Override
public void onBindViewHolder(MainViewHolder holder, int position) {
holder.bindData(modelList.get(position));
}
#Override
public int getItemCount() {
return modelList.size();
}
class MainViewHolder extends RecyclerView.ViewHolder {
TextView mainText, subText;
public MainViewHolder(View itemView) {
super(itemView);
mainText = (TextView) itemView.findViewById(R.id.mainText);
subText = (TextView) itemView.findViewById(R.id.subText);
}
public void bindData(RowModel rowModel) {
mainText.setText(rowModel.getMainText());
subText.setText(rowModel.getSubText());
}
}
}
Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_panel);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
unclickableRows = new ArrayList<>();
unswipeableRows = new ArrayList<>();
dialogItems = new String[25];
for (int i = 0; i < 25; i++) {
dialogItems[i] = String.valueOf(i + 1);
}
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mAdapter = new MainAdapter(this, getData());
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
onTouchListener = new RecyclerTouchListener(this, mRecyclerView);
onTouchListener
.setIndependentViews(R.id.rowButton)
.setViewsToFade(R.id.rowButton)
.setClickable(new RecyclerTouchListener.OnRowClickListener() {
#Override
public void onRowClicked(int position) {
util.shortToast(getApplicationContext(), "Row " + (position + 1) + " clicked!");
}
#Override
public void onIndependentViewClicked(int independentViewID, int position) {
util.shortToast(getApplicationContext(), "Button in row " + (position + 1) + " clicked!");
}
})
.setSwipeOptionViews(R.id.add, R.id.edit, R.id.change)
.setSwipeable(R.id.rowFG, R.id.rowBG, new RecyclerTouchListener.OnSwipeOptionsClickListener() {
#Override
public void onSwipeOptionClicked(int viewID, int position) {
String message = "";
if (viewID == R.id.add) {
message += "Add";
} else if (viewID == R.id.edit) {
message += "Edit";
} else if (viewID == R.id.change) {
message += "Change";
}
message += " clicked for row " + (position + 1);
util.shortToast(getApplicationContext(), message);
}
});
mRecyclerView.addOnItemTouchListener(onTouchListener);
// Detect touched area
detector = new Swipe(this,this);
db = new DB(getApplicationContext());
Bundle bundle = getIntent().getExtras();
if(bundle != null) {
String id = bundle.getString("id");
Toast.makeText(this, "Welcome " + db.getUsernameById(id), Toast.LENGTH_LONG).show();
}
//get references of layout
// adapter = new AdapterUsers(this, R.layout.textview_users, arrayList);
// listView = (ListView) findViewById(R.id.users);
// listView.setAdapter(adapter);
//
// showAllUsers();
}
public void showAllUsers() {
try {
Cursor cursor = db.selectAllUsers();
cursor.moveToFirst();
adapter.clear();
if (cursor.getCount() == 0) {
Toast.makeText(this, "Empty user list", Toast.LENGTH_SHORT).show();
} else {
for (int i = 0; i < cursor.getCount(); i++) {
HashMap<String, Object> hm = new HashMap<String, Object>();
hm.put(ID, cursor.getString(cursor.getColumnIndex(db.ID_USER)));
hm.put(USERNAME, cursor.getString(cursor.getColumnIndex(db.NAME_USER)));
arrayList.add(hm);
cursor.moveToNext();
}
}
} catch (Exception e) {
Log.d("Show users", " failed due to " + e.getMessage());
}
}
// Swipe interface
#Override
public void onSwipe(int direction) {
String str = "";
switch (direction) {
case Swipe.SWIPE_RIGHT :
listView.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//deleteUser(id);
Toast.makeText(AdminPanel.this, "user deleted", Toast.LENGTH_LONG).show();
}
});
str = "Swipe Right";
break;
case Swipe.SWIPE_LEFT : str = "Swipe Left";
break;
case Swipe.SWIPE_DOWN : str = "Swipe Down";
break;
case Swipe.SWIPE_UP : str = "Swipe Up";
break;
}
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
#Override
public void onDoubleTap() {
Toast.makeText(this, "Double Tap", Toast.LENGTH_SHORT).show();
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (touchListener != null) touchListener.getTouchCoordinates(ev);
return super.dispatchTouchEvent(ev);
}
#Override
public void setOnActivityTouchListener(OnActivityTouchListener listener) {
this.touchListener = listener;
}
private List<RowModel> getData() {
List<RowModel> list = new ArrayList<>(25);
for (int i = 0; i < 25; i++) {
list.add(new RowModel("Row " + (i + 1), "Some Text... "));
}
return list;
}
}
you can change your getData() method and make it return HashMap.
private HashMap <String,String> getData() {
HashMap <String,String> list = new HashMap <String,String>();
for (int i = 0; i < 25; i++) {
list.put(i,"Text");
}
return list;
}
now in your Adapter you can handle it like...
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.MainViewHolder> {
LayoutInflater inflater;
<HashMap<String,String> modelList;
public MainAdapter(Context context, <HashMap<String,String> modelList) {
this.inflater = LayoutInflater.from(context);
this.modelList = modelList;
}
#Override
public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.recycler_row, parent, false);
return new MainViewHolder(view);
}
#Override
public void onBindViewHolder(MainViewHolder holder, int position) {
//holder.bindData();
holder.mainText.setText(modelList.get(position)); // value for the given key
}
#Override
public int getItemCount() {
return modelList.size();
}
class MainViewHolder extends RecyclerView.ViewHolder {
TextView mainText, subText;
public MainViewHolder(View itemView) {
super(itemView);
mainText = (TextView) itemView.findViewById(R.id.mainText);
subText = (TextView) itemView.findViewById(R.id.subText);
}
}
}
I am using listview to populate data coming from the server. This listview will show that data in a fragmentTab. Now the data is parsing fine and logcat is also showing the data. But the data is not being populated by listview. I tried to see the error through debugging but there is no problem. Even the Holder in adapter catches the data but it's not displayed. I don't know what the problem is. I tried the following questions but didn't got the answer.
Android - ListView in Fragment does not showing up
Android - ListView in Fragment does not show
ListView in Fragment Not Displayed
Below is my fragment and the adapter.
Tastemaker Fragment:
public class TasteMakersFragment extends Fragment
{
CommonClass commonTasteMakers;
String tasteMaker_url = CommonClass.url+ URLConstants.Host.URL_ALL_SUGGESTED_TASTEMAKERS;
String user_token = "8aa0dcd5aaf54c8a5aaef1aa242f342f";
ListView suggested_list;
List<SuggestedUserModel> suggestedUsers_list = new ArrayList<>();
SuggestedUsersAdapter mAdapter;
int selectedPosition = 0;
public TasteMakersFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.from(getActivity()).inflate(R.layout.suggested_users_tastemakers, null);
commonTasteMakers = new CommonClass(getActivity().getApplicationContext());
suggested_list = (ListView)v.findViewById(R.id.lst_suggestedUsers);
new GetSuggestedUsers().execute(tasteMaker_url);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
private class GetSuggestedUsers extends AsyncTask< String, Void, Void>
{
private ProgressDialog Dialog = new ProgressDialog(getActivity());
protected void onPreExecute() {
if (suggestedUsers_list.isEmpty())
{
Dialog = ProgressDialog.show(getActivity(),"Please be patient!","Fetching for first time...");
}
}
#Override
protected Void doInBackground(String... params)
{
if (suggestedUsers_list.isEmpty())
{
getSuggestedUsers();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
else{
Log.d("---- Already Fetched --", "---- Already Fetched ----");
return null;
}
}
protected void onPostExecute(Void unused)
{
Dialog.dismiss();
mAdapter = new SuggestedUsersAdapter(getActivity(), suggestedUsers_list);
suggested_list.setAdapter(mAdapter);
suggested_list.setSelection(selectedPosition);
mAdapter.notifyDataSetChanged();
//startMainActivity();
}
}
private List<SuggestedUserModel> getSuggestedUsers()
{
StringRequest postRequest = new StringRequest(Request.Method.POST, tasteMaker_url, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
try {
//JSONObject jsonResponse = new JSONObject(response).getJSONObject("form");
JSONObject jsonResponse = new JSONObject(response);
if (jsonResponse.has("data"))
{
JSONObject data = jsonResponse.getJSONObject("data");
String code = jsonResponse.getString("code");
if(code.equals("200"))
{
if(data.has("tasteMakers"))
{
JSONArray tastemakers = data.getJSONArray("tasteMakers");
for (int i =0; i<tastemakers.length(); i++)
{
JSONObject jsnObj = tastemakers.getJSONObject(i);
String id = jsnObj.getString("userId");
String name = jsnObj.getString("name");
String profilePic = jsnObj.getString("imgUrl");
Boolean isFollowed = jsnObj.getBoolean("isFollowed");
suggestedUsers_list.add(new SuggestedUserModel(id,
name,
profilePic,
isFollowed));
Log.d("Names are ----", "size is=" + name +" and their id are: "+id);
}
// Log.d("Adapter list ----", "size is=" + suggestedUsers_list.size());
}
}
else {
Log.d("Error0 Error Error", "response------:" + jsonResponse);
}
}
// Log.d("response222---------","response22222------:"+jsonResponse);
} catch (JSONException e) {
Log.d("-----Stop------", "!!!");
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
// the POST parameters:
params.put("sessionToken", user_token);
return params;
} };
postRequest.setRetryPolicy(new DefaultRetryPolicy(20000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(getActivity().getApplicationContext()).add(postRequest);
return suggestedUsers_list;
}
}
Adapter Class:
public class SuggestedUsersAdapter extends BaseAdapter {
Context context;
int count = 1;
private List<SuggestedUserModel> allUsers;
public SuggestedUsersAdapter(FragmentActivity activity, List<SuggestedUserModel> suggestUserModel)
{
Log.d("Custom Adapter called", "" + suggestUserModel.size());
context = activity;
allUsers = suggestUserModel;
//FragmentActivity mActivity = activity;
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return allUsers.size();
// return imageId.length;
}
#Override
public Object getItem(int position) {
return allUsers.get(position);
// return position;
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint({"ViewHolder", "InflateParams", "CutPasteId"})
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final mHolder holder;
// int type = getItemViewType(position);
LayoutInflater layoutInflater;
getItemViewType(position);
if (convertView == null)
{
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.suggested_users_tastemaker_cell, null);
holder = new mHolder();
// convertView.setTag(mFeedsListItemViewHolder);
holder.txt_suggestUserName = (TextView) convertView.findViewById(R.id.tv_tasteMakerName);
holder.imgV_userProfile = (ImageView) convertView.findViewById(R.id.imgBtn_tasteMaker_pic);
holder.btnFollow = (Button) convertView.findViewById(R.id.btnFollow_tasteMaker);
holder.btnFollowing = (Button) convertView.findViewById(R.id.btnFollowing);
convertView.setTag(holder);
} else {
holder = (mHolder) convertView.getTag();
}
final SuggestedUserModel suggestUser = allUsers.get(position);
holder.txt_suggestUserName.setText(allUsers.get(position).getSuggested_UserName());
/*if(suggestUser.getSuggested_UserImage().equals(""))
{
Picasso
.with(context)
.load(R.mipmap.ic_launcher)
.transform(new CropSquareTransformationHomePage())
.into(holder.imgV_userProfile);
}
else {
Picasso
.with(context)
.load(suggestUser.getSuggested_UserImage())
.transform(new CropSquareTransformationHomePage())
.into(holder.imgV_userProfile);
}*/
holder.pos = position;
//mFeedsListItemViewHolder.setData(allPersons.get(position));
return convertView;
}
private class mHolder {
TextView txt_suggestUserName;
ImageView imgV_userProfile;
Button btnFollow;
Button btnFollowing;
int pos;
}
}
Note: I already tried declaring listview and assigning adapter in onActivityCreated() method of fragment but no effect.
Any Help will be appreciated.
Below is the code where i m parsing JSON and this method gets called onResume() method.
private void parseJSONSubTypeEventsSelect(String response)
throws JSONException {
JSONObject jsonObject = new JSONObject(response);
JSONArray columns = jsonObject.getJSONArray("columns");
JSONArray rowsWrapper = jsonObject.getJSONArray("rows");
JsonHelper jsonHelper = new JsonHelper();
List<List<String>> listOfListRow = new ArrayList<List<String>>();
Map<String, List<String>> map = new HashMap<>();
try {
for (int i = 0; i < rowsWrapper.length(); i++) {
if (i == rowsWrapper.length()) {
break;
} else {
map.put(rowsWrapper.get(i).toString(),jsonHelper.toList(rowsWrapper.getJSONArray(i)));
rowListSubTypeEvents = jsonHelper.toList(rowsWrapper.getJSONArray(i));
listOfListRow.add(rowListSubTypeEvents);
}
}
// System.out.println(listOfListRow);
} catch (Exception e1) {
e1.printStackTrace();
}
I am Clearing the data here but the same data is printed twice
StandName.clear();
slNo.clear();
Rate.clear();
System.out.println("StandName before"+StandName);
System.out.println("slNo before"+slNo);
System.out.println("Rate before"+Rate);
StandName.add("Select Stand Name");
slNo.add("");
Rate.add("");
System.out.println("StandName after"+StandName);
System.out.println("slNo after"+slNo);
System.out.println("Rate after"+Rate);
for (List<String> listRows : listOfListRow) {
int k = 0;
for (String value : listRows) {
k++;
switch (k) {
case 1:
imageMapCoords.add(value);
// listOfListRow.add(logoFileNameList);
break;
case 2:
slNo.add(value);
// listOfListRow.add(logoFileName1List);
break;
case 3:
StandName.add(value);
// listOfListRow.add(logoFileName1List);
break;
case 4:
Rate.add(value);
// listOfListRow.add(logoFileName1List);
break;
case 5:
avail.add(value);
// listOfListRow.add(logoFileName1List);
break;
case 6:
allowSeatSelection.add(value);
// listOfListRow.add(logoFileName1List);
break;
case 7:
panaromicView.add(value);
// listOfListRow.add(logoFileName1List);
break;
}
}
}
tvVenue.setText(Venue.get(Venue.size() - 1));
System.out.println("Stand names from third activity"+StandName);
System.out.println("data sending to pojo slNo "+slNo);
System.out.println("data sending to pojo StandName"+StandName);
System.out.println("data sending to pojo Rate"+Rate);
for (int i = 0; i <= rowsWrapper.length(); i++) {
RowItemThird item = new RowItemThird(slNo.get(i),StandName.get(i), Rate.get(i));
rowItems.add(item);
}
adapter = new CustomBaseAdapterThird(this, rowItems);
adapter.notifyDataSetChanged();
// lvThird.setAdapter(adapter);
spinner.setAdapter(adapter);
pDialog.hide();
pDialog.dismiss();
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
positionCheckStandName = StandName.get(position);
System.out.println("positionCheckStandName"+positionCheckStandName);
positionSlNo = slNo.get(position);
stringRate = Rate.get(position);
System.out.println("SLNO"+positionSlNo);
/* spinner.getSelectedItemPosition();*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Below is the pojo class
public class RowItemThird {
private String mSlNo;
private String mStandName;
private String mRate;
public RowItemThird(String slNo, String StandName, String Rate) {
mSlNo = slNo;
mStandName = StandName;
mRate = Rate;
}
public String getmSlNo() {
return mSlNo;
}
public void setmSlNo(String mSlNo) {
this.mSlNo = mSlNo;
}
public String getmStandName() {
return mStandName;
}
public void setmStandName(String mStandName) {
this.mStandName = mStandName;
}
public String getmRate() {
return mRate;
}
public void setmRate(String mRate) {
this.mRate = mRate;
}
}
Below is the BaseAdapter class to add items to spinner
public class CustomBaseAdapterThird extends BaseAdapter
{
private Context mContext;
private List<RowItemThird> mRowItems;
TextView slNO;
TextView StandName;
TextView Rate;
public CustomBaseAdapterThird(Context context, List<RowItemThird> rowItems)
{
mContext = context;
mRowItems = rowItems;
}
#Override
public int getCount() {
return mRowItems.size();
}
#Override
public Object getItem(int position) {
return mRowItems.get(position);
}
#Override
public long getItemId(int position) {
return mRowItems.indexOf(getItem(position));
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = null;
LayoutInflater mInflator = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflator.inflate(R.layout.event_list_item_third_sub_type_event_select, null);
slNO = (TextView) convertView.findViewById(R.id.textViewSLNo);
StandName = (TextView) convertView.findViewById(R.id.textViewStand);
Rate = (TextView) convertView.findViewById(R.id.textViewRate);
RowItemThird row = (RowItemThird) getItem(position);
slNO.setText(row.getmSlNo());
StandName.setText(row.getmStandName());
Rate.setText(row.getmRate());
return convertView;
}
}
Every time you are adding the data to the rowItems object, which you are passing to the spinner adapter
adapter = new CustomBaseAdapterThird(this, rowItems);
adapter.notifyDataSetChanged();
So clear the ``rowItems` data before adding the new data
rowItems.clear();
for (int i = 0; i <= rowsWrapper.length(); i++) {
RowItemThird item = new RowItemThird(slNo.get(i),StandName.get(i), Rate.get(i));
rowItems.add(item);
}