So many people have faced this exception and i tried the solutions available for this exception but none of it actually worked for my case.
So my problem is i have a filter button at my toolbar and it has three items in it 1. ascending order , 2. descending order , 3. date specific. when i am selecting ascending and descending items data is getting populated correctly inside recyclerview. but when i am selecting the date specific option and showing a datepicker ....the data is not getting populated inside recyclerview and when i touch screen application gets crashed and gives me the above mentioned exception.
my code for fragment where i am performing these operations :-
public class PendingOrders extends Fragment {
String filterString="date_desc";
String filterDateString="";
private int mDay,mMonth,mYear;
private static final String TAG = "PendingORDERS";
private RecyclerView mMessagesView;
private List<PendingOrderModel> mMessages = new ArrayList<PendingOrderModel>();
CustomItemClickListener listener;
private PendingOrderAdapter mAdapter;
private Socket mSocket;
private Boolean isConnected = true;
public static final int DIALOG_FRAGMENT = 1;
String actualPrice,amount,total,filledAmount,orderPrice,proceeds,orderDate,orderType,orderId;
String currencyname,order,order1,orderType1 , orderDate1,idz;
public PendingOrders() {
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mAdapter = new PendingOrderAdapter(context, mMessages,listener);
if (context instanceof Activity) {
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
AppController app = (AppController) getActivity().getApplication();
SharedPreferences pref = getActivity().getSharedPreferences("MyPREFERENCES", 0);
idz=pref.getString("ZuserID", null);
mSocket = app.getSocket();
mSocket.on("pending_orders_data", orderCompletedData);
mSocket.connect();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_pending_orders, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMessagesView = (RecyclerView) view.findViewById(R.id.rv_pending_orders);
mMessagesView.setLayoutManager(new LinearLayoutManager(getActivity()));
mMessagesView.setItemAnimator(null);
mAdapter = new PendingOrderAdapter(getActivity(), mMessages, new CustomItemClickListener() {
#Override
public void onItemClick(View v, int position) {
String orderid = mMessages.get(position).getmOrderId();
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
Fragment prev = getActivity().getSupportFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
DialogFragment dialogFrag = PendingCancelDialog.newInstance(123);
dialogFrag.show(getActivity().getFragmentManager().beginTransaction(), "dialog");
Bundle args = new Bundle();
args.putString("ID",orderid);
dialogFrag.setArguments(args);
}
});
mMessagesView.setAdapter(mAdapter);
initObjects();
}
private void initObjects() {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("user_id", idz);
} catch (JSONException e) {
e.printStackTrace();
}
mSocket.emit("register_user", jsonObject.toString());
mSocket.emit("fetch_pending_orders", getSendMessageString(""));
}
public String getSendMessageString(String message) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("page_no", "1"); //1: text message 2: multimedia message
jsonObject.put("user_id", idz);
jsonObject.put("records_per_page", "5");
jsonObject.put("filter", filterString);
Log.i("??", "filterString: "+filterString);
jsonObject.put("filter_date", filterDateString);
Log.i("??", "filterDateString: "+filterDateString);
return jsonObject.toString();
} catch (Exception e) {
e.printStackTrace();
}
return message;
}
private void addMessage(String orderId,String order,String currencyname,String amount,String filledAmount,String proceeds,String orderPrice,String orderDate,String orderType) {
mMessages.add(new PendingOrderModel.Builder(PendingOrderModel.RECEIVER)
.orderid(orderId).order(order).amount(amount).currencyname(currencyname).filledamount(filledAmount).orderprice(orderPrice).proceeds(proceeds).orderdate(orderDate).ordertype(orderType).build());
mMessagesView.getRecycledViewPool().clear();
mAdapter.notifyDataSetChanged();
}
private Emitter.Listener orderCompletedData = new Emitter.Listener() {
#Override
public void call(final Object... args) {
if(getActivity() != null) {
getActivity().runOnUiThread(() -> {
JSONArray object1 = (JSONArray) args[0];
if(object1 != null){
JSONArray array = new JSONArray();
array = object1.optJSONArray(0);
int arraylength = array.length();
for(int j=0; j<array.length();j++){
JSONObject obj = new JSONObject();
try {
obj = array.getJSONObject(j);
currencyname = obj.getString("coin");
orderId = obj.getString("id");
order1 = obj.getString("order");
filledAmount = obj.getString("coin_quantity");
amount = obj.getString("total_amount");
proceeds = obj.getString("remaining");
orderPrice = obj.getString("order_price");
orderDate1 = obj.getString("create_time");
orderType1= obj.getString("order_type");
} catch (JSONException e) {
e.printStackTrace();
}
if(order1 == "1"){
order = "Limit";
}
else{
order = "Market";
}
if(orderType1 == "1"){
orderType = "Sell";
}else{
orderType = "buy";
}
String [] date = orderDate1.split("T");
orderDate = date[0].trim();
addMessage(orderId,order,currencyname,amount,filledAmount,proceeds,orderPrice,orderDate,orderType);
}
}
});
}
}
};
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.asc_order:
filterString="date asc";
filterDateString="";
mMessages.clear();
mSocket.emit("fetch_pending_orders", getSendMessageString(""));
return true;
case R.id.desc_order:
filterString="date desc";
mMessages.clear();
mSocket.emit("fetch_pending_orders", getSendMessageString(""));
return true;
case R.id.pick_date:
filterString="date specific";
mMessages.clear();
pickdate();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void pickdate() {
Calendar c1 = Calendar.getInstance();
mYear = c1.get(Calendar.YEAR);
mMonth = c1.get(Calendar.MONTH);
mDay = c1.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(),R.style.DAte_Theme,
(view, year, monthOfYear, dayOfMonth) -> {
int month = monthOfYear + 1;
String formattedMonth = "" + month;
String formattedDayOfMonth = "" + dayOfMonth;
if(month < 10){
formattedMonth = "0" + month;
}
if(dayOfMonth < 10){
formattedDayOfMonth = "0" + dayOfMonth;
}
filterDateString= formattedDayOfMonth + "/" + formattedMonth + "/" + year;
Log.i("date",filterDateString);
mSocket.emit("fetch_pending_orders", getSendMessageString(""));
// updateDate(filterDateString);
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
}
Below is my Logcat :-
java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder{cfdb59c position=3 id=-1, oldPos=-1, pLpos:-1 no parent} android.support.v7.widget.RecyclerView{476168c VFED..... .F...... 0,0-1080,1560 #7f090169 app:id/rv_pending_orders}, adapter:com.vamediabox.greenpay.adapters.PendingOrderAdapter#d6e71d5, layout:android.support.v7.widget.LinearLayoutManager#e738dea, context:com.vamediabox.greenpay.activities.MyorderActivity#70a64f9
at android.support.v7.widget.RecyclerView$Recycler.validateViewHolderForOffsetPosition(RecyclerView.java:5421)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5603)
at android.support.v7.widget.GapWorker.prefetchPositionWithDeadline(GapWorker.java:285)
at android.support.v7.widget.GapWorker.flushTaskWithDeadline(GapWorker.java:342)
at android.support.v7.widget.GapWorker.flushTasksWithDeadline(GapWorker.java:358)
at android.support.v7.widget.GapWorker.prefetch(GapWorker.java:365)
at android.support.v7.widget.GapWorker.run(GapWorker.java:396)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
See just do one thing when you select the date picker then add these lines before calling the main function.
onClick
{
adapter.notifyDataSetChanged();
recyclerView.getRecycledViewPool().clear();
and then the rest code....
}
Related
After a long search on the internet I couldn't find any solution to meet my requirements.
I have one array list which is passed into the dialog fragment, but my requirement is:
When the user selects the date it calls the web service again and gets another data according to data and passes the same dialog fragment. How can I achieve that ? I have tried with static value but its not clearing the value. My code is:
public static class DatePickerDialogFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener
{
String userName;
public interface UserUserIdListener {
void updateIdUserName(String userName);
}
public static final int FLAG_START_DATE = 0;
public static final int FLAG_END_DATE = 1;
public static List<Orederlist>reportorderIdList=new ArrayList<>();
// private List<Userlist> reportUserList = new ArrayList<>();
private int flag = 0;
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void setFlag(int i) {
flag = i;
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar calendar = Calendar.getInstance();
Calendar calendar1=Calendar.getInstance();
calendar1.set(year, monthOfYear, dayOfMonth);
calendar.set(year, monthOfYear, dayOfMonth);
String reportOrderIds="";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
if (flag == FLAG_START_DATE) {
textviewFromDate.setText(format.format(calendar.getTime()));
fromDateReport=textviewFromDate.getText().toString();
JSONObject pieObject = new JSONObject();
try
{
pieObject.put("fromDate",""+fromDateReport);
pieObject.put("orderId",""+reportOrderIds);
pieObject.put("password",""+sPrefs.getString(Constants.PASSWORD,""));
pieObject.put("toDate",""+toDateReport);
pieObject.put("user",""+sPrefs.getString(Constants.USER_NAME,""));
pieObject.put("subUser",""+reportSubUsers);
progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Loading....");
progressDialog.setCancelable(false);
progressDialog.show();
} catch (Exception e)
{
e.printStackTrace();
}
// String TAG = "delivered";
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonObjectRequest jsOnbjRequest = new
JsonObjectRequest(Request.Method.POST,
Constants.GetSummarizedReports, pieObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response)
{
progressDialog.dismiss();
try {
JSONArray jsonArray = (JSONArray) response.get("orderlist");
{
if (jsonArray.length()>0)
{
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
// Integer name = json.optInt();
String name = json.optString("orderId").toString();
Orederlist user = new Orederlist(name);
user.setOrderId(name);
reportorderIdList.add(user);
}}
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
}
}) {
#Override
public String getBodyContentType() {
return "application/json";
}
};
jsOnbjRequest.setRetryPolicy(new DefaultRetryPolicy(500000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsOnbjRequest);
} else if (flag == FLAG_END_DATE) {
textviewToDate.setText(format.format( calendar1.getTime()));
toDateReport= textviewToDate.getText().toString();
JSONObject pieObject = new JSONObject();
try
{
pieObject.put("fromDate",""+fromDateReport);
pieObject.put("orderId",""+reportOrderIds);
pieObject.put("password",""+sPrefs.getString(Constants.PASSWORD,""));
pieObject.put("toDate",""+toDateReport);
pieObject.put("user",""+sPrefs.getString(Constants.USER_NAME,""));
pieObject.put("subUser",""+reportSubUsers);
progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Loading....");
progressDialog.setCancelable(false);
progressDialog.show();
} catch (Exception e)
{
e.printStackTrace();
}
// String TAG = "delivered";
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonObjectRequest jsOnbjRequest = new
JsonObjectRequest(Request.Method.POST,
Constants.GetSummarizedReports, pieObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response)
{
progressDialog.dismiss();
try {
JSONArray jsonArray = (JSONArray) response.get("orderlist");
{
if (jsonArray.length()>0)
{
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
// Integer name = json.optInt();
String name = json.optString("orderId").toString();
Orederlist user = new Orederlist(name);
user.setOrderId(name);
reportorderIdList.add(user);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
}
}) {
#Override
public String getBodyContentType() {
return "application/json";
}
};
jsOnbjRequest.setRetryPolicy(new DefaultRetryPolicy(500000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsOnbjRequest);
}
}
}
and for dialog fragment pass data is :
FragmentManager managerOrderIds = getSupportFragmentManager();
UserJobIds dialogOrderIds = new UserJobIds();
dialogOrderIds.setdata(orderIdList,reportorderIdList);//with static array list which is not claer the value
dialogOrderIds.show(managerOrderIds, "Dialog");
What you can do is just create a newInstance of Dialog Fragment assign data to it, then call show().Below is an example.
public class D2Fragment extends DialogFragment {
private ArrayList<String> list;
public static D2Fragment getInstanceFor(ArrayList<String> list){
D2Fragment d2Fragment=new D2Fragment();
d2Fragment.list=list;
return d2Fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.item_dialog, container,
false);
getDialog().setTitle("DialogFragment Sample");
Log.e("size",list.size()+"");// Here is the list
// Do something else
return rootView;
}
}
When you show dialog.
ArrayList<String> list=new ArrayList<>();
list.add("Val1");
list.add("Val2");
D2Fragment d2Fragment=D2Fragment.getInstanceFor(list);
d2Fragment.show(getSupportFragmentManager(),"dialog2");
Or just create a setter for your data.
public class D2Fragment extends DialogFragment {
private ArrayList<String> list;
public void setData(ArrayList<String> list){
this.list=list;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.item_dialog, container,
false);
getDialog().setTitle("DialogFragment Sample");
Log.e("size",list.size()+"");// Here is the list
// Do something else
return rootView;
}
}
and to show Dialog.
ArrayList<String> list = new ArrayList<>();
list.add("Val1");
list.add("Val2");
D2Fragment d2Fragment = new D2Fragment();
d2Fragment.setData(list);
d2Fragment.show(getSupportFragmentManager(), "dialog2");
In activity you can always find that particular DialgFragment by tag you assigned at the time of transaction.
Fragment fragment=getSupportFragmentManager().findFragmentByTag("dialog2");
if(fragment!=null && fragment instanceof D2Fragment){
((D2Fragment)fragment).call();// You can call any public method of this dialog fragment here
}
How to do the Filter concept from Below design? I here by attached two screen designs.
DashBoard Fragment -> Having Listview with Base adapter.
The above ListView code is given Below
DashBoardRefactor
public class DashBoardRefactor extends Fragment {
public static ProgressDialog progress;
public static List<DashListModel> dashRowList1 = new ArrayList<DashListModel>();
public static View footerView;
// #Bind(R.id.dashListView)
public static ListView dashListView;
int preCount = 2, scroll_Inc = 10, lastCount;
boolean flag = true;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dashboard_fragment, container, false);
ButterKnife.bind(this, v);
setHasOptionsMenu(true);
progress = new ProgressDialog(getActivity());
dashListView = (ListView) v.findViewById(R.id.dashListView);
footerView = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.dashboard_list_footer, null, false);
dashListView.addFooterView(footerView);
footerView.setVisibility(View.GONE);
dashRowList1.clear();
dashboardViewTask();
dashListView.setOnScrollListener(new EndlessScrollListener(getActivity(), dashListView, footerView));
return v;
}
public void dashboardViewTask() {
progress.setMessage("Loading...");
progress.setCanceledOnTouchOutside(false);
progress.setCancelable(false);
progress.show();
// footerView.setVisibility(View.VISIBLE);
Map<String, String> params = new HashMap<String, String>();
Log.e("candidate_id", "candidate_id---->" + SessionStores.getBullHornId(getActivity()));
params.put("candidate_id", SessionStores.getBullHornId(getActivity()));
params.put("employmentPreference", SessionStores.getEmploymentPreference(getActivity()));
params.put("page", "1");
new DashBoardTask(getActivity(), params, dashListView, footerView);
}
#Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
if (menu != null) {
menu.removeItem(R.id.menu_notify);
}
inflater.inflate(R.menu.menu_options, menu);
MenuItem item = menu.findItem(R.id.menu_filter);
item.setVisible(true);
getActivity().invalidateOptionsMenu();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.his__menu_accept:
Toast.makeText(getActivity(), "clicked dashboard menu accept", Toast.LENGTH_LONG).show();
return true;
case R.id.menu_filter:
// click evnt for filter
Toast.makeText(getActivity(), "clicked dashboard filter", Toast.LENGTH_LONG).show();
Intent filter_intent = new Intent(getActivity(), DashBoardFilterScreen.class);
startActivity(filter_intent);
getActivity().overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onPause() {
super.onPause();
// dashboardViewTask();
}
}
DashBoardTask:
public class DashBoardTask {
public static String candidateIdNo;
public static Integer isBookmarked;
public ListAdapter dashListAdapter;
ListView dashListView;
View footerView;
String fromdate_formated = "";
String todate_formated = "";
private Context context;
private JSONObject jObject = null;
private String result, authorizationKey;
private Map<String, String> params;
public DashBoardTask(Context context, Map<String, String> params, ListView dashListView, View footerView) {
this.context = context;
Log.e("context ", "DashBoardTask: " + context);
this.dashListView = dashListView;
Dashboard.dashRowList.clear();
this.params = params;
this.footerView = footerView;
ResponseTask();
}
private void ResponseTask() {
authorizationKey = Constants.ACCESS_TOKEN;
new ServerResponse(ApiClass.getApiUrl(Constants.DASHBOARD_VIEW)).getJSONObjectfromURL(ServerResponse.RequestType.POST, params, authorizationKey, context, "", new VolleyResponseListener() {
#Override
public void onError(String message) {
if (DashBoardRefactor.progress.isShowing()) {
DashBoardRefactor.progress.dismiss();
}
}
#Override
public void onResponse(String response) {
String dateEnd = "", startDate = "";
result = response.toString();
try {
jObject = new JSONObject(result);
if (jObject != null) {
Integer totalJobList = jObject.getInt("page_count");
Integer total = jObject.getInt("total");
Integer count = jObject.getInt("count");
Integer start = jObject.getInt("start");
if (footerView.isShown() && count == 0) {
footerView.setVisibility(View.GONE);
}
Integer Status = jObject.getInt("status");
if (Status == 1) {
SessionStores.savetotalJobList(totalJobList, context);
JSONArray dataObject = jObject.getJSONArray("data");
Dashboard.dashRowList.clear();
for (int i = 0; i < dataObject.length(); i++) {
Log.e("length", "lenght----->" + dataObject.length());
JSONObject jobDetail = dataObject.getJSONObject(i);
Log.e("jobDetail", "jobDetail----->" + jobDetail);
Integer goalsName = jobDetail.getInt("id");
String compnyTitle = jobDetail.getString("title");
String description = jobDetail.getString("description");
Integer salary = jobDetail.getInt("salary");
String dateAdded = jobDetail.getString("dateAdded");
if (jobDetail.getString("startDate") != null && !jobDetail.getString("startDate").isEmpty() && !jobDetail.getString("startDate").equals("null")) {
startDate = jobDetail.getString("startDate");
} else {
Log.e("Task Null", "Task Null----startDate->");
}
if (jobDetail.getString("dateEnd") != null && !jobDetail.getString("dateEnd").isEmpty() && !jobDetail.getString("dateEnd").equals("null")) {
dateEnd = jobDetail.getString("dateEnd");
} else {
Log.e("Task Null", "Task Null----->");
}
isBookmarked = jobDetail.getInt("isBookmarked");
Integer startSalary = jobDetail.getInt("customFloat1");
Integer endSalary = jobDetail.getInt("customFloat2");
JSONObject cmpanyName = jobDetail.getJSONObject("clientCorporation");
String compnyNamede = cmpanyName.getString("name");
String city = jobDetail.getString("customText1");
JSONObject candidateId = jobDetail.getJSONObject("clientContact");
candidateIdNo = candidateId.getString("id");
DashListModel dashListItem = new DashListModel();
dashListItem.setDashCompanyName(compnyNamede);
dashListItem.setDashJobDescription(description);
dashListItem.setDashJobPosition(compnyTitle);
dashListItem.setDashJobCity(city);
// dashListItem.setDashJobState(state);
dashListItem.setDashSalary(startSalary.toString());
dashListItem.setDashJobAvailableDate(dateAdded);
dashListItem.setDashId(goalsName.toString());
dashListItem.setDashIsBookMarked(isBookmarked.toString());
dashListItem.setDashEndSalary(endSalary.toString());
dashListItem.setToDate(dateEnd);
////////////////////////////////////
String fromDate = null, toDate = null, postedDate = null;
if (startDate.length() > 11) {
Log.e("11", "11---->");
fromDate = Utils.convertFromUnixDateAdded(startDate);
} else if (startDate.length() == 10) {
Log.e("10", "10----->");
fromDate = Utils.convertFromUnix(startDate);
}
if (dateEnd.length() > 11) {
Log.e("11", "11---->");
toDate = Utils.convertFromUnixDateAdded(dateEnd);
} else if (dateEnd.length() == 10) {
Log.e("10", "10----->");
toDate = Utils.convertFromUnix(dateEnd);
}
if (dateAdded.length() > 11) {
Log.e("11", "11---->");
postedDate = Utils.convertFromUnixDateAdded(dateAdded);
} else if (dateAdded.length() == 10) {
Log.e("10", "10----->");
postedDate = Utils.convertFromUnix(dateAdded);
}
try {
if (!fromDate.isEmpty() || !fromDate.equalsIgnoreCase("null")) {
String[] fromDateSplit = fromDate.split("/");
String fromMonth = fromDateSplit[0];
String fromDat = fromDateSplit[1];
String fromYear = fromDateSplit[2];
String fromMonthName = new DateFormatSymbols().getMonths()[Integer.parseInt(fromMonth) - 1];
fromdate_formated = fromMonthName.substring(0, 3) + " " + fromDat + getDayOfMonthSuffix(Integer.parseInt(fromDat));
Log.e("fromdate", "fromdate---->" + fromDate);
Log.e("toDate", "toDate---->" + toDate);
Log.e("fromMonth", "fromMonth---->" + fromMonth);
Log.e("fromDat", "fromDat---->" + fromDat);
Log.e("fromYear", "fromYear---->" + fromYear);
}
if (!toDate.isEmpty() || !toDate.equalsIgnoreCase("null")) {
String[] toDateSplit = toDate.split("/");
String toMonth = toDateSplit[0];
String toDat = toDateSplit[1];
String toYear = toDateSplit[2];
String toMonthName = new DateFormatSymbols().getMonths()[Integer.parseInt(toMonth) - 1];
todate_formated = toMonthName.substring(0, 3) + " " + toDat + getDayOfMonthSuffix(Integer.parseInt(toDat)) + " " + toYear;
Log.e("________________", "-------------------->");
Log.e("toMonth", "toMonth---->" + toMonth);
Log.e("toDat", "toDat---->" + toDat);
Log.e("toYear", "toYear---->" + toYear);
Log.e("________________", "-------------------->");
Log.e("toMonthName", "toMonthName---->" + toMonthName);
}
} catch (Exception e) {
e.printStackTrace();
}
dashListItem.setPostedDate(postedDate);
dashListItem.setFromDate(fromdate_formated);
dashListItem.setEndDate(todate_formated);
/////////////////////////////////////////
// Dashboard.dashRowList.add(dashListItem);
DashBoardRefactor.dashRowList1.add(dashListItem);
}
// get listview current position - used to maintain scroll position
int currentPosition = dashListView.getFirstVisiblePosition();
dashListAdapter = new DashListAdapter(context, DashBoardRefactor.dashRowList1, dashListView);
dashListView.setAdapter(dashListAdapter);
((BaseAdapter) dashListAdapter).notifyDataSetChanged();
if (currentPosition != 0) {
// Setting new scroll position
dashListView.setSelectionFromTop(currentPosition + 1, 0);
}
} else if (Status==0 && count==0 && start==0){
String Message = jObject.getString("message");
Utils.ShowAlert(context, Message);
}
if (footerView.isShown()) {
footerView.setVisibility(View.GONE);
}
//progress.dismiss();
if (DashBoardRefactor.progress.isShowing()) {
try {
DashBoardRefactor.progress.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
}
DashListModel:
public class DashListModel {
private String dashCompanyName;
private String dashJobPosition;
private String dashJobPostedDate;
private String dashJobDescription;
private String dashSalary;
private String dashJobCity;
private String dashJobState;
private String dashJobAvailableDate;
private String dashId, dashIsBookmarked;
private String dashEndSalary;
private String toDate;
private String postedDate, fromdate, enddate;
public String getDashCompanyName() {
return dashCompanyName;
}
public void setDashCompanyName(String dashCompanyName) {
this.dashCompanyName = dashCompanyName;
}
public String getDashJobPosition() {
return dashJobPosition;
}
public void setDashJobPosition(String dashJobPosition) {
this.dashJobPosition = dashJobPosition;
}
public String getDashJobDescription() {
return dashJobDescription;
}
public void setDashJobDescription(String dashJobDescription) {
this.dashJobDescription = dashJobDescription;
}
public String getDashJobPostedDate() {
return dashJobPostedDate;
}
public void setDashJobPostedDate(String dashJobPostedDate) {
this.dashJobPostedDate = dashJobPostedDate;
}
public String getDashSalary() {
return dashSalary;
}
public void setDashSalary(String dashSalary) {
this.dashSalary = dashSalary;
}
public String getDashJobCity() {
return dashJobCity;
}
public void setDashJobCity(String dashJobCity) {
this.dashJobCity = dashJobCity;
}
/* public String getDashJobState() {
return dashJobState;
}
public void setDashJobState(String dashJobState) {
this.dashJobState = dashJobState;
}*/
public String getDashJobAvailableDate() {
return dashJobAvailableDate;
}
public void setDashJobAvailableDate(String dashJobAvailableDate) {
this.dashJobAvailableDate = dashJobAvailableDate;
}
public String getDashId() {
return dashId;
}
public void setDashId(String dashId) {
this.dashId = dashId;
}
public String getDashIsBookmarked() {
return dashIsBookmarked;
}
public void setDashIsBookMarked(String dashIsBookmarked) {
this.dashIsBookmarked = dashIsBookmarked;
}
public String getDashEndSalary() {
return dashEndSalary;
}
public void setDashEndSalary(String dashEndSalary) {
this.dashEndSalary = dashEndSalary;
}
public String getToDate() {
return toDate;
}
public void setToDate(String toDate) {
this.toDate = toDate;
}
public String getPostedDate() {
return postedDate;
}
public void setPostedDate(String postedDate) {
this.postedDate = postedDate;
}
public String getFromDate() {
return fromdate;
}
public void setFromDate(String fromdate) {
this.fromdate = fromdate;
}
public String getEndDate() {
return enddate;
}
public void setEndDate(String enddate) {
this.enddate = enddate;
}
DashListAdapter:
package com.peoplecaddie.adapter;
public class DashListAdapter extends BaseAdapter {
public static ListView dashListView;
Context c;
private LayoutInflater inflater;
private List<DashListModel> dashRowList;
public DashListAdapter(Context c, List<DashListModel> dashRowList, ListView dashListView) {
this.c = c;
this.dashListView = dashListView;
this.dashRowList = dashRowList;
}
#Override
public int getCount() {
return this.dashRowList.size();
}
#Override
public Object getItem(int position) {
return dashRowList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder dashHolder;
if (inflater == null)
inflater = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.dashboard_jobdetails_list, null);
final DashListModel dashModel = dashRowList.get(position);
dashHolder = new ViewHolder(convertView);
dashHolder.dash_company_name.setText(dashModel.getDashCompanyName());
dashHolder.dash_position_name.setText(dashModel.getDashJobPosition());
dashHolder.dash_posted_date.setText(dashModel.getPostedDate());
dashHolder.dash_job_description.setText(Utils.stripHtml(dashModel.getDashJobDescription()));
dashHolder.dash_salary.setText(dashModel.getDashSalary() + " - " + dashModel.getDashEndSalary());
dashHolder.dash_available_date.setText(dashModel.getFromDate() + " - " + dashModel.getEndDate());
dashHolder.book_jobCity.setText(dashModel.getDashJobCity());
if (dashModel.getDashIsBookmarked().equalsIgnoreCase("1")) {
dashHolder.bookmark_img.setImageResource(R.drawable.bookmark);
} else if (dashModel.getDashIsBookmarked().equalsIgnoreCase("0")) {
dashHolder.bookmark_img.setImageResource(R.drawable.blue_tag_img);
}
dashHolder.bookmark_img.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (dashModel.getDashIsBookmarked().equalsIgnoreCase("0")) {
dashModel.setDashIsBookMarked("1");
Map<String, String> params = new HashMap<String, String>();
params.put("candidate_id", SessionStores.getBullHornId(c));
params.put("joborder_id", dashModel.getDashId());
BackGroundTasks bookmark_add_bg_tasks = new BackGroundTasks(c, new JSONObject(params), Constants.BOOKMARK_ADD_TAG);
bookmark_add_bg_tasks.ResponseTask(new BackGroundTasks.VolleyCallbackOnEdit() {
#Override
public void onSuccess(String result) {
String resp_resultsd = result;
Log.e("insidecallback", " bookmark_add_bg_tasks----->" + resp_resultsd);
// finish();
dashHolder.bookmark_img.setImageResource(R.drawable.bookmark);
notifyDataSetChanged();
}
});
} else if (dashModel.getDashIsBookmarked().equalsIgnoreCase("1")) {
dashModel.setDashIsBookMarked("0");
Log.e("imgchange", " imgchange");
Map<String, String> params = new HashMap<String, String>();
params.put("candidate_id", SessionStores.getBullHornId(c));
params.put("joborder_id", dashModel.getDashId());
BackGroundTasks bookmark_delete_bg_tasks = new BackGroundTasks(c, new JSONObject(params), Constants.BOOKMARK_DELETE_TAG);
bookmark_delete_bg_tasks.ResponseTask(new BackGroundTasks.VolleyCallbackOnEdit() {
#Override
public void onSuccess(String result) {
String resp_resultsd = result;
Log.e("insidecallback", " bookmark_delete_bg_tasks----->" + resp_resultsd);
// finish();
dashHolder.bookmark_img.setImageResource(R.drawable.blue_tag_img);
notifyDataSetChanged();
}
});
}
}
});
return convertView;
}
static class ViewHolder {
#Bind(R.id.book_company_name)
TextView dash_company_name;
private RelativeLayout.LayoutParams viewLayParams;
public ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
Clarification:
How do to Filter while click the Filter Button On DashBoard Fragment. Please Suggest the way. I here by attached My Filter design also.
Dashboard Fragment--> Filter Button-> Filter screen-> the Filtered results should view on DashBoard Fragment.
Once click the apply Button Based on the input from Filter screen it filters the list view the result comes from back end team. I have to display that result on Dashboard Fragment.
Kindly please clarify this Filter concept.
I have an app that reads and display data from a weather API as show below.
Now those data you see in the RecyclerView are displayed via a Fragment. What happens is when I click the Forecast button in the toolbar the web service service is running again. Which means that the Fragment is added in the stack/click.
So here is my logic how to fix that. If the stack is null then add the Fragment. If not then don't.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.forecast) {
String tag = "forecastFragment";
Fragment f = getSupportFragmentManager().findFragmentByTag(tag);
if (f == null) {
ForecastFragment forecastFragment = new ForecastFragment();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.main_content, forecastFragment, "forecastfragment");
ft.addToBackStack("added today current");
forecastFragment.setArguments(b);
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
ft.commit();
} else{
getSupportFragmentManager().findFragmentById(R.id.main_content);
}
}
return super.onOptionsItemSelected(item);
}
Here is what I did, but still the web service is running every time I click the Forecast button.
Any ideas?
Here is my Webservice that is run by the ForecastFragment.
class ForecastFragment extends Fragment {
private static final String FORECAST_KEY = "forecast";
public static String URL=
"http://api.openweathermap.org/data/2.5/forecast/daily?";
EditText editText;
public static String BASE_URL= "";
private String IMG_URL ="http://api.openweathermap.org/img/w/";
private String retrievedLat;
private String retrievedLog;
private RecyclerView mRecyclerView;
ImageView imageView;
public ArrayList<Model> modelList;
private Model m;
WeekForecastAdapter adapter;
public ForecastFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_forecast, container, false);
retrievedLat = getArguments().getString("lat");
retrievedLog = getArguments().getString("log");
//http://api.openweathermap.org/data/2.5/forecast/daily?lat=35&lon=139&units=metric&cnt=10&mode=json&appid=d48708e1e4d8e2b60da14778acd8d56a
BASE_URL = URL +"lat="+retrievedLat+"&lon="+retrievedLog+"&units=metric&cnt=10&mode=json&appid=d48708e1e4d8e2b60da14778acd8d56a";
modelList = new ArrayList<>();
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView = (RecyclerView)rootView.findViewById(R.id.week_forecast_recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(linearLayoutManager);
adapter = new WeekForecastAdapter(getActivity(),modelList);
mRecyclerView.setAdapter(adapter);
if(savedInstanceState!=null){
ArrayList<Model> items = savedInstanceState.getParcelableArrayList(FORECAST_KEY);
modelList = savedInstanceState.getParcelableArrayList(FORECAST_KEY);
adapter.setModel(items);
}else {
if(isOnline()) {
weekWeatherData();
}else{
Toast.makeText(getActivity(),"No internet connection",Toast.LENGTH_SHORT).show();
}
}
return rootView;
}
private void weekWeatherData() {
modelList.clear();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
BASE_URL,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
try {
m = new Model();
JSONObject cityObject = response.getJSONObject("city");
String city = cityObject.getString("name");
String country = cityObject.getString("country");
JSONArray jsonObject = response.getJSONArray("list");
for(int i = 0;i<jsonObject.length();i++){
m = new Model();
m.setCity(city);
m.setCountry(country);
//list:
// {"dt":1464343200,"temp":{"day":23.05,"min":8.65,"max":24.96,"night":13.22,"eve":24.85,"morn":8.65},
// "pressure":950.2,"humidity":41,"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"
// }],
// "speed":1.16,"deg":342,"clouds":0}
JSONObject innerJSON = jsonObject.getJSONObject(i);
long dateTime = innerJSON.getLong("dt");
Date weekDay = new Date(dateTime * 1000L);
SimpleDateFormat outFormat = new SimpleDateFormat("EEEE");
String day = outFormat.format(weekDay);
SimpleDateFormat outFormat1 = new SimpleDateFormat("dd MMM");
String date = outFormat1.format(weekDay);
m.setDay(day);
m.setDate(date);
m.setDay(day);
//temp:{"day":26.92,"min":19.48,"max":26.92,"night":19.48,"eve":25.65,"morn":26.92}
JSONObject tempObject = innerJSON.getJSONObject("temp");
m.setTemperature(tempObject.getString("day"));
m.setMaxTemperature(tempObject.getString("max"));
m.setMinTemperature(tempObject.getString("min"));
double pressure = innerJSON.getDouble("pressure");
int humidity = innerJSON.getInt("humidity");
m.setPressure(String.valueOf(pressure));
m.setHumidity(String.valueOf(humidity));
JSONArray weather = innerJSON.getJSONArray("weather");
for(int j=0;j<weather.length();j++){
JSONObject weatherObject = weather.getJSONObject(j);
m.setDescription(weatherObject.getString("description"));
m.setImageIcon(IMG_URL+weatherObject.getString("icon"));
}
double speed = innerJSON.getDouble("speed");
m.setSpeed(String.valueOf(speed));
modelList.add(m);
}
} catch (JSONException e) {
Log.e("TAG", e.toString());
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.v("Theo","onSaveInstanceState called");
outState.putParcelableArrayList(FORECAST_KEY,modelList);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.v("Theo","onDestroy called");
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
}
Change:
ft.replace(R.id.main_content, forecastFragment, "forecastfragment");
To:
ft.replace(R.id.main_content, forecastFragment, tag);
Because your tag (i.e. "forecastFragment") string value is different than the tag you are passing while adding the fragment (i.e. "forecastfragment"). That's why it is not able to find the fragment by tag and adding it everytime on clicking.
I found another solution too.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.forecast) {
ForecastFragment forecastFragment = null;
int backStackEntryCount =
getSupportFragmentManager().getBackStackEntryCount();
if (backStackEntryCount == 0 && forecastFragment == null) {
forecastFragment = new ForecastFragment();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.main_content, forecastFragment);
ft.addToBackStack("added today current");
forecastFragment.setArguments(b);
//fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
ft.commit();
}else{
//getSupportFragmentManager().findFragmentById(R.id.main_content);
}
}
return super.onOptionsItemSelected(item);
}
In this code I have a custom adapter, and after I add new data into ArrayList my adapter.notifyDataSetChanged(); doesn't work.
public class ReceiveListFragment extends ListFragment implements AbsListView.OnScrollListener {
public ArrayList<ReceivedItemStructure> items;
private int prevVisibleItem;
private boolean isFirstTime;
private DatabaseHandler db;
private String config_username;
private String config_password;
private ReceivedAdapter adapter;
private Cursor cursor;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
db = new DatabaseHandler(G.context);
config_username = Configuration.getInstance()
.getString(getActivity(),
Configuration.SharedPrefsTypes.USERNAME);
config_password = Configuration.getInstance()
.getString(getActivity(),
Configuration.SharedPrefsTypes.PASSWORD);
items = new ArrayList<ReceivedItemStructure>();
getRequestFromServer(0, 10);
adapter = new ReceivedAdapter(G.context, items);
setListAdapter(adapter);
Timer smsThread = new Timer();
GetSMSThread getSMSThread = new GetSMSThread();
smsThread.scheduleAtFixedRate(getSMSThread, 1, 10000); //(timertask,delay,period)
return super.onCreateView(inflater, container, savedInstanceState);
}
private String getRequestFromServer(long lastID, int count) {
String received = "";
try {
received = new JsonService(config_username, config_password, lastID, count, G.F_RECEIVE_SMS).request();
JSONArray data_array = new JSONArray(received);
String mUserID = config_username;
for (int i = 0; i < data_array.length(); i++) {
JSONObject json_obj = data_array.getJSONObject(i);
String mLastID = json_obj.getString("id_recived_sms");
String mSmsBody = json_obj.getString("sms_body");
String mSmsNumber = json_obj.getString("sms_number");
String mSenderName = json_obj.getString("mobile_number");
String mContactName = json_obj.getString("contact_name");
String mDate = json_obj.getString("recived_date");
ReceivedItemStructure item = new ReceivedItemStructure(
mLastID,
mUserID,
mSmsBody,
mSmsNumber,
mSenderName,
mContactName,
mDate
);
items.add(item);
//Log.e(" ", "" + mLastID);
}
/** Creating array adapter to set data in listview */
} catch (Exception e) {
e.printStackTrace();
}
return received;
}
public long getLastID() {
return Long.parseLong(items.get(items.size() - 1).getmLastID());
}
private void addDataToList(String LastID, String SmsBody, String SmsNumber, String SenderName, String ContactName, String Date) {
String mLastID = LastID;
String mUserID = config_username;
String mSmsBody = SmsBody;
String mSmsNumber = SmsNumber;
String mSenderName = SenderName;
String mContactName = ContactName;
String mDate = Date;
ReceivedItemStructure item = new ReceivedItemStructure(
mLastID,
mUserID,
mSmsBody,
mSmsNumber,
mSenderName,
mContactName,
mDate
);
items.add(item);
adapter.update(items);
adapter.notifyDataSetChanged();
}
public class GetSMSThread extends TimerTask {
private Long lastID;
private SQLiteDatabase dbHelper;
private List<ReceiveListFragment> rows;
#Override
public void run() {
lastID = getLastID();
if (Configuration.getInstance().checkInternetConnection(G.context)) {
try {
Thread threadTask = new Thread() {
#Override
public void run() {
G.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
int countSMS = 0;
String smsReceivedSender = "";
String receive_lastID = "";
String r = new JsonService(config_username, config_password, 0, 1, G.F_RECEIVE_SMS).request();
JSONArray data_array = new JSONArray(r);
ArrayList<String> items_array = new ArrayList<String>();
JSONObject json_obj = data_array.getJSONObject(0);
receive_lastID = json_obj.getString("id_recived_sms");
smsReceivedSender = json_obj.getString("mobile_number");
for (ReceivedItemStructure rf : items) {
items_array.add(rf.getmLastID());
}
if (items_array.indexOf(receive_lastID) == -1) {
countSMS++;
addDataToList(
json_obj.getString("id_recived_sms"),
json_obj.getString("sms_body"),
json_obj.getString("sms_number"),
json_obj.getString("mobile_number"),
json_obj.getString("contact_name"),
json_obj.getString("recived_date")
);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};
threadTask.start();
} catch (Exception e) {
e.printStackTrace();
} // END TRY
}
}
}
}
My custom Adapter code is this:
public class ReceivedAdapter extends ArrayAdapter<ReceivedItemStructure> {
private ArrayList<ReceivedItemStructure> list;
public ReceivedAdapter(Context c, ArrayList<ReceivedItemStructure> items) {
super(c,0,items);
list = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ReceiveItemView itemView = (ReceiveItemView)convertView;
if (null == itemView)
itemView = ReceiveItemView.inflate(parent);
itemView.setItem(getItem(position));
return itemView;
}
public void update(ArrayList<ReceivedItemStructure> items) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
addAll(items);
} else {
for (ReceivedItemStructure item : items) {
add(item);
}
}
}
}
setListAdapter(adapter); works correctly and I don't have any problem, but after I add new data into items notifyDataSetChanged it doesn't work.
My manifest content:
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="21"/>
it is the super class that is handling the dataset, since you are not overriding getCount and getItem,
public void update(ArrayList<ReceivedItemStructure> items) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
addAll(items);
} else {
for (ReceivedItemStructure item : items) {
add(item)
}
}
}
addAll was introduced with Honeycomb, so you probably want to check the current supported sdk where you are app is running
You are modifying your original items collection. But you should to modify adapter's data. Use ArrayAdapter.add method to add new items.
I am trying to use Endless listview adapter in application code but some how i am just not able to see any values in the listview. My code is running perfectly fine when using normal listview adapter. I an trying to use CWAC- endless adpater. I can get how to run it with my asynctask as it gives me blank screen after loding.
Below is my code for the some.
public class EndlessAdapterExample extends ListActivity {
public JSONArray jsonarray,jsondatearray;
public String url;
public String selectedvalue;
public String TAG = "TAG Event Display";
public String SuggestCity;
public String SuggestState;
public String suggestCountry;
public String event_id,address;
String lat;
String lng;
public String event_name;
public String dateKey;
public String datetime,timenew;
Calendar cal;
public SharedPreferences prefs;
public Editor editor;
public String access_token,id,username;
public static ArrayList<EventsBean> arrayEventsBeans = new ArrayList<EventsBean>();
ArrayList<DateBean> sortArray = new ArrayList<DateBean>();
public SAmpleAdapter adapter;
public ImageView img_menu,img_calender;
public ListView listview;
static int LIST_SIZE;
private int mLastOffset = 0;
static final int BATCH_SIZE = 10;
ArrayList<EventsBean> countriesSub = new ArrayList<EventsBean>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setTheme(android.R.style.Theme);
setContentView(R.layout.sample_endless);
listview = (ListView)findViewById(android.R.id.list);
try {
// Preferences values fetched from the preference of FBConnection class.
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
access_token = prefs.getString("access_token", null);
id = prefs.getString("uid", null);
username = prefs.getString("username", null);
if(access_token == null && id == null && username == null)
{
Toast.makeText(getApplicationContext(), "FaceBook Login was not successful" +
"/nPlease Relogin.", Toast.LENGTH_SHORT).show();
}
else
{
Log.i(TAG, "VALUES::" + access_token+ " " + id + " " +username);
url = "mu Url"
}
} catch (NullPointerException e) {
Log.i(TAG, "User Not Logged IN " + e.getMessage());
// TODO Auto-generated catch block
e.printStackTrace();
}
init();
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
// TODO Auto-generated method stub
// Fetching the position from the listview which has been selected.
}
});
}
private void init() {
new FetchEventValues().execute();
}
private void setLastOffset(int i) {
mLastOffset = i;
}
private int getLastOffset(){
return mLastOffset;
}
private void displayList(ArrayList<EventsBean> countriesSub) {
setListAdapter(new DemoAdapter());
}
// AsyncTask Class called in the OnCreate() when the activity is first started.
public class FetchEventValues extends AsyncTask<Void, ArrayList<EventsBean>, ArrayList<EventsBean>>
{
ProgressDialog progressdialog = new ProgressDialog(EndlessAdapterExample.this);
ArrayList<EventsBean> merge = new ArrayList<EventsBean>();
ArrayList<EventsBean> localList;
public EventsBean eventsbean;
#SuppressLint("SimpleDateFormat")
#SuppressWarnings("unchecked")
#Override
protected ArrayList<EventsBean> doInBackground(Void... params) {
// Creating JSON Parser instance
JsonParser jParser = new JsonParser();
// getting JSON string from URL
JSONObject jsonobj = jParser.getJSONFromUrl(url);
Log.i(TAG, "URL VALUES:" + url);
try{
// Code to get the auto complete values Autocomplete Values
JSONArray jsonAarray = jsonobj.getJSONArray(Constants.LOCATIONS);
eventsbean = new EventsBean();
Log.e(TAG, "Location Array Size:" + jsonAarray.length());
for(int j = 0 ; j < jsonAarray.length() ; j++)
{
if(!jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_CITY) && !jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_STATE) && !jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_COUNTRY))
{
JSONObject job = jsonAarray.getJSONObject(j);
if(job.has(Constants.LOCATION_STATE))
{
SuggestCity = job.getString(Constants.LOCATION_CITY);
eventsbean.setLocation_city(job.getString(Constants.LOCATION_CITY));
SuggestState = job.getString(Constants.LOCATION_STATE);
eventsbean.setLocation_state(job.getString(Constants.LOCATION_STATE));
suggestCountry = job.getString(Constants.LOCATION_COUNTRY);
eventsbean.setLocation_country(job.getString(Constants.LOCATION_COUNTRY));
}
}
}
// JSON object to fetch the events in datewise format
JSONObject eventobject = jsonobj.getJSONObject("events");
// #SuppressWarnings("unchecked")
Iterator<Object> keys = eventobject.keys();
while (keys.hasNext()) {
String datestring = String.valueOf(keys.next());
if (datestring.trim().length() > 0) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = formatter.parse(datestring);
DateBean dateBean = new DateBean(date);
sortArray.add(dateBean);
}
// JSONArray jsonArray = eventobject.getJSONArray(datestring);
//System.out.println(" --"+jsonArray);
}
System.out.println("size:"+sortArray.size());
System.out.println("==========sorting array======");
Collections.sort(sortArray,new CompareDate());
//reverse order
//Collections.reverse(sortArray);
for(DateBean d : sortArray){
dateKey = new SimpleDateFormat("yyyy-MM-dd").format(d.getDate());
System.out.println(dateKey);
Date today = new Date();
Date alldates = d.getDate();
cal = Calendar.getInstance();
/// Calendar alldates1 = Calendar.getInstance();
JSONArray jsonArray = eventobject.getJSONArray(dateKey);
System.out.println(" --"+jsonArray);
for (int i = 0 ; i < jsonArray.length() ; i++)
{
if (alldates.compareTo(today) > 0)
// if (alldates1 > cal) alldates.getTime() >= today.getTime()
{
JSONObject jsonobjname = jsonArray.getJSONObject(i);
eventsbean = new EventsBean();
JSONObject jobjectpicture = jsonobjname.getJSONObject(Constants.PICTURE);
JSONObject jobjeventpicture = jobjectpicture.getJSONObject(Constants.DATA);
eventsbean.setUrl(jobjeventpicture.getString(Constants.URL));
if(jsonobjname.has(Constants.OWNER))
{
JSONObject owner_obj = jsonobjname.getJSONObject(Constants.OWNER);
eventsbean.setOwner_id(owner_obj.getString(Constants.OWNER_ID));
eventsbean.setOwner_name(owner_obj.getString(Constants.OWNER_NAME));
String owner_name = owner_obj.getString(Constants.OWNER_NAME);
Log.i(TAG, "Owner:" + owner_name);
}
if(!jsonobjname.isNull(Constants.COVER))
{
JSONObject objectcover = jsonobjname.getJSONObject(Constants.COVER);
eventsbean.setCover_id(objectcover.getString(Constants.COVER_ID));
eventsbean.setSource(objectcover.getString(Constants.SOURCE));
String cover_url = objectcover.getString(Constants.SOURCE);
Log.i(TAG, "Cover Url:" + cover_url);
eventsbean.setOffset_y(objectcover.getString(Constants.OFFSET_Y));
eventsbean.setOffset_x(objectcover.getString(Constants.OFFSET_X));
}
eventsbean.setName(jsonobjname.getString(Constants.NAME));
eventsbean.setEvent_id(jsonobjname.getString(Constants.EVENT_ID));
eventsbean.setStart_time(jsonobjname.getString(Constants.START_TIME));
eventsbean.setDescription(jsonobjname.getString(Constants.DESCRIPTION));
eventsbean.setLocation(jsonobjname.getString(Constants.LOCATION));
if(!jsonobjname.isNull(Constants.IS_SILHOUETTE))
{
eventsbean.setIs_silhouette(jsonobjname.getString(Constants.IS_SILHOUETTE));
}
eventsbean.setPrivacy(jsonobjname.getString(Constants.PRIVACY));
datetime = jsonobjname.getString(Constants.START_TIME);
if(!jsonobjname.isNull(Constants.VENUE))
{
JSONObject objectvenue = jsonobjname.getJSONObject(Constants.VENUE);
if(objectvenue.has(Constants.VENUE_NAME))
{
eventsbean.setVenue_name(objectvenue.getString(Constants.VENUE_NAME));
event_name = objectvenue.getString(Constants.VENUE_NAME);
Log.i(TAG, "Event Venue Name:" + event_name);
}
else
{
eventsbean.setLatitude(objectvenue.getString(Constants.LATITUDE));
eventsbean.setLongitude(objectvenue.getString(Constants.LONGITUDE));
eventsbean.setCity(objectvenue.getString(Constants.CITY));
eventsbean.setState(objectvenue.getString(Constants.STATE));
eventsbean.setCountry(objectvenue.getString(Constants.COUNTRY));
eventsbean.setVenue_id(objectvenue.getString(Constants.VENUE_ID));
eventsbean.setStreet(objectvenue.getString(Constants.STREET));
address = objectvenue.getString(Constants.STREET);
eventsbean.setZip(objectvenue.getString(Constants.ZIP));
}
}
arrayEventsBeans.add(eventsbean);
Log.i(TAG, "arry list values:" + arrayEventsBeans.size());
}
}
}
}catch(Exception e){
localList=null;
Log.e(TAG , "Exception Occured:" + e.getMessage());
}
return arrayEventsBeans;
}
class CompareDate implements Comparator<DateBean>{
#Override
public int compare(DateBean d1, DateBean d2) {
return d1.getDate().compareTo(d2.getDate());
}
}
#Override
protected void onPostExecute(ArrayList<EventsBean> result) {
super.onPostExecute(result);
if(this.progressdialog.isShowing())
{
this.progressdialog.dismiss();
}
// adapter = new SAmpleAdapter(EndlessAdapterExample.this,0, arrayEventsBeans);
//listview.setAdapter(adapter);
//displayList(arrayEventsBeans);
LIST_SIZE = arrayEventsBeans.size();
for (int i = 0; i <= BATCH_SIZE; i++) {
countriesSub.add(arrayEventsBeans.get(i));
}
setLastOffset(BATCH_SIZE);
displayList(countriesSub);
Log.i(TAG, "country list:" + countriesSub.size());
}
#Override
protected void onPreExecute() {
super.onPreExecute();
this.progressdialog.setMessage("Loading....");
this.progressdialog.setCanceledOnTouchOutside(false);
this.progressdialog.show();
}
}
public class SAmpleAdapter extends ArrayAdapter<EventsBean> {
Context context;
public ArrayList<EventsBean> mOriginalvalues;
private ArrayList<EventsBean> mDisplayvalues;
ImageLoader imageloader;
public String datenew,datetime,date_text_value,timenew;
public int date_text,year;
public String time,month,description;
public LayoutInflater inflator = null;
public SAmpleAdapter(Context context, int resource, ArrayList<EventsBean> mEventarraylist) {
super(context, resource , mEventarraylist);
// TODO Auto-generated constructor stub
this.mOriginalvalues = mEventarraylist;
this.mDisplayvalues = mEventarraylist;
inflator = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageloader=new ImageLoader(context.getApplicationContext());
getFilter();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mOriginalvalues.size();
}
#Override
public EventsBean getItem(int position) {
// TODO Auto-generated method stub
return mOriginalvalues.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
Holder viewHolder;
if(convertView == null)
{
viewHolder=new Holder();
convertView = inflator.inflate(R.layout.activity_list_items, parent, false);
viewHolder.txt_name = (TextView)convertView.findViewById(R.id.textname);
viewHolder.txt_owner_name = (TextView)convertView.findViewById(R.id.ownername);
viewHolder.txt_time = (TextView)convertView.findViewById(R.id.date);
viewHolder.txt_date = (TextView)convertView.findViewById(R.id.txt_date_value);
viewHolder.txt_month = (TextView)convertView.findViewById(R.id.txt_month_value);
viewHolder.txt_year = (TextView)convertView.findViewById(R.id.txt_year_value);
viewHolder.userimg = (ImageView)convertView.findViewById(R.id.imageView1);
convertView.setTag(viewHolder);
}
else
{
viewHolder=(Holder)convertView.getTag();
}
viewHolder.txt_name.setText(mOriginalvalues.get(position).getName());
viewHolder.txt_owner_name.setText(mOriginalvalues.get(position).getOwner_name());
String url = mOriginalvalues.get(position).getSource();
date_text_value = mOriginalvalues.get(position).getStart_time();
try {
parseDateFromString(date_text_value);
} catch (Exception e) {
Log.i("Adapter TAG", "Date Exception" + e.getMessage());
}
viewHolder.txt_date.setText(String.valueOf(date_text));
viewHolder.txt_month.setText(month);
viewHolder.txt_year.setText(String.valueOf(year));
Log.i("TEST", "Date:" + date_text_value);
imageloader.DisplayImage(url, viewHolder.userimg);
viewHolder.txt_time.setText(timenew);
return convertView;
}
public void resetData() {
mOriginalvalues = mDisplayvalues;
}
#SuppressLint("SimpleDateFormat")
public Date parseDateFromString(String aDateString){
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Calendar c = Calendar.getInstance();
Date date= new Date();
try {
date= inputFormat.parse(aDateString);
System.out.println(date);
SimpleDateFormat day = new SimpleDateFormat("dd-MMM-yyyy");
SimpleDateFormat time = new SimpleDateFormat("hh:mm a", Locale.getDefault());
SimpleDateFormat month_date = new SimpleDateFormat("MMM");
c.setTime(inputFormat.parse(aDateString));
System.out.println(day.format(date));
datenew = day.format(date).toString();
date_text = c.get(Calendar.DAY_OF_MONTH);
month = month_date.format(c.getTime());
year = c.get(Calendar.YEAR);
System.out.println("Year = " + c.get(Calendar.YEAR));
System.out.println("Month = " + month);
System.out.println("Day = " + date_text);
System.out.println(time.format(date));
timenew = time.format(date).toString();
} catch (ParseException e) {
Log.i("TAG", "DateFormat Pasring Error:" + e.getMessage());
}
return date;
}
private class Holder{
TextView txt_name;
TextView txt_owner_name ;
TextView txt_time;
TextView txt_date;
TextView txt_month;
TextView txt_year;
ImageView userimg;
}
}
class DemoAdapter extends EndlessAdapter {
private RotateAnimation rotate=null;
ArrayList<EventsBean> tempList = new ArrayList<EventsBean>();
LayoutInflater inflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
DemoAdapter() {
super(new SAmpleAdapter(EndlessAdapterExample.this,R.layout.sample_endless,countriesSub));
inflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rotate=new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF,
0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
rotate.setDuration(600);
rotate.setRepeatMode(Animation.RESTART);
rotate.setRepeatCount(Animation.INFINITE);
}
#Override
protected View getPendingView(ViewGroup parent) {
View row=getLayoutInflater().inflate(R.layout.row, null);
View child=row.findViewById(R.id.textview1);
child.setVisibility(View.GONE);
child=row.findViewById(R.id.throbber);
child.setVisibility(View.VISIBLE);
child.startAnimation(rotate);
return(row);
}
#Override
protected boolean cacheInBackground() {
tempList.clear();
int lastOffset = getLastOffset();
if(lastOffset < LIST_SIZE){
int limit = lastOffset + BATCH_SIZE;
for(int i=(lastOffset+1); (i<=limit && i<LIST_SIZE); i++){
tempList.add(arrayEventsBeans.get(i));
}
setLastOffset(limit);
if(limit<LIST_SIZE){
return true;
} else {
return false;
}
} else {
return false;
}
}
#SuppressLint("NewApi")
#Override
protected void appendCachedData() {
#SuppressWarnings("unchecked")
ArrayAdapter<EventsBean> arrAdapterNew = (ArrayAdapter<EventsBean>)getWrappedAdapter();
int listLen = tempList.size();
for(int i=0; i<listLen; i++){
arrAdapterNew.addAll(tempList.get(i));
}
}
}
}
I have updated my code. I guess my problem now is with the custom adapter as it gives me multiple values after it reaches the end of the listview. Initially i do get 10 values but after the update it gets same 10 values again but the count reaches to 121.
Replace your init() as below,
private void init() {
new FetchEventValues().execute();
}
and replace onPostExecute() with below,
#Override
protected void onPostExecute(ArrayList<EventsBean> result) {
super.onPostExecute(result);
if (this.progressdialog.isShowing()) {
this.progressdialog.dismiss();
}
// adapter = new SAmpleAdapter(EndlessAdapterExample.this,0,
// arrayEventsBeans);
// listview.setAdapter(adapter);
LIST_SIZE = arrayEventsBeans.size();
for (int i = 0; i <= BATCH_SIZE; i++) {
countriesSub.add(arrayEventsBeans.get(i));
}
setLastOffset(BATCH_SIZE);
displayList(countriesSub);
}