I have a recyclerview that display news.
News is composed by name_news,image_news,time_news.
I am getting the data from mysqldatabse.
This is my adapter class:
public class PostAdapter2 extends RecyclerView.Adapter<PostAdapter2.ViewHolder>{
public Context c;
public FragmentManager mContext;
public ArrayList<News_data> original_items = new ArrayList<>();
public ArrayList<News_data> filtered_items = new ArrayList<>();
public ArrayList<Simplenews_data> original_items2 = new ArrayList<>();
public ArrayList<Simplenews_data> filtered_items2 = new ArrayList<>();
// ItemFilter mFilters = new ItemFilter();
public PostAdapter2(Context c, ArrayList<News_data> postList) {
this.c = c;
this.original_items = postList;
this.filtered_items = postList;
}
public PostAdapter2(FragmentManager mContext, ArrayList<Simplenews_data> postList) {
this.mContext = mContext;
this.original_items2 = postList;
this.filtered_items2 = postList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_news, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
try {
final Simplenews_data post = filtered_items2.get(position);
PicassoClient.downloadImage(c, post.getImage_simplenews(), holder.image_news);
holder.txt_news_title.setText(post.getName_simplenews());
holder.txt_date.setText(post.getTime_simplenews());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick() {
Bundle x = new Bundle();
x.putString("news_title", post.getName_simplenews());
x.putString("news", post.getDesc_simplenews());
x.putString("image",post.getImage_simplenews());
x.putString("time",post.getTime_simplenews());
x.putString("date",post.getDate_simplenews());
Fragment descriptionFragment = new DescriptionFragment();
FragmentTransaction transaction = mContext.beginTransaction();
descriptionFragment.setArguments(x);
transaction.replace(R.id.framelayout, descriptionFragment).addToBackStack(null).commit();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return filtered_items2.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ItemClickListener itemClickListener;
TextView txt_news_title,txt_date;
ImageView image_news;
public ViewHolder(View itemView) {
super(itemView);
txt_news_title = (TextView) itemView.findViewById(R.id.txt_news_title);
txt_date = (TextView) itemView.findViewById(R.id.txt_timedate);
image_news = (ImageView) itemView.findViewById(R.id.image_news);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
try {
this.itemClickListener.onItemClick();
}catch (Exception e)
{
e.printStackTrace();
}
}
public void setItemClickListener(ItemClickListener itemClickListener)
{
this.itemClickListener=itemClickListener;
}
}
}
I am using a PHP interface to add news.
The getTime_simplenews() contains the news sumbmitted time format as : 14:00
So i want to display the immediate news in Top of recyclerview not under the previous news.
Thanks a lot.
UPDATED :
public class Simplenews_data {
int id_simplenews;
String name_simplenews,image_simplenews,desc_simplenews,time_simplenews,date_simplenews;
public String getDate_simplenews() {
return date_simplenews;
}
public void setDate_simplenews(String date_simplenews) {
this.date_simplenews = date_simplenews;
}
public String getTime_simplenews() {
return time_simplenews;
}
public void setTime_simplenews(String time_simplenews) {
this.time_simplenews = time_simplenews;
}
public int getId_simplenews() {
return id_simplenews;
}
public void setId_simplenews(int id_simplenews) {
this.id_simplenews = id_simplenews;
}
public String getName_simplenews() {
return name_simplenews;
}
public void setName_simplenews(String name_simplenews) {
this.name_simplenews = name_simplenews;
}
public String getImage_simplenews() {
return image_simplenews;
}
public void setImage_simplenews(String image_simplenews) {
this.image_simplenews = image_simplenews;
}
public String getDesc_simplenews() {
return desc_simplenews;
}
public void setDesc_simplenews(String desc_simplenews) {
this.desc_simplenews = desc_simplenews;
}
Fragment Code:
public void parseJson2(String response) {
try {
JSONArray array = new JSONArray(response);
JSONObject jsonObject = null;
post_array2.clear();
Simplenews_data p;
for (int i = 0; i < array.length(); i++) {
jsonObject = array.getJSONObject(i);
int id_simplenews = jsonObject.getInt("id_simplenews");
String name_simplenews = jsonObject.getString("name_simplenews");
String image_simplenews = jsonObject.getString("image_simplenews");
String desc_simplenews = jsonObject.getString("desc_simplenews");
String time_simplenews = jsonObject.getString("time_simplenews");
String date_simplenews = jsonObject.getString("date_simplenews");
p = new Simplenews_data();
p.setId_simplenews(id_simplenews);
p.setName_simplenews(name_simplenews);
p.setImage_simplenews(image_simplenews);
p.setDesc_simplenews(desc_simplenews);
p.setTime_simplenews(time_simplenews);
p.setDate_simplenews(date_simplenews);
post_array2.add(p);
}
} catch (JSONException e) {
swipeRefreshLayout.setRefreshing(false);
e.printStackTrace();
}
adapter = new PostAdapter2(getFragmentManager(), post_array2);
recycler_post.setAdapter(adapter);
swipeRefreshLayout.setRefreshing(false);
}
I have updated your model class and implemented Comparable to it
public class Simplenews_data implements Comparable<Simplenews_data> {
int id_simplenews;
String name_simplenews,image_simplenews,desc_simplenews,time_simplenews,date_simplenews;
public String getDate_simplenews() {
return date_simplenews;
}
public void setDate_simplenews(String date_simplenews) {
this.date_simplenews = date_simplenews;
}
public String getTime_simplenews() {
return time_simplenews;
}
public void setTime_simplenews(String time_simplenews) {
this.time_simplenews = time_simplenews;
}
public int getId_simplenews() {
return id_simplenews;
}
public void setId_simplenews(int id_simplenews) {
this.id_simplenews = id_simplenews;
}
public String getName_simplenews() {
return name_simplenews;
}
public void setName_simplenews(String name_simplenews) {
this.name_simplenews = name_simplenews;
}
public String getImage_simplenews() {
return image_simplenews;
}
public void setImage_simplenews(String image_simplenews) {
this.image_simplenews = image_simplenews;
}
public String getDesc_simplenews() {
return desc_simplenews;
}
public void setDesc_simplenews(String desc_simplenews) {
this.desc_simplenews = desc_simplenews;
}
#Override
public int compareTo(MyObject o) {
Date newDate = formatDateTime(o.getTime_simplenews(), "HH:mm", "YYYY-MM-DD HH:mm");
Date inputDate = formatDateTime(getTime_simplenews(), "HH:mm", "YYYY-MM-DD HH:mm");
return inputDate.compareTo(newDate);
}
public Date formatDateTime(String date, String fromFormat, String toFormat) {
Date d = null;
try {
d = new SimpleDateFormat(fromFormat, Locale.US).parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return new SimpleDateFormat(toFormat, Locale.US).parse(d);
}
}
Sort the list using below code
Collections.sort(yourList);
Related
I want to show inner json array in Recyclerview.
I was getting all the data in logcat.
But my problem is how to write code in adapter class for inner array items.
My problem is like this question
How to get data from nested json array android
I have similar json array.
I want to pass arraylist to Adapter.
This is my modal
public class OuterModal {
String menuId;
String menuName;
private List<InnerModal> innerItem;
public String getMenuId() {
return menuId;
}
public void setMenuId(String menuId) {
this.menuId = menuId;
}
public String getMenuName() {
return menuName;
}
public void setMenuName(String menuName) {
this.menuName = menuName;
}
public List<InnerModal> getInnerItem() {
return innerItem;
}
public void setInnerItem(List<InnerModal> innerItem) {
this.innerItem = innerItem;
}
}
This is my another modal
public class InnerModal {
String vendor_item_id;
String vendor_id;
String vendor_item_name;
String vendor_item_image;
String vendor_item_price;
String vendor_item_category;
String vendor_item_description;
String vendor_item_status;
public String getVendor_item_id() {
return vendor_item_id;
}
public void setVendor_item_id(String vendor_item_id) {
this.vendor_item_id = vendor_item_id;
}
public String getVendor_id() {
return vendor_id;
}
public void setVendor_id(String vendor_id) {
this.vendor_id = vendor_id;
}
public String getVendor_item_name() {
return vendor_item_name;
}
public void setVendor_item_name(String vendor_item_name) {
this.vendor_item_name = vendor_item_name;
}
public String getVendor_item_image() {
return vendor_item_image;
}
public void setVendor_item_image(String vendor_item_image) {
this.vendor_item_image = vendor_item_image;
}
public String getVendor_item_price() {
return vendor_item_price;
}
public void setVendor_item_price(String vendor_item_price) {
this.vendor_item_price = vendor_item_price;
}
public String getVendor_item_category() {
return vendor_item_category;
}
public void setVendor_item_category(String vendor_item_category) {
this.vendor_item_category = vendor_item_category;
}
public String getVendor_item_description() {
return vendor_item_description;
}
public void setVendor_item_description(String vendor_item_description) {
this.vendor_item_description = vendor_item_description;
}
public String getVendor_item_status() {
return vendor_item_status;
}
public void setVendor_item_status(String vendor_item_status) {
this.vendor_item_status = vendor_item_status;
}
}
This is JSON Responce
StringRequest stringRequest = new StringRequest(Request.Method.GET,
mainUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("menu");
List<OuterModal> outerModalList=new ArrayList<>();
OuterModal outerModal=new OuterModal();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
String menu_id = json.getString("menu_id");
String menu_name = json.getString("menu_name");
outerModal.setMenuId(menu_id);
outerModal.setMenuName(menu_name);
JSONArray productsListArray = json.getJSONArray("Products List");
for (int j = 0; j < productsListArray.length(); j++) {
// Log.d("myDraaa", "list responce:" + productsListArray);
JSONObject productsListjson = productsListArray.getJSONObject(j);
InnerModal innerModal=new InnerModal();
List<InnerModal> innerModalList=new ArrayList<>();
String vendor_item_id = productsListjson.getString("vendor_item_id");
String vendor_id = productsListjson.getString("vendor_id");
String vendor_item_name = productsListjson.getString("vendor_item_name");
String vendor_item_image = productsListjson.getString("vendor_item_image");
String vendor_item_status = productsListjson.getString("vendor_item_status");
String quantity = productsListjson.getString("quantity");
innerModal.setVendor_id(vendor_id);
innerModal.setVendor_item_id(vendor_item_id);
innerModal.setVendor_item_category("");
innerModal.setVendor_item_description("");
innerModal.setVendor_item_image(vendor_item_image);
innerModal.setVendor_item_name(vendor_item_name);
innerModal.setVendor_item_status(vendor_item_status);
innerModal.setVendor_item_price(quantity);
outerModal.getInnerItem().add(innerModal);
}
outerModalList.add(outerModal);
}
public class SecondAdapter extends RecyclerView.Adapter<SecondAdapter.SecondVH> {
List<OuterModal> arrayList;
Context context;
public SecondAdapter(List<OuterModal> arrayList, Context context) {
this.arrayList = arrayList;
this.context = context;
}
#NonNull
#Override
public SecondVH onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.my_custom_style, null, false);
return new SecondVH(v);
}
#Override
public void onBindViewHolder(#NonNull SecondVH holder, final int position) {
OuterModal outerModal=arrayList.get(position);
holder.title.setText(outerModal.getMenuName());
}
#Override
public int getItemCount() {
return arrayList.size();
}
public class SecondVH extends RecyclerView.ViewHolder {
TextView title;
TextView items;
ConstraintLayout constraintLayout;
TextView itemName, itemPrice, itemDescription;
public SecondVH(View itemView) {
super(itemView);
title = itemView.findViewById(R.id.bestSellers);
items = itemView.findViewById(R.id.myCustItemName);
constraintLayout = itemView.findViewById(R.id.csL);
itemPrice = itemView.findViewById(R.id.itemPrice);
itemDescription = itemView.findViewById(R.id.itemDesc);
}
}
}
Thanks in advance.
Please help me.
I have a model class:
public class Home_Model_ViewPager {
public String buttonLink;
public String tipsDescription;
public String tipsButton;
public Context context;
public Home_Model_ViewPager( Context context, String tipsDescription, String tipsButton, String buttonLink) {
this.context = context;
this.tipsDescription = tipsDescription;
this.tipsButton = tipsButton;
this.buttonLink = buttonLink;
}
public String getButtonLink() {
return buttonLink;
}
public void setButtonLink(String buttonLink) {
this.buttonLink = buttonLink;
}
public String getTipsDescription() {
return tipsDescription;
}
public void setTipsDescription(String tipsDescription) {
this.tipsDescription = tipsDescription;
}
public String getTipsButton() {
return tipsButton;
}
public void setTipsButton(String tipsButton) {
this.tipsButton = tipsButton;
}
}
I have used this model class to use it in viewpager adapter.
So, I am using a recyclerview and setting data to it. Now I have a problem that I have a viewpager in recycleritem. I want to return the size of viewpager adapter of any element in Home_Model_ViewPager as each element has diff size.
This is what I tried in ViewPagerAdapter:
public class ViewPagerAdapter extends PagerAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
List<Home_Model_ViewPager> totalList;
public ViewPagerAdapter(Context context, List<Home_Model_ViewPager> totalList) {
this.context = context;
this.totalList = totalList;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return totalList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
// Declare Variables
TextView tricksDescription;
Button tricksButton;
View itemView = inflater.inflate(R.layout.viewpager_item, container,
false);
tricksDescription = itemView.findViewById(R.id.xtv_tricks_description);
tricksButton = itemView.findViewById(R.id.tricks_button);
tricksDescription.setText(Html.fromHtml(totalList.get(position).getTipsDescription()));
tricksButton.setText(Html.fromHtml(totalList.get(position).getTipsButton()));
tricksButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
String url = totalList.get(position).getButtonLink();
intent.setData(Uri.parse(url));
startActivity(intent);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
I am using volley to get the values as JSON..
private void Home() {
try {
if (getActivity()!=null)
Commonfunctions.LoadPreferences(getActivity());
System.out.println("Authtoken:" + Commonfunctions.Token_key);
appservice.View_All_Events(Commonfunctions.Token_key, String.valueOf(pagenumber), new Server_Callback() {
#Override
public void onSuccess(String response) {
System.out.println("HOME Response :" + response);
try {
JSONObject signObject = new JSONObject(response);
String resStatus = signObject.getString(AppConstants.STATUS);
String resCode = signObject.getString(AppConstants.CODE);
String resMsg = signObject.getString(AppConstants.MSG);
if (resCode.equals(AppConstants.SUCCESS_CODE)) {
JSONArray allEvents = signObject.getJSONArray("all");
System.out.println("INNER Response :" + allEvents);
for (int i = 0; i < allEvents.length(); i++) {
JSONObject innerObj1 = allEvents.getJSONObject(i);
String backgroundImg = innerObj1.getString("backg_img");
String declinedCount = innerObj1.getString("decli_count");
String acceptedCount = innerObj1.getString("accep_count");
String invitedCount = innerObj1.getString("invi_count");
String messages = innerObj1.getString("i_chat");
String name = innerObj1.getString("name");
String eventTime = innerObj1.getString("duration");
String userPhoto = innerObj1.getString("photo");
JSONArray viewpagerEvents = innerObj1.getJSONArray("action");
for (int u = 0; u < viewpagerEvents.length(); u++) {
JSONObject innerObj3 = viewpagerEvents.getJSONObject(u);
String buttonText = innerObj3.getString("text");
String tipsDesc = innerObj3.getString("action_text");
String buttonLink = innerObj3.getString("button_link");
final Home_Model home_data = new Home_Model(name, messages,invitedCount,declinedCount,acceptedCount,eventTime,
userPhoto,backgroundImg);
data.add(home_data);
final Home_Model_ViewPager home_viewpager = new Home_Model_ViewPager(getContext(),tipsDesc,buttonText, buttonLink);
viewPagerData.add(home_viewpager);
}
}
adapter = new HomeAdapter(getContext(),data);
pagerAdapter = new ViewPagerAdapter(getActivity(), viewPagerData);
home_recycler.setAdapter(adapter);
adapter.notifyDataSetChanged();
if (adapter.getItemCount()==0) {
noeventLayout.setVisibility(View.VISIBLE);
}
else {
noeventLayout.setVisibility(View.GONE);
}
} else if (resCode.equals(AppConstants.UPDATE_CODE)) {
//Version_Update versionUpdate=new Version_Update(SignIn.this,response);
} else {
getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
Commonfunctions.showerrorsnackbar(resMsg, getActivity(), parentLayout);
}
} catch (JSONException e) {
e.printStackTrace();
}
}//on success close
});//server callback closed
} catch (Exception e) {
e.printStackTrace();
}
}
HomeAdapter:
class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.ViewHolder> {
Context context;
List<Home_Model> students;
public HomeAdapter(Context context,List<Home_Model> students) {
this.context = context;
this.students = students;
}
#Override
public HomeAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.event_home_list, viewGroup, false);
return new HomeAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(final HomeAdapter.ViewHolder holder, final int position) {
holder.title.setText(students.get(position).getName());
holder.invited.setText(students.get(position).getInvited());
holder.accepted.setText(students.get(position).getAccept());
holder.declined.setText(students.get(position).getDecline());
holder.eventTime.setText(students.get(position).getEvent_time());
holder.messages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getActivity(),Chat_view.class));
}
});
holder.viewPager.setAdapter(pagerAdapter);
holder.dots = new ImageView[holder.dotsCount];
for (int i = 0; i < holder.dotsCount; i++) {
holder.dots[i] = new ImageView(context);
holder.dots[i].setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_dot_gray ));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
holder.sliderDots.addView(holder.dots[i], params);
}
holder.dots[0].setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_dot_colorprimary));
holder.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for (int i = 0; i < holder.dotsCount; i++) {
holder.dots[i].setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_dot_gray));
}
holder.dots[position].setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_dot_colorprimary));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
if (students.get(position).getMessages().contentEquals("false")) {
holder.status.setVisibility(View.INVISIBLE);
}
else {
holder.status.setVisibility(View.VISIBLE);
}
holder.status.setVisibility(View.INVISIBLE);
try {
Glide.with(getActivity()).load(students.get(position).getProimg()).into(holder.pro_img);
Glide.with(getActivity()).load(students.get(position).getBgimg()).into(holder.card_main);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return students.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView title, messages, invited, accepted, declined, eventTime;
private PorterShapeImageView pro_img;
ImageView card_main, status;
ViewPager viewPager;
LinearLayout sliderDots;
private ImageView[] dots;
private int dotsCount;
public ViewHolder(View itemView) {
super(itemView);
title = itemView.findViewById(R.id.xtv_welcome);
messages = itemView.findViewById(R.id.xtv_message);
invited = itemView.findViewById(R.id.xtv_invited);
accepted = itemView.findViewById(R.id.xtv_accepted);
declined = itemView.findViewById(R.id.xtv_decline);
eventTime = itemView.findViewById(R.id.contact_number);
pro_img = itemView.findViewById(R.id.pro_pic);
card_main = itemView.findViewById(R.id.card_main);
status = itemView.findViewById(R.id.incoming_image);
viewPager = itemView.findViewById(R.id.viewPagerTips);
sliderDots = itemView.findViewById(R.id.sliderDots);
dotsCount = pagerAdapter.getCount();
}
}
}
Please try to make one different array list for your viewpager's adapter:
ArrayList<Home_Model_ViewPager> tempList = new ArrayList<>();
for(int k=0;k<viewpagerData.size();k++){
Home_Model_ViewPager object = viewPagerData.get(k);
if(object.getTripDesc()!=null && object.getTripDesc().length() >0){
tempList.add(object);
}
}
ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(getActivity(), tempList);
home_recycler.setAdapter(adapter);
adapter.notifyDataSetChanged();
I had an ListVew where I have to show the orders List from Database.I have Multiple orders in Mysql Database but only one order is continuously repeating in ListVew.Any help regarding this is Appreciated.
Here is my Adapter Class
public class OrderApprovalAdapter extends ArrayAdapter
{
List list1 = new ArrayList();
Context context;
public OrderApprovalAdapter(#NonNull Context context, #NonNull int Resource)
{
super(context, Resource);
this.context = context;
}
#Override
public void add(#Nullable Object object)
{
super.add(object);
list1.add(object);
}
#Override
public int getCount()
{
return list1.size();
}
#Override
public Object getItem(int position)
{
return list1.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
final OrderApprovalAdapter.ContactHolder contactHolder;
View row;
row = convertView;
if (row == null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.order_approval_format, parent, false);
contactHolder = new ContactHolder();
contactHolder.date = (TextView) row.findViewById(R.id.invoice_date);
contactHolder.orderid = (TextView) row.findViewById(R.id.invoice_no);
contactHolder.shopname = (TextView) row.findViewById(R.id.shop_name);
contactHolder.ownername = (TextView) row.findViewById(R.id.owner_name);
contactHolder.mobile=(TextView) row.findViewById(R.id.mobile_noo);
contactHolder.location=(TextView)row.findViewById(R.id.location);
contactHolder.itemscount=(TextView)row.findViewById(R.id.items);
contactHolder.amount=(TextView)row.findViewById(R.id.total);
contactHolder.Approval=(Button)row.findViewById(R.id.Approve_btn);
contactHolder.Decline=(Button)row.findViewById(R.id.decline_btn);
row.setTag(contactHolder);
} else
{
contactHolder = (ContactHolder) row.getTag();
}
final OrderApprovalDetails contacts = (OrderApprovalDetails) this.getItem(position);
contactHolder.date.setText(contacts.getDate());
contactHolder.orderid.setText(contacts.getOrderid());
contactHolder.shopname.setText(contacts.getShopname());
contactHolder.ownername.setText(contacts.getOwnername());
contactHolder.mobile.setText(contacts.getMobile());
contactHolder.location.setText(contacts.getLocation());
contactHolder.itemscount.setText(contacts.getItemscount());
contactHolder.amount.setText(contacts.getAmount());
contactHolder.Approval.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(context, "Approved", Toast.LENGTH_SHORT).show();
}
});
contactHolder.Decline.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(context, "Decline", Toast.LENGTH_SHORT).show();
}
});
return row;
}
static class ContactHolder
{
TextView date,orderid,shopname,ownername,mobile,location,itemscount,amount;
Button Approval,Decline;
}
}
Retriving Data From Database
class OrdersListBackgroundTask extends AsyncTask<Void,Void,String>
{
#Override
protected void onPreExecute()
{
OrdersList_url="http://10.0.2.2/accounts/OrderForm2.php";
}
#Override
protected String doInBackground(Void... params)
{
try {
URL url=new URL(OrdersList_url);
HttpURLConnection httpURLConnection=
(HttpURLConnection)url.openConnection();
InputStream is= httpURLConnection.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
StringBuilder sb=new StringBuilder();
while ((JSON_STRING4=br.readLine())!=null)
{
sb.append(JSON_STRING4+ "");
}
br.close();
is.close();
httpURLConnection.disconnect();
return sb.toString().trim();
} catch (MalformedURLException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result)
{
//TextView tv=(TextView)findViewById(R.id.tv);
//tv.setText(result);
json_string4=result;
}
}
Sending Through intent to Next Page
public void Orders_List(View v)//Button click
{
if (json_string4==null)
{
Toast.makeText(this, "Get Orders First", Toast.LENGTH_SHORT).show();
}else
{
Intent i1=new Intent(this,OrdersList.class);
i1.putExtra("json_data4",json_string4);
startActivity(i1);
}
}
Usage in MainActivity
json_string4=getIntent().getExtras().getString("json_data4");
listView_Orders=(ListView)findViewById(R.id.listViewOrderlist);
listView_Orders.setItemsCanFocus(true);
search_filter=(EditText)findViewById(R.id.search_et);
orderApprovalAdapter=new
OrderApprovalAdapter(this,R.layout.order_approval_format);
listView_Orders.setAdapter(orderApprovalAdapter);
//listView_Orders.setTextFilterEnabled(true);
try
{
jsonObject=new JSONObject(json_string4);
jsonArray=jsonObject.getJSONArray("orders");
int count=0;
for (int i=0;i<jsonArray.length();i++)
{
JSONObject jo=jsonArray.getJSONObject(i);
date=jo.getString("date");
orderid=jo.getString("orderid");
shopname=jo.getString("shopname");
ownername=jo.getString("ownername");
mobile=jo.getString("mobile");
location=jo.getString("location");
items=jo.getString("items_count");
amount=jo.getString("amount");
OrderApprovalDetails orderApprovalDetails=new OrderApprovalDetails(date,orderid,shopname,ownername,mobile,location,items,amount,Approve,Decline);
orderApprovalAdapter.add(orderApprovalDetails);
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
OrderApprovalDetails Class
public class OrderApprovalDetails
{
public static String
date,orderid,shopname,ownername,mobile,location,itemscount,amount;
public static Button Approval,Decline;
public OrderApprovalDetails(String date,String orderid,String shopname,String ownername,String mobile,String location,String itemscount,String amount,Button Approval,Button Decline)
{
this.setDate(date);
this.setOrderid(orderid);
this.setShopname(shopname);
this.setOwnername(ownername);
this.setMobile(mobile);
this.setLocation(location);
this.setItemscount(itemscount);
this.setAmount(amount);
this.setApproval(Approval);
this.setDecline(Decline);
}
public String getDate()
{
return date;
}
public static Button getApproval() {
return Approval;
}
public static void setApproval(Button approval) {
Approval = approval;
}
public static Button getDecline() {
return Decline;
}
public static void setDecline(Button decline) {
Decline = decline;
}
public void setDate(String date) {
this.date = date;
}
public String getOrderid() {
return orderid;
}
public void setOrderid(String orderid) {
this.orderid = orderid;
}
public String getShopname() {
return shopname;
}
public void setShopname(String shopname) {
this.shopname = shopname;
}
public String getOwnername() {
return ownername;
}
public void setOwnername(String ownername) {
this.ownername = ownername;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getItemscount() {
return itemscount;
}
public void setItemscount(String itemscount) {
this.itemscount = itemscount;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
Don't know where I did Mistake,Please Help me to findout that,Thanks in Advance.
You class members should never be declared static as you have done here -
public class OrderApprovalDetails
{
public static String date,orderid,shopname,ownername,mobile,location,itemscount,amount;
change this to
public class OrderApprovalDetails
{
public String date,orderid,shopname,ownername,mobile,location,itemscount,amount;
I am trying to load data into my recyclerview via url okhttp calls, and I am receiving the following error:
"java.lang.ClassCastException: SearchActivity cannot be cast to SearchForBarbershop$BarbershopRequesterResponse"
Here are the classes.
SearchActivity:
public class SearchActivity extends AppCompatActivity {
private RecyclerAdapter mAdapter;
private RecyclerView mRecyclerView;
private LinearLayoutManager mLinearLayoutManager;
private ArrayList<Barbershop> barbershopList;
private SearchForBarbershop searchForBarbershop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mLinearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
barbershopList = new ArrayList<>();
mAdapter = new RecyclerAdapter(barbershopList);
mRecyclerView.setAdapter(mAdapter);
setRecyclerViewScrollListener();
searchForBarbershop = new SearchForBarbershop(this);
}
#Override
protected void onStart() {
super.onStart();
if (barbershopList.size() == 0) {
requestShop();
}
}
private int getLastVisibleItemPosition() {
return mLinearLayoutManager.findLastVisibleItemPosition();
}
private void setRecyclerViewScrollListener() {
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
int totalItemCount = mRecyclerView.getLayoutManager().getItemCount();
if (!searchForBarbershop.isLoadingData() && totalItemCount == getLastVisibleItemPosition() + 1) {
requestShop();
}
}
});
}
private void requestShop() {
try {
searchForBarbershop.getBarbershop();
} catch (IOException e) {
e.printStackTrace();
}
}
//#Override
public void receivedNewShop(final Barbershop newBarbershop) {
runOnUiThread(new Runnable() {
#Override
public void run() {
barbershopList.add(newBarbershop);
mAdapter.notifyItemInserted(barbershopList.size());
}
});
}
}
SearchForBarbershop:
public class SearchForBarbershop {
public interface BarbershopRequesterResponse {
void receivedNewBarbershop(Barbershop barbershop);
}
private BarbershopRequesterResponse barbershopRequesterResponse;
private OkHttpClient client;
private boolean isLoadingData;
public boolean isLoadingData() { return isLoadingData; }
public SearchForBarbershop (Activity listeningActivity) {
client = new OkHttpClient();
isLoadingData = false;
barbershopRequesterResponse = (BarbershopRequesterResponse) listeningActivity;
}
public void getBarbershop() throws IOException {
String url = "http://pubapi.yp.com/search-api/search/devapi/search?searchloc=30043&term=barbers&format=json&sort=distance&radius=50&listingcount=20&key=gmj3x7mhsh";
Request request = new Request.Builder().url(url).build();
isLoadingData = true;
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
isLoadingData = false;
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
JSONObject object = new JSONObject(response.body().string());
Barbershop receivedShop = new Barbershop(object);
barbershopRequesterResponse.receivedNewBarbershop(receivedShop);
isLoadingData = false;
} catch (JSONException e) {
isLoadingData = false;
e.printStackTrace();
}
}
});
}
}
Barbershop:
public class Barbershop{
private String name;
private String city;
public Barbershop(JSONObject barbershopJSON) {
try {
JSONArray businessArray = barbershopJSON.getJSONObject("searchResult").getJSONObject("searchListings").getJSONArray("searchListing");
for(int i = 0; i < businessArray.length(); i++) {
//Parse JSON and assign to variables
JSONObject business_object_1 = businessArray.getJSONObject(i);
String primaryc = business_object_1.getString("primaryCategory");
//Check to make sure the main category is "Barbers"
if((primaryc).equals("Barbers")) {
name = business_object_1.getString("businessName");
city = business_object_1.getString("city");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public String getCity() {
return city;
}
public String getName() {
return name;
}
}
RecyclerAdapter:
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ShopHolder> {
private ArrayList<Barbershop> mbarbershops;
public RecyclerAdapter(ArrayList<Barbershop> barbershops) {
mbarbershops = barbershops;
}
#Override
public RecyclerAdapter.ShopHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View inflatedView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cardview_barber_search, parent, false);
return new ShopHolder(inflatedView);
}
#Override
public void onBindViewHolder(RecyclerAdapter.ShopHolder holder, int position) {
Barbershop itemBarbershop = mbarbershops.get(position);
holder.bindShop(itemBarbershop);
}
#Override
public int getItemCount() {
return 0;
}
public static class ShopHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView mName;
private TextView mCity;
public ShopHolder(View view) {
super(view);
mName = (TextView) view.findViewById(R.id.textViewName);
mCity = (TextView) view.findViewById(R.id.textViewCity);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
}
public void bindShop(Barbershop barbershop) {
mName.setText(barbershop.getName());
mCity.setText(barbershop.getCity());
}
}
}
It can't be cast because it doesn't implement that interface. Your commented-out #override statement should be a clue for you here.
Change it to:
public class SearchActivity extends AppCompatActivity
implements SearchForBarbershop.BarbershopRequesterResponse {
....
And don't forget to remove the comment for method you implemented:
#Override
public void receivedNewShop(final Barbershop newBarbershop) {
....
I think you need change constructor SearchForBarbershop
BarbershopRequesterResponse listener;
Context context
public SearchForBarbershop (Context context,BarbershopRequesterResponse listener) {
client = new OkHttpClient();
isLoadingData = false;
this.context = context;
this.listener = listener;
}
And change in SearchActivity
searchForBarbershop = new SearchForBarbershop(SearchActivity.this, this);
In my application i am using Custom adapter ans showing the service data to list view. Every thing works fine for me but i want to sort the list view items based on "fare" condition.
Any one help me how to sort my list view based on "fare" (lowest to highest)
My code:
BusData.java :
package com.reloadapp.reload.data;
/**
* Created by user1 on 5/21/2015.
*/
public class BusData
{
private String routescheduleid;
private String companyname;
private String companyid;
private String deptime;
private String arrtime;
private int fare;
private String buslabel;
private String avaliableseats;
private String bustypename;
private String difftime;
boolean ac,non_ac,sleeper,non_slepeer;
private String pickuproutescheduleid;
private String pickupname;
public String getDropoffname() {
return Dropoffname;
}
public void setDropoffname(String dropoffname) {
Dropoffname = dropoffname;
}
public boolean getac() {
return ac;
}
public void setac(boolean ac) {
this.ac = ac;
}
public boolean getnon_ac() {
return non_ac;
}
public void setnon_ac(boolean non_ac) {
this.non_ac = non_ac;
}
public boolean getsleeper() {
return sleeper;
}
public void setsleeper(boolean sleeper) {
this.sleeper = sleeper;
}
public boolean getnon_slepeer() {
return non_slepeer;
}
public void setnon_slepeer(boolean non_slepeer) {
this.non_slepeer = non_slepeer;
}
private String Dropoffname;
public BusData()
{
}
public String getPickuproutescheduleid() {
return pickuproutescheduleid;
}
public void setPickuproutescheduleid(String pickuproutescheduleid) {
this.pickuproutescheduleid = pickuproutescheduleid;
}
public String getPickupname() {
return pickupname;
}
public void setPickupname(String pickupname) {
this.pickupname = pickupname;
}
public String getDifftime() {
return difftime;
}
public void setDifftime(String difftime) {
this.difftime = difftime;
}
public BusData(String routescheduleid,String companyname,String companyid,String deptime,String arrtime,int fare,String buslabel,String avaliableseats,String bustypename,String difftime)
{
this.routescheduleid=routescheduleid;
this.companyname=companyname;
this.companyid=companyid;
this.deptime=deptime;
this.arrtime=arrtime;
this.fare=fare;
this.buslabel=buslabel;
this.avaliableseats=avaliableseats;
this.bustypename=bustypename;
this.difftime=difftime;
}
public String getRoutescheduleid() {
return routescheduleid;
}
public void setRoutescheduleid(String routescheduleid) {
this.routescheduleid = routescheduleid;
}
public String getCompanyname() {
return companyname;
}
public void setCompanyname(String companyname) {
this.companyname = companyname;
}
public String getCompanyid() {
return companyid;
}
public void setCompanyid(String companyid) {
this.companyid = companyid;
}
public String getDeptime() {
return deptime;
}
public void setDeptime(String deptime) {
this.deptime = deptime;
}
public String getArrtime() {
return arrtime;
}
public void setArrtime(String arrtime) {
this.arrtime = arrtime;
}
public int getFare() {
return fare;
}
public void setFare(int fare) {
this.fare = fare;
}
public String getBuslabel() {
return buslabel;
}
public void setBuslabel(String buslabel) {
this.buslabel = buslabel;
}
public String getAvaliableseats() {
return avaliableseats;
}
public void setAvaliableseats(String avaliableseats) {
this.avaliableseats = avaliableseats;
}
public String getBustypename() {
return bustypename;
}
public void setBustypename(String bustypename) {
this.bustypename = bustypename;
}
}
BusAdapter.java:
public class BusDataAdapter extends BaseAdapter {
ArrayList<BusData> bpData;
private ArrayList<BusData> arraylist;
private Activity activity;
ProgressDialog mProgressDialog;
public static String journey_bus;
public static String rid;
String travelname, travetime = null;
private LayoutInflater inflater;
//SearchActivity obj=new SearchActivity(journey_bus);
public BusDataAdapter(Activity activity, ArrayList<BusData> bpData) {
// TODO Auto-generated constructor stub
this.activity = activity;
this.bpData = bpData;
mProgressDialog = new ProgressDialog(activity);
inflater = LayoutInflater.from(activity);
}
public void setJourneyBus(String journey_bus) {
this.journey_bus = journey_bus;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return bpData.size();
}
#Override
public Object getItem(int location) {
// TODO Auto-generated method stub
return location;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.buslistviewitems, null);
Typeface custom_bold = Typeface.createFromAsset(activity.getAssets(),
"fonts/SourceSansPro_Semibold.ttf");
Typeface custom_regular = Typeface.createFromAsset(activity.getAssets(),
"fonts/SourceSansPro_Light.ttf");
viewHolder.deptime = (TextView) convertView
.findViewById(R.id.deptime);
viewHolder.difftime = (TextView) convertView
.findViewById(R.id.difftime);
viewHolder.busfare = (TextView) convertView
.findViewById(R.id.busfare);
viewHolder.buslabel = (TextView) convertView
.findViewById(R.id.buslabel);
viewHolder.routeid = (TextView) convertView
.findViewById(R.id.routeid);
viewHolder.bustypename = (TextView) convertView
.findViewById(R.id.bustypename);
viewHolder.availableseat = (TextView) convertView
.findViewById(R.id.avaliableseats);
viewHolder.businfo = (LinearLayout) convertView.findViewById(R.id.businfo);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.deptime.setText(bpData.get(position).getDeptime() + "-" + bpData.get(position).getArrtime());
// travetime = bpData.get(position).getDeptime() + "-" + bpData.get(position).getArrtime();
viewHolder.difftime.setText(bpData.get(position).getDifftime());
viewHolder.busfare.setText(bpData.get(position).getFare());
viewHolder.buslabel.setText(bpData.get(position).getBuslabel());
viewHolder.routeid.setText(bpData.get(position).getRoutescheduleid());
viewHolder.bustypename.setText(bpData.get(position).getBustypename());
// travelname = bpData.get(position).getBuslabel();
viewHolder.availableseat.setText(bpData.get(position).getAvaliableseats() + "Seats");
if (bpData.get(position).getAvaliableseats().equalsIgnoreCase("0")) {
viewHolder.availableseat.setText("Sold Out");
} else {
viewHolder.availableseat.setText(bpData.get(position).getAvaliableseats() + "Seats");
}
class ViewHolder {
TextView difftime, deptime, busfare, buslabel, routeid, bustypename, availableseat;
LinearLayout businfo;
//Button businfo;
}}
FromtoActivity.java:
public class FromtoActivity extends AppCompatActivity {
ArrayList<BusData> bdata = new ArrayList<BusData>();
ArrayList<BusData> filter_list = new ArrayList<BusData>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.fromto);
Intent intent = getIntent();
json_object = intent.getStringExtra("json_objcet");
busdata();
}
public void busdata() {
try {
bdata.clear();
travel_list.clear();
filter_list.clear();
JSONObject result = new JSONObject(json_object);
JSONObject Data = result.getJSONObject("Data");
routearray = Data.getJSONArray("Route");
for (int i = 0; i < routearray.length(); i++) {
// String companyid = routearray.getJSONObject(i).getString("CompanyId");
CompanyName = routearray.getJSONObject(i).getString("CompanyName");
String deptime = routearray.getJSONObject(i).getString("DepTime");
routeScheduleId = routearray.getJSONObject(i).getString("RouteScheduleId");
String arrtime = routearray.getJSONObject(i).getString("ArrTime");
/* String dtDeparture = "2014-12-15T13:30:00";
String dtArrival = "2014-12-15T23:00:00";*/
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date dateDeparture = format.parse(deptime);
Date dateArrival = format.parse(arrtime);
dateArrival.compareTo(dateDeparture);
long diff = dateArrival.getTime() - dateDeparture.getTime();
long arrivaltime = dateArrival.getTime();
arrivaldate = new SimpleDateFormat("hh:mm a").format(new Date(arrivaltime));
long departuretime = dateDeparture.getTime();
depardate = new SimpleDateFormat("hh:mm a").format(new Date(departuretime));
/* Log.v("TAG_realarrtime",""+arrivaldate);
Log.v("TAG_realdeptime",""+depardate);
*/
long hours = TimeUnit.MILLISECONDS.toHours(diff);
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff) - hours * 60;
// System.out.println(hours + "." + minutes + "hrs");
msg = hours + "." + minutes + "hrs";
fare = routearray.getJSONObject(i).getInt("Fare");
hasac = routearray.getJSONObject(i).getString("HasAC");
hasnac = routearray.getJSONObject(i).getString("HasNAC");
hasseater = routearray.getJSONObject(i).getString("HasSeater");
hassleeper = routearray.getJSONObject(i).getString("HasSleeper");
String isvolvo = routearray.getJSONObject(i).getString("IsVolvo");
buslabel = routearray.getJSONObject(i).getString("BusLabel");
avaliableseats = routearray.getJSONObject(i).getString("AvailableSeats");
bustypename = routearray.getJSONObject(i).getString("BusTypeName");
BusData bs = new BusData();
// bs.setCompanyname(CompanyName);
//bs.setCompanyid(companyid);
bs.setFare(fare);
bs.setBuslabel(CompanyName);
bs.setBustypename(bustypename);
bs.setAvaliableseats(avaliableseats);
bs.setArrtime(arrivaldate);
bs.setDeptime(depardate);
bs.setDifftime(msg);
bs.setac(routearray.getJSONObject(i).getBoolean("HasAC"));
bs.setnon_ac(routearray.getJSONObject(i).getBoolean("HasNAC"));
bs.setsleeper(routearray.getJSONObject(i).getBoolean("HasSleeper"));
bs.setnon_slepeer(routearray.getJSONObject(i).getBoolean("HasSeater"));
bs.setRoutescheduleid(routeScheduleId);
bdata.add(bs);
if (!travel_list.contains(bdata.get(i).getBuslabel()))
travel_list.add(bdata.get(i).getBuslabel());
}
adapter = new BusDataAdapter(this, bdata);
fromto.setAdapter(adapter);
adapter.setJourneyBus(date_bus);
filter_list.addAll(bdata);
adapter = new BusDataAdapter(this, filter_list);
fromto.setAdapter(adapter);
/* adapter.setrouteid(routeScheduleId);
*/
} catch (Exception e) {
e.printStackTrace();
}
}
}
You should sort the list before call adapter to list the data.
Collections.sort(bdata, new Comparator<BusData>() {
public int compare(BusData o1, BusData o2) {
return o2.getFare().compareTo(o1.getFare());
}
});
for(BusData busData:bdata)
{
Log.e("Fare : ",busData.getFare());
}
After sorting completed call Adapter to list the data:
adapter = new BusDataAdapter(this, bdata);
fromto.setAdapter(adapter);
adapter.setJourneyBus(date_bus);
filter_list.addAll(bdata);
adapter = new BusDataAdapter(this, filter_list);
fromto.setAdapter(adapter);
You can use Collections.sort method for this..
Do like this...
Collections.sort(filterlist, new Comparator<bData>() {
#Override
public int compare(bData lhs, bData rhs) {
return (lhs.getFair() > rhs.getFair()) ? -1 : (lhs.getFair() > rhs.getFair()) ? 1 : 0;
}
});
You need to use comparator api in android.
Comparator<BusData> comparator=new Comparator<BusData>() {
#Override
public int compare(final BusData lhs, final BusData rhs) {
return lhs.getFare().equals(rhs.getFare());
}
};
Collections.sort(busDataList,comparator);
then your list will be sorted.
You need to give already sorted collection of buses to your adapter. Adapter shouldn't be responsible for sorting and ListView as well.
Try this:
Collections.sort(bdata, new Comparator<BusData>() {
#Override
public int compare(BusData lhs, BusData rhs) {
return lhs.getFare() > rhs.getFare();
}
});
You can use the Comparator and sort the list
class FareComparator implements Comparator{
public int Compare(Object o1,Object o2){
BusData s1=(BusData)o1;
BusData s2=(BusData)o2;
if(s1.fare==s2.fare)
return 0;
else if(s1.fare>s2.fare)
return -1;
else
return 1;
}
}
and use
Collections.sort(bdata,new FareComparator());
before the
adapter = new BusDataAdapter(this, bdata);