Here is the code of my fragment where i am accesing a web service in asynctask to fetch data and display in list also i am lazy loading the images..When the fragment is created for the first time the output is correct it displays 7 items in the list which it should , the problem is when the fragment is recreated after being destroyed the data is repeated i.e if it started for the second time the list shows 14 items (7 from earlier and 7 are again fetched) and this happens everytime it recreates , the no. of items in list is 7 more than the previous.. Although in On destroy i cleared the data of the adapter and the adapter.getCount() shows 0 but still this problem exists.
public class ServiceCarListFragment extends Fragment {
private String url;
private ArrayList<CarDetail> carDetailList = new ArrayList<CarDetail>();
private CarListAdapter adapter;
private ListView mList ;
private ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Log.d("Services", "On Create");
url = getActivity().getIntent().getStringExtra("url");
adapter = new CarListAdapter(getActivity() , carDetailList);
new DownloadCarDetail().execute(url);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
Log.d("Services", "On CreateView");
View v = inflater.inflate(R.layout.fragment_service_car_list, container,false);
mList = (ListView)v.findViewById(R.id.list);
mList.setAdapter(adapter);
return v;
}
class DownloadCarDetail extends AsyncTask<String, String, ArrayList<CarDetail>>{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = ProgressDialog.show(getActivity(), null, "Loading...",true);
}
#Override
protected ArrayList<CarDetail> doInBackground(String... params) {
// TODO Auto-generated method stub
ArrayList<CarDetail> carDetailList = JsonParser.parseJson(params[0]);
return carDetailList;
}
#Override
protected void onPostExecute(ArrayList<CarDetail> carDetailList) {
// TODO Auto-generated method stub
//ServiceCarListFragment.this.carDetailList = carDetailList;
//adapter = new CarListAdapter(getActivity(),ServiceCarListFragment.this.carDetailList);
//mList.setAdapter(adapter);
progressDialog.dismiss();
ServiceCarListFragment.this.carDetailList.addAll(carDetailList);
adapter.notifyDataSetChanged();
for (CarDetail car : carDetailList) {
// START LOADING IMAGES FOR EACH STUDENT
car.loadImage(adapter);
}
}
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
carDetailList.clear();
adapter.notifyDataSetChanged();
Log.d("Services", String.valueOf(adapter.getCount()));
}
#Override
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
Log.d("Services", "On DestroyView");
}
#Override
public void onDetach() {
// TODO Auto-generated method stub
super.onDetach();
Log.d("Services", "On Detach");
}
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
Log.d("Services", "On Attach");
}
}
This is the custom adapter i am using
public class CarListAdapter extends BaseAdapter {
private ArrayList<CarDetail> items = new ArrayList<CarDetail>();
private Context context;
public CarListAdapter(Context context , ArrayList<CarDetail> items) {
super();
this.context = context;
this.items = items;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return items.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Log.d("Inside", "GetView");
LayoutInflater mInflater = (LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
ViewHolder holder = null;
CarDetail car = items.get(position);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.car_list_row, parent , false);
holder = new ViewHolder();
holder.tvCarName = (TextView) convertView.findViewById(R.id.tvCarName);
holder.tvDailyPriceValue = (TextView) convertView.findViewById(R.id.tvWeeklyPriceValue);
holder.tvWeeklyPriceValue = (TextView) convertView.findViewById(R.id.tvWeeklyPriceValue);
holder.imgCar = (ImageView) convertView.findViewById(R.id.imgCar);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvCarName.setText(car.getCarName());
if (car.getImage() != null) {
holder.imgCar.setImageBitmap(car.getImage());
} else {
// MY DEFAULT IMAGE
holder.imgCar.setImageResource(R.drawable.ic_action_call);
}
return convertView;
}
static class ViewHolder {
TextView tvCarName;
TextView tvDailyPriceValue;
TextView tvWeeklyPriceValue;
ImageView imgCar;
}
}
This is the model class
public class CarDetail {
private String carId;
private String carName;
private String imageUrl;
private String thumbUrl;
private String dailyPrice;
private String weeklyPrice;
private String weekendPrice;
private String deposit;
private String minimumAge;
private String color;
private String make;
private String location;
private String bodyType;
private String fuelType;
private String transmission;
private String carType;
private String model;
private String description;
private Bitmap image;
private Bitmap thumbImage;
private CarListAdapter carAdapter;
public CarDetail() {
super();
// TODO Auto-generated constructor stub
}
public CarDetail(String carId, String carName, String imageUrl,
String thumbUrl, String dailyPrice, String weeklyPrice,
String weekendPrice, String deposit, String minimumAge,
String color, String make, String location, String bodyType,
String fuelType, String transmission, String carType, String model,
String description) {
super();
this.carId = carId;
this.carName = carName;
this.imageUrl = imageUrl;
this.thumbUrl = thumbUrl;
this.dailyPrice = dailyPrice;
this.weeklyPrice = weeklyPrice;
this.weekendPrice = weekendPrice;
this.deposit = deposit;
this.minimumAge = minimumAge;
this.color = color;
this.make = make;
this.location = location;
this.bodyType = bodyType;
this.fuelType = fuelType;
this.transmission = transmission;
this.carType = carType;
this.model = model;
this.description = description;
// TO BE LOADED LATER - OR CAN SET TO A DEFAULT IMAGE
this.image = null;
this.thumbImage = null;
}
public String getCarId() {
return carId;
}
public void setCarId(String carId) {
this.carId = carId;
}
public String getCarName() {
return carName;
}
public void setCarName(String carName) {
this.carName = carName;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getThumbUrl() {
return thumbUrl;
}
public void setThumbUrl(String thumbUrl) {
this.thumbUrl = thumbUrl;
}
public String getDailyPrice() {
return dailyPrice;
}
public void setDailyPrice(String dailyPrice) {
this.dailyPrice = dailyPrice;
}
public String getWeeklyPrice() {
return weeklyPrice;
}
public void setWeeklyPrice(String weeklyPrice) {
this.weeklyPrice = weeklyPrice;
}
public String getWeekendPrice() {
return weekendPrice;
}
public void setWeekendPrice(String weekendPrice) {
this.weekendPrice = weekendPrice;
}
public String getDeposit() {
return deposit;
}
public void setDeposit(String deposit) {
this.deposit = deposit;
}
public String getMinimumAge() {
return minimumAge;
}
public void setMinimumAge(String minimumAge) {
this.minimumAge = minimumAge;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getBodyType() {
return bodyType;
}
public void setBodyType(String bodyType) {
this.bodyType = bodyType;
}
public String getFuelType() {
return fuelType;
}
public void setFuelType(String fuelType) {
this.fuelType = fuelType;
}
public String getTransmission() {
return transmission;
}
public void setTransmission(String transmission) {
this.transmission = transmission;
}
public String getCarType() {
return carType;
}
public void setCarType(String carType) {
this.carType = carType;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Bitmap getImage() {
return image;
}
public void setImage(Bitmap image) {
this.image = image;
}
public Bitmap getThumbImage() {
return thumbImage;
}
public void setThumbImage(Bitmap thumbImage) {
this.thumbImage = thumbImage;
}
public void loadImage(CarListAdapter carAdapter) {
// HOLD A REFERENCE TO THE ADAPTER
this.carAdapter = carAdapter;
if (thumbUrl != null && !thumbUrl.equals("")) {
new ImageLoadTask().execute(thumbUrl);
}
}
// ASYNC TASK TO AVOID CHOKING UP UI THREAD
private class ImageLoadTask extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
Log.i("ImageLoadTask", "Loading image...");
}
// PARAM[0] IS IMG URL
protected Bitmap doInBackground(String... param) {
Log.i("ImageLoadTask", "Attempting to load image URL: " + param[0]);
try {
Bitmap b = JsonParser.downloadBitmap(param[0]);
return b;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
protected void onProgressUpdate(String... progress) {
// NO OP
}
protected void onPostExecute(Bitmap ret) {
if (ret != null) {
Log.i("ImageLoadTask", "Successfully loaded " + carName + " image");
image = ret;
if (carAdapter != null) {
// WHEN IMAGE IS LOADED NOTIFY THE ADAPTER
carAdapter.notifyDataSetChanged();
}
} else {
Log.e("ImageLoadTask", "Failed to load " + carName + " image");
}
}
}
You need to clear ArrayList Data just before your next call of Async Method.
In your case it would be carDetailLis.clear() new DownloadCarDetail().execute(url); or just check the flow and clear it.
I suggest to you to modify
ServiceCarListFragment.this.carDetailList.addAll(carDetailList);
in
ServiceCarListFragment.this.carDetailList = new ArrayList...
carDetailList.addAll
And you should verify if the length of carDetailList is the same after several calls to the server.
Related
i wont to display the list of chats of clients.the data is come from json,
the last message of chat is display on chat.but it displays all message of all clients in list.like
here is my ListMessage.class activity
public class ListMessage extends AppCompatActivity implements View.OnClickListener {
ImageButton btnFooter_Home, btnFooter_Message, btnFooter_Notification, btnFooter_More;
EditText textUser;
List<Msg_data> msgList;
ListView lv;
String uri = "http://staging.talentslist.com/api/user/23/chat";
LinearLayout linear_Home, linear_Message, linear_Notification, linear_More;
GlobalClass myGlog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_message);
myGlog = new GlobalClass(getApplicationContext());
setFooter();
lv = (ListView) findViewById(R.id.listView);
textUser = (EditText) findViewById(R.id.textUser);
// textUser.isFocused()
boolean inConnected = myGlog.isNetworkConnected();
if (inConnected) {
requestData(uri);
}
}
public void requestData(String uri) {
StringRequest request = new StringRequest(uri,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
msgList = MsgJSONParser.parseData(response);
MsgAdapter adapter = new MsgAdapter(ListMessage.this, msgList);
lv.setAdapter(adapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ListMessage.this, error.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
}
}
MsgAdapter.java class
public class MsgAdapter extends BaseAdapter{
private Context context;
private List<Msg_data> nList;
private LayoutInflater inflater = null;
private LruCache<Integer, Bitmap> imageCache;
private RequestQueue queue;
String isread;
public MsgAdapter(Context context, List<Msg_data> list) {
this.context = context;
this.nList = list;
inflater = LayoutInflater.from(context);
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
imageCache = new LruCache<>(cacheSize);
queue = Volley.newRequestQueue(context);
}
public class ViewHolder {
TextView __isread;
TextView _username;
TextView _detais;
TextView _time;
ImageView _image;
}
#Override
public int getCount() {
return nList.size();
}
#Override
public Object getItem(int position) {
return nList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
final Msg_data msg = nList.get(position);
final ViewHolder holder;
isread = msg.getIs_read();
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_notification, null);
if (isread.equals("0")) {
convertView.setBackgroundColor(Color.parseColor("#009999"));
}
holder = new ViewHolder();
holder._username = (TextView) convertView.findViewById(R.id.tvtitle);
holder._detais = (TextView) convertView.findViewById(R.id.tvdesc);
holder.__isread = (TextView) convertView.findViewById(R.id.tvplateform);
holder._time = (TextView) convertView.findViewById(R.id.createdTime);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder._username.setText(msg.getUser_name().toString());
holder._detais.setText(msg.getMessage().toString());
holder._time.setText(msg.getCreated_at().toString());
// holder.__isread.setText(notifi.getIs_read().toString());
holder._image = (ImageView) convertView.findViewById(R.id.gameImage);
Glide.with(context)
.load(msg.getImage_link().toString()) // Set image url
.diskCacheStrategy(DiskCacheStrategy.ALL) // Cache for image
.into(holder._image);
return convertView;
}
}
Msg_data.java class
public class Msg_data {
public int id;
public String user_id;
public String user_name;
public String message;
public String is_read;
public String image_link;
public String created_at;
public String from;
public String to;
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getIs_read() {
return is_read;
}
public void setIs_read(String is_read) {
this.is_read = is_read;
}
public String getImage_link() {
return image_link;
}
public void setImage_link(String image_link) {
this.image_link = image_link;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public Msg_data() {
}
public Msg_data(int id) {
this.id = id;
}
}
MsgJSONParser.java class
public class MsgJSONParser {
static List<Msg_data> notiList;
public static List<Msg_data> parseData(String content) {
JSONArray noti_arry = null;
Msg_data noti = null;
try {
JSONObject jsonObject = new JSONObject(content);
noti_arry = jsonObject.getJSONArray("data");
notiList = new ArrayList<>();
for (int i = 0; i < noti_arry.length(); i++) {
JSONObject obj = noti_arry.getJSONObject(i);
//JSONObject obj = noti_arry.getJSONObject(i);
noti = new Msg_data();
noti.setId(obj.getInt("id"));
noti.setMessage(obj.getString("message"));
noti.setUser_name(obj.getString("user_name"));
noti.setFrom(obj.getString("from"));
noti.setTo(obj.getString("to"));
noti.setCreated_at(obj.getString("created_at"));
noti.setImage_link(obj.getString("image_link"));
noti.setIs_read(obj.getString("is_read"));
notiList.add(noti);
}
return notiList;
} catch (JSONException ex) {
ex.printStackTrace();
return null;
}
}
}
please give me some idea what to do and how to do
i guess, you should replace
msgList = MsgJSONParser.parseData(response);
MsgAdapter adapter = new MsgAdapter(ListMessage.this, msgList);
with
msgList = MsgJSONParser.parseData(response);
ArrayList<Msg_data> userList=new ArrayList();
for (int i=0;i<msgList.size();i++){
if (!userList.contains(msgList.get(i)))
userList.add(msgList.get(i));
else {
int index=userList.indexOf(msgList.get(i));
if (userList.get(index).compareTo(msgList.get(i))>0)
userList.add(msgList.get(i));
}
}
MsgAdapter adapter = new MsgAdapter(ListMessage.this, userList);`
and implement Comparable and override equals method in your Msg_data class
public class Msg_data implements Comparable {
public int id;
public String user_id;
public String user_name;
public String message;
public String is_read;
public String image_link;
public String created_at;
public String from;
public String to;
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getIs_read() {
return is_read;
}
public void setIs_read(String is_read) {
this.is_read = is_read;
}
public String getImage_link() {
return image_link;
}
public void setImage_link(String image_link) {
this.image_link = image_link;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public Msg_data() {
}
public Msg_data(int id) {
this.id = id;
}
#Override
public boolean equals(Object obj) {
try
{
return (this.getUser_id().equals(( (Msg_data)obj).getUser_id()));
}
catch(NullPointerException e){
return false;
}
}
#Override
public int compareTo(#NonNull Object o) {
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("your pattern here");
try {
Date date=simpleDateFormat.parse(created_at);
Date dateOtherObject=simpleDateFormat.parse(((Msg_data)o).getCreated_at());
return date.compareTo(dateOtherObject);
}
catch (ParseException e){
return -1;
}
}
something like this:) Dont forget replace simple date format in compare method
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;
1- MainActivity:
public class MainActivity extends AppCompatActivity {
private List<String> mListItems = Arrays.asList("Hamaki","Amr Diab");
private ArtistsAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView)findViewById(R.id.Artist_list_view);
mAdapter = new ArtistsAdapter(this, mListItems);
listView.setAdapter(mAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this,SoundActivity.class);
intent.putExtra("Artist", mListItems.get(position));
startActivity(intent);
}
});
}
}
2-Sound Activity:
public class SoundActivity extends AppCompatActivity {
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sound);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, new SoundFragment()).commit();
}
}
3-Sound Fragment:
public class SoundFragment extends Fragment {
static SCTrackAdapter mAdapter;
static DatabaseReference db;
static FirebaseHelper helper;
private TextView mSelectedTrackTitle;
static ArrayList<Music> mTracks = new ArrayList<>();
static MediaPlayer mMediaPlayer;
private ImageView mPlayerControl;
static String Artist;
static ListView listView;
int currentTrack;
private static String fileName;
public SoundFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
new Fetchtracks().execute();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_sound, container, false);
Intent intent = getActivity().getIntent();
if (intent != null) {
Artist = intent.getStringExtra("Artist");
}
listView = (ListView) rootView.findViewById(R.id.track_list_view);
mAdapter = new SCTrackAdapter(getActivity(), mTracks);
listView.setAdapter(mAdapter);
return rootView;
}
4- STrack Adapter:
public class SCTrackAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<Music> mTracks;
public SCTrackAdapter(Context context, ArrayList<Music> tracks) {
mContext = context;
mTracks = tracks;
}
public void update_tracks(ArrayList<Music> list)
{
mTracks.clear();
mTracks.addAll(list);
}
#Override
public int getCount() {
return mTracks.size();
}
#Override
public Music getItem(int position) {
return mTracks.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.track_list_row, parent, false);
holder = new ViewHolder();
holder.titleTextView = (TextView) convertView.findViewById(R.id.track_title);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.titleTextView.setText(mTracks.get(position).getName());
return convertView;
}
static class ViewHolder {
TextView titleTextView;
}
}
5- Fetchtracks:
public class Fetchtracks extends AsyncTask<Void, Void, ArrayList<Music>> {
#Override
protected ArrayList<Music> doInBackground(Void... voids) {
db = FirebaseDatabase.getInstance().getReference().child(Artist);
helper = new FirebaseHelper(db);
mTracks.addAll(helper.retrieve());
Log.e("doInBackground: ",helper.retrieve()+"");
return mTracks;
}
#Override
protected void onPostExecute(ArrayList<Music> list) {
super.onPostExecute(list);
Log.e("doInBackground: ",list.size()+"");
mAdapter.update_tracks(list);
mAdapter.notifyDataSetChanged();
}
}
6- FirebaseHelper:
public class FirebaseHelper {
DatabaseReference db;
Boolean saved=null;
ArrayList<Music> A = new ArrayList<>();
public FirebaseHelper(DatabaseReference db) {
this.db = db;
}
//WRITE
public Boolean save(Music m)
{
if(m==null)
{
saved=false;
}else
{
try
{
// db.child(Artist).push().setValue(m);
saved=true;
}catch (DatabaseException e)
{
e.printStackTrace();
saved=false;
}
}
return saved;
}
//READ
public ArrayList<Music> retrieve()
{
A.clear();
db.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.e("onChildAdded: ", "1");
fetchData(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Log.e("onChildAdded: ", "2");
fetchData(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
// Log.e("onChildAdded: ", "3");
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
// Log.e("onChildAdded: ", "4");
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Log.e("onChildAdded: ", "5");
}
});
return A;
}
private void fetchData(DataSnapshot dataSnapshot)
{
Music m=new Music();
m.setName(dataSnapshot.child("name").getValue().toString());
m.setUrl(dataSnapshot.child("url").getValue().toString());
A.add(m);
// SoundFragment.mTracks.add(m);
// Log.e("onFetch: ", SoundFragment.mTracks.size()+"");
}
}
7- Music:
public class Music {
String name;
String url;
public Music() {
}
public void setName(String name) {
this.name = name;
}
public void setUrl(String url) {
this.url = url;
}
public String getName() {
return name;
}
public String getURL() {
return url;
}
}
no need to call this in onPostExecute() as it is only set
listView.setAdapter(mAdapter);
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);
I put a limit of 15 records to be displayed in my listview. The 15 records successfully displayed but when i clicked on load more button, it add the previous 15 records and the new records too. Here is my async task where more records is being added. I use articlesAdapter.notifyDataSetChanged(); set too but the issue remains. i believe it has something to do with articlesFiltered.size()/15)+1.
public class ActusScreen extends BaseActivity implements OnClickListener {
private DisplayImageOptions options;
ImageLoader imageLoader;
String link;
//...
final int NONE=0;
final int THEME=1;
final int SEARCH=2;
final int THEME_TO_SEARCH=3;
final int SEARCH_RESULTS=4;
final int THEME_TO_SEARCH_RESULTS=5;
int MODE=NONE;
public ArrayList<Article> articles;
public ArrayList<Article> articlesFiltered;
public ArrayList<Theme> themes;
public ArrayList<Theme> themeFiltered;
public static int titleIndex=0;
static boolean original_view = false;
RelativeLayout adLayout;
ListView themesList;
RelativeLayout searchLayout;
EditText searchField;
Button back, theme;
StringBuilder builder;
ScrollView scrollme;
ThemesAdapter themeAdapter;
ArticlesAdapter articlesAdapter;
TextView header_text;
ActusScreen context;
ProgressDialog pd;
ImageView image_actus;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actus);
context=this;
back=(Button)findViewById(R.id.envoye);
back.setOnClickListener(this);
back.setVisibility(View.GONE);
theme=(Button)findViewById(R.id.theme);
theme.setOnClickListener(this);
Button search=(Button)findViewById(R.id.search);
search.setOnClickListener(this);
header_text = (TextView)findViewById(R.id.text_titre);
header_text.setText(getResources().getText(R.string.actus).toString());
adLayout=(RelativeLayout)findViewById(R.id.adLayout);
themeAdapter=new ThemesAdapter(this);
themesList=(ListView)findViewById(R.id.themesList);
themesList.setAdapter(themeAdapter);
themesList.setVisibility(View.GONE);
SelectedArticle.mtypo=1;
articlesAdapter=new ArticlesAdapter(this);
ListView articlesList=(ListView)findViewById(R.id.articlesList);
articlesList.setAdapter(articlesAdapter);
searchLayout=(RelativeLayout)findViewById(R.id.searchLayout);
searchLayout.setVisibility(View.GONE);
searchField=(EditText)findViewById(R.id.keyword);
Button valid=(Button)findViewById(R.id.valid);
valid.setOnClickListener(this);
new GetAllArticlesTask().execute();
image_actus = (ImageView)findViewById(R.id.image);
image_actus.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = link;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
options = new DisplayImageOptions.Builder()
// .showStubImage(R.drawable.ic_launcher)
.displayer(new RoundedBitmapDisplayer(3))
.cacheInMemory()
.cacheOnDisc()
.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(getApplicationContext()));
new backTask().execute("");
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
//FavoriteScreen.flagx=1;
super.onStart();
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.envoye:
back();
break;
case R.id.theme:
if(themesList.getVisibility()==View.VISIBLE)
themesList.setVisibility(View.GONE);
else
themesList.setVisibility(View.VISIBLE);
break;
case R.id.search:
search();
break;
case R.id.valid:
searchLayout.setVisibility(View.GONE);
if(MODE==SEARCH)
MODE=SEARCH_RESULTS;
else
MODE=THEME_TO_SEARCH_RESULTS;
filterArticles();
break;
}
}
public void search(){
switch(MODE){
case SEARCH_RESULTS:
searchLayout.setVisibility(View.VISIBLE);
MODE=SEARCH;
break;
case THEME_TO_SEARCH_RESULTS:
searchLayout.setVisibility(View.VISIBLE);
MODE=THEME_TO_SEARCH;
break;
case THEME:
searchLayout.setVisibility(View.VISIBLE);
MODE=THEME_TO_SEARCH;
break;
case NONE:
searchLayout.setVisibility(View.VISIBLE);
back.setVisibility(View.VISIBLE);
theme.setVisibility(View.GONE);
MODE=SEARCH;
break;
}
}
public void back(){
switch(MODE){
case SEARCH_RESULTS:
searchLayout.setVisibility(View.VISIBLE);
MODE=SEARCH;
break;
case THEME_TO_SEARCH_RESULTS:
searchLayout.setVisibility(View.VISIBLE);
MODE=THEME_TO_SEARCH;
break;
case THEME:
back.setVisibility(View.GONE);
theme.setVisibility(View.VISIBLE);
/*
*
Intent intent = getIntent();
finish();
startActivity(intent);
*/
articlesAdapter=new ArticlesAdapter(this);
ListView articlesList=(ListView)findViewById(R.id.articlesList);
articlesList.setAdapter(articlesAdapter);
//ActusScreen.titleIndex=0;
ArticlesAdapter.mode = true;
titleIndex=0;
new GetAllArticlesTask().execute();
header_text.setText(getResources().getText(R.string.actus).toString());
MODE=NONE;
break;
case SEARCH:
searchLayout.setVisibility(View.GONE);
back.setVisibility(View.GONE);
theme.setVisibility(View.VISIBLE);
MODE=NONE;
copyArticles();
articlesAdapter.notifyDataSetChanged();
break;
case THEME_TO_SEARCH:
searchLayout.setVisibility(View.GONE);
MODE=THEME;
copyArticles();
articlesAdapter.notifyDataSetChanged();
break;
}
}
private void copyArticles() {
if(articles!=null){
if(articlesFiltered==null)
articlesFiltered=new ArrayList<Article>();
else
articlesFiltered.clear();
for(Article a: articles)
articlesFiltered.add(a);
}
}
public void filterArticles(){
String key=searchField.getText().toString().toLowerCase();
if(key.length()>0){
if(articlesFiltered!=null){
articlesFiltered.clear();
System.gc();
}
for(Article a: articles){
if(a.name.toLowerCase().contains(key))
articlesFiltered.add(a);
}
articlesAdapter.notifyDataSetChanged();
}
}
private class GetAllArticlesTask extends AsyncTask<Void, Void, Void> {
#Override
public Void doInBackground(Void... params) {
if(Globals.themes==null)
Globals.themes=HTTPFunctions.getThemesList();
if(articles!=null){
articles.clear();
System.gc();
}
articles=HTTPFunctions.getAllArticles();
copyArticles();
return null;
}
#Override
public void onPreExecute() {
pd = ProgressDialog.show(context, "", context.getResources().getString(R.string.loading), true, false);
}
#Override
public void onPostExecute(Void result) {
pd.dismiss();
articlesAdapter.notifyDataSetChanged();
themeAdapter.notifyDataSetChanged();
}
}
private class GetThemeArticlesTask extends AsyncTask<String, Void, Void> {
#Override
public Void doInBackground(String... params) {
if(articles!=null){
articles.clear();
System.gc();
}
articles=HTTPFunctions.getThemeArticles(params[0]);
//begin 06/03; articles.theme_id not set by HTTPFunctions when a specific theme is selected; need to set it explicitly
for (Article a : articles)
a.theme_id=params[0];
//end
System.out.println("theme article: "+ HTTPFunctions.getThemeArticles(params[0]));
copyArticles();
return null;
}
#Override
public void onPreExecute() {
pd = ProgressDialog.show(context, "", context.getResources().getString(R.string.loading), true, false);
}
#Override
public void onPostExecute(Void result) {
pd.dismiss();
articlesAdapter.notifyDataSetChanged();
}
}
private class GetMoreArticlesTask extends AsyncTask<Void, Void, Void> {
#Override
public Void doInBackground(Void... params) {
ArrayList<Article>moreArticles=HTTPFunctions.getMoreArticles(addOne((articlesFiltered.size()/15)));
if(moreArticles!=null){
articles.addAll(articles);
copyArticles();
}
return null;
}
#Override
public void onPreExecute() {
pd = ProgressDialog.show(context, "", context.getResources().getString(R.string.loading), true, false);
}
#Override
public void onPostExecute(Void result) {
pd.dismiss();
articlesAdapter.notifyDataSetChanged();
}
}
public void articleSelected(int id){
Globals.copyArticles(articlesFiltered);
Intent i=new Intent(context, SelectedArticle.class);
i.putExtra("id", id);
//begin
//i.putExtra("title", ArticlesAdapter.selected);
if (titleIndex==0){
String title=Util.getTitleName(articlesFiltered.get(id).type, articlesFiltered.get(id).theme_id);
i.putExtra("title", title);
}
else{
String title=ArticlesAdapter.selected.toUpperCase();
i.putExtra("title", title);
}
//end
context.startActivity(i);
}
public void themeSelected(int id){
themesList.setVisibility(View.GONE);
MODE=THEME;
theme.setVisibility(View.GONE);
back.setVisibility(View.VISIBLE);
ArticlesAdapter.mode = false;
//begin 06/03
//ArticlesAdapter.selected=Globals.themes.get(id).name;
//header_text.setText(Globals.themes.get(id).name.toUpperCase());
Spanned name=Html.fromHtml(Globals.themes.get(id).name);
System.out.println("spanned name: "+ name);
ArticlesAdapter.selected=name.toString().toUpperCase();
header_text.setText(name.toString().toUpperCase());
//end
System.out.println("theme_name: "+ Globals.themes.get(id).name);
new GetThemeArticlesTask().execute(Globals.themes.get(id).id);
}
public void loadMore(){
new GetMoreArticlesTask().execute();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
if (original_view==true){
new GetAllArticlesTask().execute();
theme.setVisibility(View.VISIBLE);
back.setVisibility(View.GONE);
header_text.setText(getResources().getText(R.string.actus).toString());
original_view=false;
}
super.onResume();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
SelectedReglementation.setview=true;
super.onPause();
}
class backTask extends AsyncTask<String, Void, ArrayList<Post>> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected ArrayList<Post> doInBackground(String... urls) {
ArrayList<Post> newpostarraylist=new ArrayList<Post>();
try{
URL url = new URL("");
BufferedReader reader = null;
builder = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
builder.append(line.trim());
}
} finally {
if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}
System.out.println("Builder: "+ builder);
}catch(Exception ex){}
return newpostarraylist;
}
#Override
protected void onPostExecute(ArrayList<Post> result) {
String[] banner_image = builder.toString().split(";");
imageLoader.displayImage(banner_image[2], image_actus,options);
link = banner_image[1];
}
}
public int addOne(int i){
return i+1;
}
}
and My article adapter
public class ArticlesAdapter extends BaseAdapter {
ActusScreen main;
ImageLoader imageLoader;
String imageUrl="";
public static String selected="";
public static boolean mode=false;
int x=0;
//disable a.theme_id null pointer wh
public static int bine=0;
public ArticlesAdapter(ActusScreen m) {
main=m;
imageLoader=new ImageLoader(m);
}
public int getCount() {
if(main.articlesFiltered!=null)
return main.articlesFiltered.size();
return 0;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView==null) {
convertView=newView(position, parent);
holder = new ViewHolder();
holder.image=(ImageView)convertView.findViewById(R.id.image);
holder.remove=(ImageView)convertView.findViewById(R.id.remove);
holder.title=(TextView)convertView.findViewById(R.id.title);
holder.text_title=(TextView)convertView.findViewById(R.id.text_title);
holder.more=(RelativeLayout)convertView.findViewById(R.id.moreLayout);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Article a=main.articlesFiltered.get(position);
imageLoader.DisplayImage(String.format(imageUrl, a.image), holder.image);
String str = a.name;
int length = str.length();
String newStr = a.name;
if (length>65)
newStr = str.replaceAll("^(.{74})(.*)$","$1...");
holder.title.setText(Html.fromHtml(newStr));
holder.text_title.setText(selected.toUpperCase());
holder.remove.setVisibility(View.GONE);
if (holder.text_title.equals(null))
holder.text_title.setText("t");
if(position==main.articlesFiltered.size()-1 && main.articlesFiltered.size()<=45 && main.articlesFiltered.size()%15==0)
holder.more.setVisibility(View.VISIBLE);
else
holder.more.setVisibility(View.GONE);
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
main.articleSelected(position);
SelectedArticle.mtypo=1;
}
});
holder.more.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
main.loadMore();
}
});
if (ActusScreen.titleIndex==0){
...
}
}
return(convertView);
}
private View newView(int position, ViewGroup parent) {
return(main.getLayoutInflater().inflate(R.layout.articles_row, parent, false));
}
class ViewHolder {
ImageView image, remove;
TextView title;
TextView text_title;
RelativeLayout more;
}
}
UPDATE
and the HttpFunction getMoreArticles()
public static ArrayList<Article> getMoreArticles(int page){
String url=LAST_ARTICLE_URL;
if(url.endsWith(".php"))
url+="?page="+page;
else
url+="&page="+page;
String response=getResponse(url);
if(!ERROR.equals(response)){
return JsonParsingFunctions.parseArticles(response);
}
return null;
}
What is happening is concatenation in the method call. articlesFiltered.size()/15 is giving 1, then the +1 is not ADDING 1, it is concatenating 1, i.e 1+1 = 11 NOT 2. You could create a method
public int addOne(int i){
return i+1;
}
and use
ArrayList<Article>moreArticles=HTTPFunctions.getMoreArticles(addOne((articlesFiltered.size()/15)));
That should work providing the rest of the code is good
what variable is your adapter?
you notify your adapter but i don't see that you add datas to your articlesAdapter