On Scroll up SwipetoRefresh enables in android? - android

I have a SwipeToRefresh when I scroll down listview and when scroll up Swipe to refresh gets enable without going on top of listview and also want to clear all data from listview and add new data it works fine but when I scroll down and send request it only show progress at bottom not adding data .How can I avoid this problem.pls let me know .
code:-
private void getDetails() {// get details of user from shared preference...
CLoginSessionManagement m_oSessionManagement = new CLoginSessionManagement(getActivity());// crating object of Login Session
HashMap<String, String> user = m_oSessionManagement.getLoginDetails();// get String from Login Session
m_szMobileNumber = user.get(CLoginSessionManagement.s_szKEY_MOBILE).trim();// getting password from saved preferences..........
m_szEncryptedPassword = user.get(CLoginSessionManagement.s_szKEY_PASSWORD).trim();// getting mobile num from shared preferences...
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// increment of record count
sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// increment of last count...
s_oDataset = new ArrayList<>();// making object of Arraylist
}
private void init() {// initialize controls
m_ProgressBar = (ProgressBar) m_Main.findViewById(R.id.progressBar1);// finding Id of progressview
m_ProgressBar.setVisibility(View.GONE);// make profressView Invisible first time
m_ListView = (ListView) m_Main.findViewById(R.id.dealList);// findind Id of Listview
m_ListView.setFadingEdgeLength(0);
/*Swipe to refresh code*/
mSwipeRefresh = (SwipeRefreshLayout) m_Main.findViewById(R.id.activity_main_swipe_refresh_layout);
if (NetworkUtil.isConnected(getActivity())) {
postDealListingDatatoServer();
} else {
Toast.makeText(getActivity(), "Please check internet connection !", Toast.LENGTH_LONG).show();
}
mSwipeRefresh.setColorSchemeResources(R.color.refresh_progress_1);
mSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
/*Here check net connection avialable or not */
if (NetworkUtil.isConnected(getActivity())) {
s_oDataset.clear();
m_ListView.removeFooterView(mFooter);
m_ListView.invalidate();
m_n_DeafalutLastCount = 0;
sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// convert int value to string /////
swipeData();
} else {
Toast.makeText(getActivity(), "Please check internet connection !", Toast.LENGTH_LONG).show();
if (mSwipeRefresh.isRefreshing()) {
mSwipeRefresh.setRefreshing(false);
}
}
}
});
m_ListView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
boolean enable = false;
if (m_ListView != null && m_ListView.getChildCount() > 0) {
// check if the first item of the list is visible
boolean firstItemVisible = m_ListView.getFirstVisiblePosition() == 0;
// check if the top of the first item is visible
boolean topOfFirstItemVisible = m_ListView.getChildAt(0).getTop() == 0;
// enabling or disabling the refresh layout
enable = firstItemVisible && topOfFirstItemVisible;
}
mSwipeRefresh.setEnabled(enable);
}
});
m_n_FormImage = new int[]{// defining Images in Integer array
R.drawable.amazon,
R.drawable.whatsapp,
R.drawable.zorpia,
R.drawable.path,
R.drawable.app_me,
R.drawable.evernote,
R.drawable.app_me};
}
/*This is new changes in code ....using Volley instead of AsynkTask*/
/*This method send request to server for deallisting*/
// this method send request to server for deal list....
public void postDealListingDatatoServer() {
try {
String json;
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();// making object of Jsons.
jsonObject.put("agentCode", m_szMobileNumber);// put mobile number
jsonObject.put("pin", m_szEncryptedPassword);// put password
jsonObject.put("recordcount", sz_RecordCount);// put record count
jsonObject.put("lastcountvalue", sz_LastCount);// put last count
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();// convert Json object to string
System.out.println("Request:-" + json);
m_Dialog = DialogUtils.showProgressDialog(getActivity(), "Please wait while loading deals...");
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, CServerAPI.m_DealListingURL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("Response:-" + response);
m_Dialog.dismiss();
try {
JSONArray posts = response.optJSONArray("dealList");// get Deal list in array from response
for (int i = 0; i < posts.length(); i++) {// loop for counting deals from server
JSONObject post = posts.getJSONObject(i);// counting deal based on index
item = new CDealAppDatastorage();// creating object of DealAppdata storage
item.setM_szHeaderText(post.getString("dealname"));// get deal name from response
item.setM_szsubHeaderText(post.getString("dealcode"));// get dealcode from response
item.setM_szDealValue(post.getString("dealvalue"));// get deal value from response
item.setM_n_Image(m_n_FormImage[i]);//set Image Index wise(Dummy)
s_oDataset.add(item);// add all items in ArrayList
}
mFooter = View.inflate(getActivity(), R.layout.footer, null);
if (!s_oDataset.isEmpty()) {// condition if data in arraylist is not empty
// Adding Load More button to lisview at bottom
m_ListView.addFooterView(mFooter);// add footer in listview
m_oAdapter = new CDealAppListingAdapter(getActivity(), s_oDataset);// create adapter object and add arraylist to adapter
m_ListView.setAdapter(m_oAdapter);//adding adapter to recyclerview
} else {
mFooter.setVisibility(View.GONE);// else Load buttonvisibility set to Gone
}
m_ListView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount != 0) {
if (!isLoading) {
isLoading = true;
if (NetworkUtil.isConnected(getActivity())) {
m_n_DefaultRecordCount = 5;// increment of record count by 5 on next load data
m_n_DeafalutLastCount = m_n_DeafalutLastCount + 5;// same here.....as above
String itemscount = String.valueOf(m_ListView.getAdapter().getCount());
System.out.println("Toatal item:-" + itemscount);
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// convert int value to string
sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// convert int value to string /////
loadmoreData();
} else {
Toast.makeText(getActivity(), "Please check internet connection !", Toast.LENGTH_LONG).show();
}
}
} else {
isLoading = false;
}
}
});
if (response.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {//server based conditions
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Connection Lost !", getActivity());
} else if (response.getString("resultdescription").equalsIgnoreCase("Deal List Not Found")) {// serevr based conditions .....
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "No more deals available", getActivity());
mFooter.setVisibility(View.GONE);
} else if (response.getString("resultdescription").equalsIgnoreCase("Technical Failure")) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Technical Failure", getActivity());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("Errror:-" + error);
m_Dialog.dismiss();
if (error instanceof TimeoutError) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.activity_main_swipe_refresh_layout), "Connection lost ! Please try again", getActivity());
} else if (error instanceof NetworkError) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.activity_main_swipe_refresh_layout), "No internet connection", getActivity());
}
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
/*This method send request to server for more deals*/
//this method post request to server to fetch more deal
public void loadmoreData() {
try {
String json;
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();// making object of Jsons.
jsonObject.put("agentCode", m_szMobileNumber);// put mobile number
jsonObject.put("pin", m_szEncryptedPassword);// put password
jsonObject.put("recordcount", sz_RecordCount);// put record count
jsonObject.put("lastcountvalue", sz_LastCount);// put last count
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();// convert Json object to string
System.out.println("Server Request:-" + json);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, CServerAPI.m_DealListingURL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("Response:-" + response);
try {
JSONArray posts = response.optJSONArray("dealList");// GETTING DEAL LIST
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.getJSONObject(i);// GETTING DEAL AT POSITION AT I
item = new CDealAppDatastorage();// object create of DealAppdatastorage
item.setM_szHeaderText(post.getString("dealname"));//getting deal name
item.setM_szsubHeaderText(post.getString("dealcode"));// getting deal code
item.setM_szDealValue(post.getString("dealvalue"));
if (!s_oDataset.contains(item)) {
s_oDataset.add(item);
isLoading = false;
m_oAdapter.notifyDataSetChanged();
}
}
if (response.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {//server based conditions
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Connection Lost !", getActivity());
} else if (response.getString("resultdescription").equalsIgnoreCase("Deal List Not Found")) {// serevr based conditions .....
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "No more deals available", getActivity());
mFooter.setVisibility(View.GONE);
} else if (response.getString("resultdescription").equalsIgnoreCase("Technical Failure")) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Technical Failure", getActivity());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("Error:-" + error);
if (error instanceof TimeoutError) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.activity_main_swipe_refresh_layout), "Connection lost ! Please try again", getActivity());
} else if (error instanceof NetworkError) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.activity_main_swipe_refresh_layout), "No internet connection", getActivity());
}
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
/*This method invoke on swipe to refresh*/
// this method invoke when swipe to refresh enable ....
public void swipeData() {
try {
String json;
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();// making object of Jsons.
jsonObject.put("agentCode", m_szMobileNumber);// put mobile number
jsonObject.put("pin", m_szEncryptedPassword);// put password
jsonObject.put("recordcount", sz_RecordCount);// put record count
jsonObject.put("lastcountvalue", sz_LastCount);// put last count
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();// convert Json object to string
System.out.println("Server Request:-" + json);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, CServerAPI.m_DealListingURL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("Response:-" + response);
mSwipeRefresh.setRefreshing(false);
try {
JSONArray posts = response.optJSONArray("dealList");// get Deal list in array from response
for (int i = 0; i < posts.length(); i++) {// loop for counting deals from server
JSONObject post = posts.getJSONObject(i);// counting deal based on index
item = new CDealAppDatastorage();// creating object of DealAppdata storage
item.setM_szHeaderText(post.getString("dealname"));// get deal name from response
item.setM_szsubHeaderText(post.getString("dealcode"));// get dealcode from response
item.setM_szDealValue(post.getString("dealvalue"));// get deal value from response
item.setM_n_Image(m_n_FormImage[i]);//set Image Index wise(Dummy)
s_oDataset.add(item);// add all items in ArrayList
}
mFooter = View.inflate(getActivity(), R.layout.footer, null);
if (!s_oDataset.isEmpty()) {// condition if data in arraylist is not empty
// Adding Load More button to lisview at bottom
m_ListView.addFooterView(mFooter);// add footer in listview
m_oAdapter = new CDealAppListingAdapter(getActivity(), s_oDataset);// create adapter object and add arraylist to adapter
m_ListView.setAdapter(m_oAdapter);//adding adapter to recyclerview
} else {
mFooter.setVisibility(View.GONE);// else Load buttonvisibility set to Gone
}
m_ListView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount != 0) {
if (!isLoading) {
isLoading = true;
if (NetworkUtil.isConnected(getActivity())) {
m_n_DefaultRecordCount = 5;// increment of record count by 5 on next load data
m_n_DeafalutLastCount = m_n_DeafalutLastCount + 5;// same here.....as above
String itemscount = String.valueOf(m_ListView.getAdapter().getCount());
System.out.println("Toatal item:-" + itemscount);
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// convert int value to string
sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// convert int value to string /////
loadmoreData();// this method load more deals from server ....
} else {
Toast.makeText(getActivity(), "Please check internet connection !", Toast.LENGTH_LONG).show();
}
}
}
}
});
if (response.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {//server based conditions
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Connection Lost !", getActivity());
} else if (response.getString("resultdescription").equalsIgnoreCase("Deal List Not Found")) {// serevr based conditions .....
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "No more deals available", getActivity());
} else if (response.getString("resultdescription").equalsIgnoreCase("Technical Failure")) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Technical Failure", getActivity());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("Error:-" + error);
mSwipeRefresh.setRefreshing(false);
if (error instanceof TimeoutError) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.activity_main_swipe_refresh_layout), "Connection lost ! Please try again", getActivity());
} else if (error instanceof NetworkError) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.activity_main_swipe_refresh_layout), "No internet connection", getActivity());
}
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
XML which contain swipe to refresh :-
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/activity_main_swipe_refresh_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<include layout="#layout/deal_list_content"/>
</android.support.v4.widget.SwipeRefreshLayout>
code for :- #layout/deal_list_content
<RelativeLayout
android:id="#+id/mainLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!---->
<ListView
android:id="#+id/dealList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#color/transparent"
android:dividerHeight="2dp"
android:padding="5sp"
android:scrollbarSize="4dp"
android:scrollbarThumbVertical="#drawable/scrollbar"/>
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
android:layout_marginBottom="10dp">
</ProgressBar>
</RelativeLayout>

SwipeRefreshView can only support one direct child. If I'm not wrong, it should only encapsulate #id/dealList.

SwipeRefreshLayout can have just one direct child. Change your layout to something along the lines of -
<RelativeLayout ...>
<SwipeRefreshLayout ...>
<ListView ...../>
</SwipeRefreshLayout>
<ProgressBar .../>
</RelativeLayout>

Related

How to dismiss dialog when attached to activity?

I have an app which contain MainActivityand that activity contains a fragment which send server request and during that i am showing a ProgressDialog. But while progress dialog is displaying, if i move from MainActivity to another activity it was giving me error "Fragment not attached to activity".
How can i resolve this issue?
code:-
/*This method send request to server for more deals*/
private void loadmoreData() {
if (mSwipeRefresh.isRefreshing()) {
mSwipeRefresh.setRefreshing(false);
}
try {
String json;
// 3. build jsonObject
final JSONObject jsonObject = new JSONObject();// making object of Jsons.
jsonObject.put(ServerRequestKeyStorage.s_szAGENT_CODE, m_szMobileNumber);// put mobile number
jsonObject.put(ServerRequestKeyStorage.s_szPASSWORD, m_szEncryptedPassword);// put password
jsonObject.put(ServerRequestKeyStorage.s_szRECORD_COUNT, sz_RecordCount);// put record count
jsonObject.put(ServerRequestKeyStorage.s_szLAST_COUNT, sz_LastCount);// put last count
Log.d("CAppList:", sz_RecordCount);
Log.d("Capplist:", sz_LastCount);
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();// convert Json object to string
Log.i(TAG, "Server Request:-" + json);
m_Dialog = DialogUtils.showProgressDialog(getActivity(), getString(R.string.loading_more_deals));
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
final String imgPath = APIStorage.IREWARDS_URL + APIStorage.s_szImagePath;
final String m_DealListingURL = APIStorage.IREWARDS_URL + APIStorage.s_szDEALLISTING_URL;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, m_DealListingURL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Server Response:-" + response);
Activity activity = getActivity();
if (activity!=null&&isAdded()){
m_Dialog.dismiss();
}
try {
int nResultCodeFromServer = Integer.parseInt(response.getString(ServerResponseStorage.s_szRESULT_CODE));
if (nResultCodeFromServer == CStaticVar.m_kTRANSACTION_SUCCESS) {
// Select the last row so it will scroll into view...
JSONArray posts = response.optJSONArray(ServerResponseStorage.s_szDEAL_ARRAY);// GETTING DEAL LIST
for (int i = 0; i < posts.length(); i++) {
try {
JSONObject post = posts.getJSONObject(i);// GETTING DEAL AT POSITION AT I
item = new CDealAppDatastorage();// object create of DealAppdatastorage
item.setM_szHeaderText(post.getString(ServerResponseStorage.s_szDEAL_NAME));//getting deal name
item.setM_szsubHeaderText(post.getString(ServerResponseStorage.s_szDEAL_CODE));// getting deal code
item.setM_szDealValue(post.getString(ServerResponseStorage.s_szDEAL_VAlUE));
item.setM_szDetails(post.getString(ServerResponseStorage.s_szDEAL_DETAILS));
String logo = post.getString(ServerResponseStorage.s_szDEAL_LOGO);
item.setM_szLogoPath(imgPath + logo);
Log.e(TAG, "Logo Path::" + item.getM_szLogoPath());
if (!s_oDataset.contains(item)) {
s_oDataset.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
}
m_oAdapter.notifyDataSetChanged();
arrayCount = posts.length();// finding length of deals coming in response from server.
// read stored value from shared preference
int n_oLastCountLength = m_oPreferenceHelper.getIntPreference(LAST_COUNT_LENGTH);
int accumulateLastCount = n_oLastCountLength + arrayCount;
/*Here we are saving deal length in shared preference*/
// save incremental length
m_oPreferenceHelper.saveIntegerValue(LAST_COUNT_LENGTH, accumulateLastCount);
// m_ListView.removeFooterView(mFooter);
m_ListView.setSelection(m_oAdapter.getCount() - posts.length());
}
if (nResultCodeFromServer == CStaticVar.m_kCONNECTION_LOST) {//server based conditions
CSnackBar.showSnackBarError(m_MainLayout, getString(R.string.connection_not_available), getActivity());
// m_ListView.removeFooterView(mFooter);
} else if (nResultCodeFromServer == CStaticVar.m_kDEAL_NOT_FOUND) {// serevr based conditions .....
CSnackBar.showSnackBarError(m_MainLayout, getString(R.string.no_more_deals), getActivity());
// //*Counting loading footer*/
// if (m_ListView.getFooterViewsCount() != 0) {
// m_ListView.removeFooterView(mFooter);
// }
} else if (nResultCodeFromServer == CStaticVar.m_kTECHNICAL_FAILURE) {
CSnackBar.showSnackBarError(m_MainLayout, getString(R.string.technical_failure), getActivity());
} else if (nResultCodeFromServer == CStaticVar.m_kALREADY_AVAIL_BENEFIT) {
CSnackBar.showSnackBarError(m_MainLayout, getString(R.string.already_avail_deals), getActivity());
} else if (nResultCodeFromServer == CStaticVar.m_kTIMED_OUT) {
CSnackBar.showSnackBarError(m_MainLayout, getString(R.string.times_out), getActivity());
// m_ListView.removeFooterView(mFooter);
} else if (nResultCodeFromServer == CStaticVar.m_kERROR_IN_DB) {
CSnackBar.showSnackBarError(m_MainLayout, "Something happened wrong in DB. Please contact support#starxsoft.com", getActivity());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error::" + error);
Activity activity = getActivity();
if (activity!=null&&isAdded()){
m_Dialog.dismiss();
}
if (error instanceof TimeoutError) {
CSnackBar.showSnackBarError(m_MainLayout, getString(R.string.connection_timed_out), getActivity());
} else if (error instanceof NetworkError) {
CSnackBar.showSnackBarError(m_MainLayout, getString(R.string.no_internet_warning), getActivity());
}
}
});
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
In this during dismiss and showing a dialog it gives me error.

How to cancel single volley request in android?

I have a MainActivity which adds a Fragment which send server request and contained a ListView with swipe to refresh ,Problem is that when I swipe down to refresh it is sending server request at the same time if I press device back app will exist at this point of time app crash.How to achieve this problem.
code for on swipe to refresh send server request.
mSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
/*Here check net connection avialable or not */
if (NetworkUtil.isConnected(getActivity())) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// convert int value to string
int length = preferences.getInt("length", 0);
sz_LastCount = String.valueOf(length);// convert int value to string /////
Log.e(TAG, "Last Count::" + sz_LastCount);
Log.e(TAG, "Record count::" + sz_RecordCount);
/*Send Request to Server for more data */
loadmoreOnSwipe();
}
}, 3500);
} else {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "No internet connection available", getActivity());
if (mSwipeRefresh.isRefreshing()) {
mSwipeRefresh.setRefreshing(false);
}
}
}
});
/*This method send request to server for more deals*/
private void loadmoreOnSwipe() {
try {
String json;
// 3. build jsonObject
final JSONObject jsonObject = new JSONObject();// making object of Jsons.
jsonObject.put("agentCode", m_szMobileNumber);// put mobile number
jsonObject.put("pin", m_szEncryptedPassword);// put password
jsonObject.put("recordcount", sz_RecordCount);// put record count
jsonObject.put("lastcountvalue", sz_LastCount);// put last count
Log.d("CAppList:", sz_RecordCount);
Log.d("Capplist:", sz_LastCount);
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();// convert Json object to string
Log.i(TAG, "Server Request:-" + json);
final String m_DealListingURL = "http://202.131.144.132:8080";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, m_DealListingURL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, "Server Response:-" + response);
if (mSwipeRefresh.isRefreshing()) {
mSwipeRefresh.setRefreshing(false);
}
try {
int nResultCodeFromServer = Integer.parseInt(response.getString("resultcode"));
if (nResultCodeFromServer == CStaticVar.m_kTRANSACTION_SUCCESS) {
// Select the last row so it will scroll into view...
JSONArray posts = response.optJSONArray("dealList");// GETTING DEAL LIST
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.getJSONObject(i);// GETTING DEAL AT POSITION AT I
item = new CDealAppDatastorage();// object create of DealAppdatastorage
item.setM_szHeaderText(post.getString("dealname"));//getting deal name
item.setM_szsubHeaderText(post.getString("dealcode"));// getting deal code
item.setM_szDealValue(post.getString("dealvalue"));
if (!s_oDataset.contains(item)) {
s_oDataset.add(item);
}
}
m_oAdapter.notifyDataSetChanged();
arrayCount = posts.length();// finding length of deals coming in response from server.
// read stored value from shared preference
int length = preferences.getInt("length", 0);
/*adding current array count with earlier saved value in shared preference*/
int accumulateLastCount = length + arrayCount;
/*Here we are saving deal length in shared preference*/
// save incremental length
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("length", accumulateLastCount);
editor.apply();
// int add = CLastCountData.getInstance().getS_szLastCount() + arrayCount;
//CLastCountData.getInstance().setS_szLastCount(add);
m_ListView.removeFooterView(mFooter);
m_ListView.setSelection(m_oAdapter.getCount() - posts.length());
}
if (nResultCodeFromServer == CStaticVar.m_kCONNECTION_LOST) {//server based conditions
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Connection Lost !", getActivity());
m_ListView.removeFooterView(mFooter);
} else if (nResultCodeFromServer == CStaticVar.m_kDEAL_NOT_FOUND) {// serevr based conditions .....
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "No more deals available", getActivity());
//*Counting loading footer*/
if (m_ListView.getFooterViewsCount() != 0) {
m_ListView.removeFooterView(mFooter);
}
} else if (nResultCodeFromServer == CStaticVar.m_kTECHNICAL_FAILURE) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Technical Failure", getActivity());
} else if (nResultCodeFromServer == CStaticVar.m_kALREADY_AVAIL_BENEFIT) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "You have already avail the benefit of this deal", getActivity());
} else if (nResultCodeFromServer == CStaticVar.m_kTIMED_OUT) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Timed Out", getActivity());
m_ListView.removeFooterView(mFooter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("Error:-" + error);
if (mSwipeRefresh.isRefreshing()) {
mSwipeRefresh.setRefreshing(false);
}
if (error instanceof TimeoutError) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Connection lost ! Please try again", getActivity());
} else if (error instanceof NetworkError) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "No internet connection", getActivity());
}
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
you can set a tag to your request. It will be an identification for every request. After that, your request queue has a cancelAll method, it is require a tag.
//Before you add your request to the queue, set the tag, the tag can be a string, or sth like that.
yourRequest.setTag(tag);
After that, when you want to cancel your request :
requestQueue.cancelAll(tag);

How to clear data in listview and load new data in listview in android on swipe to refresh?

I have a list view which add data from server in first hit it add 5 data and when scroll down it add more 5 data from server and have a swipe to refresh on pull down swipe it clears data and add 5 data from server and again next hit add 5 more same like when scroll down .problem is that right now I have load more button which I want to replace with progress bar at bottom of listview and when I swipe down to refresh it add more 5 data first time and when on second swipe it can't how can I archive this problem.
code:-
private int m_n_DefaultRecordCount = 5;// intiallly record count is 5.
private int m_n_DeafalutLastCount = 0;//initally lastcount is 0.
private SwipeRefreshLayout mSwipeRefresh;
private Button btnLoadMore;
private ProgressBar m_ProgressBar;
private ProgressDialog m_Dialog;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(getActivity(), "Login successfully", Toast.LENGTH_SHORT).show();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
m_Main = inflater.inflate(R.layout.deal_listing, container, false);//intialize mainLayout
getDetails();// get deatail of user from sharedpreference......
init();//initialize metho
return m_Main;
}
private void getDetails() {// get details of user from shared preference...
CLoginSessionManagement m_oSessionManagement = new CLoginSessionManagement(getActivity());// crating object of Login Session
HashMap<String, String> user = m_oSessionManagement.getLoginDetails();// get String from Login Session
m_szMobileNumber = user.get(CLoginSessionManagement.s_szKEY_MOBILE).trim();// getting password from saved preferences..........
m_szEncryptedPassword = user.get(CLoginSessionManagement.s_szKEY_PASSWORD).trim();// getting mobile num from shared preferences...
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// increment of record count
sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// increment of last count...
s_oDataset = new ArrayList<>();// making object of Arraylist
if (NetworkUtil.isConnected(getActivity())) {
postDealListingDatatoServer();
} else {
Toast.makeText(getActivity(), "Please check internet connection !", Toast.LENGTH_LONG).show();
}
}
private void init() {// initialize controls
m_ProgressBar = (ProgressBar) m_Main.findViewById(R.id.progressBar1);// finding Id of progressview
m_ProgressBar.setVisibility(View.GONE);// make profressView Invisible first time
/*Swipe to refresh code*/
mSwipeRefresh = (SwipeRefreshLayout) m_Main.findViewById(R.id.activity_main_swipe_refresh_layout);
mSwipeRefresh.setColorSchemeResources(R.color.refresh_progress_1);
mSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
/*Here check net connection avialable or not */
if (NetworkUtil.isConnected(getActivity())) {
m_ListView.removeFooterView(btnLoadMore);
s_oDataset.clear();
m_n_DeafalutLastCount = 0;
sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// convert int value to string /////
swipeData();
} else {
Toast.makeText(getActivity(), "Please check internet connection !", Toast.LENGTH_LONG).show();
if (mSwipeRefresh.isRefreshing()) {
mSwipeRefresh.setRefreshing(false);
}
}
}
});
m_n_FormImage = new int[]{// defining Images in Integer array
R.drawable.amazon,
R.drawable.whatsapp,
R.drawable.zorpia,
R.drawable.path,
R.drawable.app_me,
R.drawable.evernote,
R.drawable.app_me};
m_ListView = (ListView) m_Main.findViewById(R.id.dealList);// findind Id of Listview
m_ListView.setFadingEdgeLength(0);
m_ListView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem == 0) {
mSwipeRefresh.setEnabled(true);
} else {
mSwipeRefresh.setEnabled(false);
}
}
});
}
/*This is new changes in code ....using Volley instead of AsynkTask*/
/*This method send request to server for deallisting*/
// this method send request to server for deal list....
public void postDealListingDatatoServer() {
try {
String json;
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();// making object of Jsons.
jsonObject.put("agentCode", m_szMobileNumber);// put mobile number
jsonObject.put("pin", m_szEncryptedPassword);// put password
jsonObject.put("recordcount", sz_RecordCount);// put record count
jsonObject.put("lastcountvalue", sz_LastCount);// put last count
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();// convert Json object to string
System.out.println("Request:-" + json);
m_Dialog = DialogUtils.showProgressDialog(getActivity(), "Please wait while loading deals...");
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, CServerAPI.m_DealListingURL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("Response:-" + response);
m_Dialog.dismiss();
try {
JSONArray posts = response.optJSONArray("dealList");// get Deal list in array from response
for (int i = 0; i < posts.length(); i++) {// loop for counting deals from server
JSONObject post = posts.getJSONObject(i);// counting deal based on index
item = new CDealAppDatastorage();// creating object of DealAppdata storage
item.setM_szHeaderText(post.getString("dealname"));// get deal name from response
item.setM_szsubHeaderText(post.getString("dealcode"));// get dealcode from response
item.setM_szDealValue(post.getString("dealvalue"));// get deal value from response
item.setM_n_Image(m_n_FormImage[i]);//set Image Index wise(Dummy)
s_oDataset.add(item);// add all items in ArrayList
}
// LoadMore button
btnLoadMore = new Button(getActivity());// creating button
btnLoadMore.setText("LOAD MORE DEALS");// set Text in Button
btnLoadMore.setBackgroundResource(R.drawable.button_boarder);// set Background Resource
btnLoadMore.setTypeface(Typeface.DEFAULT_BOLD);
btnLoadMore.setTextSize(14);
btnLoadMore.setTextColor(Color.WHITE);// set Color of button text
btnLoadMore.setGravity(Gravity.CENTER);// set Gravity of button text
if (!s_oDataset.isEmpty()) {// condition if data in arraylist is not empty
// Adding Load More button to lisview at bottom
m_ListView.addFooterView(btnLoadMore);// add footer in listview
m_oAdapter = new CDealAppListingAdapter(getActivity(), s_oDataset);// create adapter object and add arraylist to adapter
m_ListView.setAdapter(m_oAdapter);//adding adapter to recyclerview
} else {
btnLoadMore.setVisibility(View.GONE);// else Load buttonvisibility set to Gone
}
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {// load more button onclick listener
if (NetworkUtil.isConnected(getActivity())) {
m_n_DefaultRecordCount = 5;// increment of record count by 5 on next load data
m_n_DeafalutLastCount = m_n_DeafalutLastCount + 5;// same here.....as above
String itemscount = String.valueOf(m_ListView.getAdapter().getCount());
System.out.println("Toatal item:-" + itemscount);
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// convert int value to string
sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// convert int value to string /////
loadmoreData();
} else {
Toast.makeText(getActivity(), "Please check internet connection !", Toast.LENGTH_LONG).show();
}
}
});
if (response.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {//server based conditions
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Connection Lost !", getActivity());
} else if (response.getString("resultdescription").equalsIgnoreCase("Deal List Not Found")) {// serevr based conditions .....
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "No more deals available", getActivity());
} else if (response.getString("resultdescription").equalsIgnoreCase("Technical Failure")) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Technical Failure", getActivity());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("Errror:-" + error);
m_Dialog.dismiss();
if (error instanceof TimeoutError) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.activity_main_swipe_refresh_layout), "Connection lost ! Please try again", getActivity());
} else if (error instanceof NetworkError) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.activity_main_swipe_refresh_layout), "No internet connection", getActivity());
}
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
/*This method send request to server for more deals*/
//this method post request to server to fetch more deal
public void loadmoreData() {
try {
String json;
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();// making object of Jsons.
jsonObject.put("agentCode", m_szMobileNumber);// put mobile number
jsonObject.put("pin", m_szEncryptedPassword);// put password
jsonObject.put("recordcount", sz_RecordCount);// put record count
jsonObject.put("lastcountvalue", sz_LastCount);// put last count
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();// convert Json object to string
System.out.println("Server Request:-" + json);
m_ProgressBar.setVisibility(View.VISIBLE);// SHOW PROGRESS BAR
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, CServerAPI.m_DealListingURL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("Response:-" + response);
try {
JSONArray posts = response.optJSONArray("dealList");// GETTING DEAL LIST
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.getJSONObject(i);// GETTING DEAL AT POSITION AT I
item = new CDealAppDatastorage();// object create of DealAppdatastorage
item.setM_szHeaderText(post.getString("dealname"));//getting deal name
item.setM_szsubHeaderText(post.getString("dealcode"));// getting deal code
item.setM_szDealValue(post.getString("dealvalue"));
if (!s_oDataset.contains(item)) {
s_oDataset.add(item);
m_oAdapter.notifyDataSetChanged();
}
}
if (response.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {//server based conditions
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Connection Lost !", getActivity());
} else if (response.getString("resultdescription").equalsIgnoreCase("Deal List Not Found")) {// serevr based conditions .....
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "No more deals available", getActivity());
} else if (response.getString("resultdescription").equalsIgnoreCase("Technical Failure")) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Technical Failure", getActivity());
}
} catch (JSONException e) {
e.printStackTrace();
}
m_ProgressBar.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("Error:-" + error);
m_ProgressBar.setVisibility(View.GONE);
if (error instanceof TimeoutError) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.activity_main_swipe_refresh_layout), "Connection lost ! Please try again", getActivity());
} else if (error instanceof NetworkError) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.activity_main_swipe_refresh_layout), "No internet connection", getActivity());
}
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
/*This method invoke on swipe to refresh*/
// this method invoke when swipe to refresh enable ....
public void swipeData() {
try {
String json;
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();// making object of Jsons.
jsonObject.put("agentCode", m_szMobileNumber);// put mobile number
jsonObject.put("pin", m_szEncryptedPassword);// put password
jsonObject.put("recordcount", sz_RecordCount);// put record count
jsonObject.put("lastcountvalue", sz_LastCount);// put last count
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();// convert Json object to string
System.out.println("Server Request:-" + json);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, CServerAPI.m_DealListingURL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("Response:-" + response);
mSwipeRefresh.setRefreshing(false);
try {
JSONArray posts = response.optJSONArray("dealList");// get Deal list in array from response
for (int i = 0; i < posts.length(); i++) {// loop for counting deals from server
JSONObject post = posts.getJSONObject(i);// counting deal based on index
item = new CDealAppDatastorage();// creating object of DealAppdata storage
item.setM_szHeaderText(post.getString("dealname"));// get deal name from response
item.setM_szsubHeaderText(post.getString("dealcode"));// get dealcode from response
item.setM_szDealValue(post.getString("dealvalue"));// get deal value from response
item.setM_n_Image(m_n_FormImage[i]);//set Image Index wise(Dummy)
s_oDataset.add(item);// add all items in ArrayList
}
// LoadMore button
btnLoadMore = new Button(getActivity());// creating button
btnLoadMore.setText("LOAD MORE DEALS");// set Text in Button
btnLoadMore.setBackgroundResource(R.drawable.button_boarder);// set Background Resource
btnLoadMore.setTypeface(Typeface.DEFAULT_BOLD);
btnLoadMore.setTextSize(14);
btnLoadMore.setTextColor(Color.WHITE);// set Color of button text
btnLoadMore.setGravity(Gravity.CENTER);// set Gravity of button text
if (!s_oDataset.isEmpty()) {// condition if data in arraylist is not empty
// Adding Load More button to lisview at bottom
m_ListView.addFooterView(btnLoadMore);// add footer in listview
m_oAdapter = new CDealAppListingAdapter(getActivity(), s_oDataset);// create adapter object and add arraylist to adapter
m_ListView.setAdapter(m_oAdapter);//adding adapter to recyclerview
} else {
btnLoadMore.setVisibility(View.GONE);// else Load buttonvisibility set to Gone
}
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {// load more button onclick listener
if (NetworkUtil.isConnected(getActivity())) {
m_n_DefaultRecordCount = 5;// increment of record count by 5 on next load data
m_n_DeafalutLastCount = m_n_DeafalutLastCount + 5;// same here.....as above
String itemscount = String.valueOf(m_ListView.getAdapter().getCount());
System.out.println("Toatal item:-" + itemscount);
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// convert int value to string
sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// convert int value to string /////
loadmoreData();// this method load more deals from server ....
} else {
Toast.makeText(getActivity(), "Please check internet connection !", Toast.LENGTH_LONG).show();
}
}
});
if (response.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {//server based conditions
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Connection Lost !", getActivity());
} else if (response.getString("resultdescription").equalsIgnoreCase("Deal List Not Found")) {// serevr based conditions .....
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "No more deals available", getActivity());
} else if (response.getString("resultdescription").equalsIgnoreCase("Technical Failure")) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Technical Failure", getActivity());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("Error:-" + error);
mSwipeRefresh.setRefreshing(false);
if (error instanceof TimeoutError) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.activity_main_swipe_refresh_layout), "Connection lost ! Please try again", getActivity());
} else if (error instanceof NetworkError) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.activity_main_swipe_refresh_layout), "No internet connection", getActivity());
}
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
}

How to make Swipe to refresh using json in android?

I have an application contain listview and have swipe to refresh.
Problem :- In oncreate method I executed Url and have footer named as "load more" ,on first Request to server I will show 5 list items like:- recordCount=5,lastcount=0,when user click on "load more" send request like recordCount=5,lastCount=5 same as another click recordCound will remain same and LastCount incremented by 5.what I want when swipe to refresh RecordCound will become 5 and lastCount will become 0.How can I do that
here is code:-
private int m_n_DefaultRecordCount = 5;// intiallly record count is 5.
private int m_n_DeafalutLastCount = 0;//initally lastcount is 0.
private String sz_RecordCount;// //declaring String record count variable variable
private String sz_LastCount;//declaring String lastcount variable
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
m_Main = inflater.inflate(R.layout.deal_listing, container, false);//intialize mainLayout
getDetails();// get deatail of user from sharedpreference......
init();//initialize metho
return m_Main;
}
private void getDetails() {// get details of user from shared preference...
CLoginSessionManagement m_oSessionManagement = new CLoginSessionManagement(getActivity());// crating object of Login Session
HashMap<String, String> user = m_oSessionManagement.getLoginDetails();// get String from Login Session
m_szMobileNumber = user.get(CLoginSessionManagement.s_szKEY_MOBILE).trim();// getting password from saved preferences..........
m_szEncryptedPassword = user.get(CLoginSessionManagement.s_szKEY_PASSWORD).trim();// getting mobile num from shared preferences...
System.out.println("Deal Mobile:-" + m_szMobileNumber);
s_oDataset = new ArrayList<>();// making object of Arraylist
new CDealDataSent().execute(m_DealListingURL);// execute Url to fetch Deal list from serevr.
}
private void init() {// initialize controls
m_connectionText = (TextView) m_Main.findViewById(R.id.notransaction_message);
m_connectionText.setVisibility(View.GONE);
m_LoadMoreProgressView = (CircularProgressView) m_Main.findViewById(R.id.progressBar1);// finding Id of progressview
m_LoadMoreProgressView.setVisibility(View.GONE);// make profressView Invisible first time
mSwipeRefresh = (SwipeRefreshLayout) m_Main.findViewById(R.id.activity_main_swipe_refresh_layout);
mSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
m_ListView.removeFooterView(btnLoadMore);
s_oDataset.clear();
new CDealDataSent().execute(m_DealListingURL);// execute Url to fetch Deal list from serevr.
}
});
m_n_FormImage = new int[]{// defining Images in Integer array
R.drawable.amazon,
R.drawable.whatsapp,
R.drawable.zorpia,
R.drawable.path,
R.drawable.app_me,
R.drawable.evernote,
R.drawable.app_me};
m_ListView = (ListView) m_Main.findViewById(R.id.dealList);// findind Id of Listview
m_ListView.setFadingEdgeLength(0);
m_ListView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem==0){
mSwipeRefresh.setEnabled(true);
}
else{
mSwipeRefresh.setEnabled(false);
}
}
});
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// increment of record count
sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// increment of last count...
}
#SuppressWarnings("deprecation")
private String DealListing(String url) {// this method POST details of user to server
InputStream inputStream;
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json;
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();// making object of Jsons.
jsonObject.put("agentCode", m_szMobileNumber);// put mobile number
jsonObject.put("pin", m_szEncryptedPassword);// put password
jsonObject.put("recordcount", sz_RecordCount);// put record count
jsonObject.put("lastcountvalue", sz_LastCount);// put last count
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();// convert Json object to string
Log.d(TAG, "Server Request:-" + json);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
// 9. receive response as inputStream
inputStream = entity.getContent();
Log.d(TAG, "InputStream:-" + inputStream.toString());
Log.d(TAG, "Response:-" + httpResponse.toString());
StatusLine statusLine = httpResponse.getStatusLine();
Log.d(TAG, "Status Code:-" + statusLine);
int statusCode = statusLine.getStatusCode();
// 10. convert inputstream to string
if (statusCode == 200) {
// 10. convert inputstream to string
s_szresult = CJsonsResponse.convertInputStreamToString(inputStream);
Log.d(TAG, "Server Response:-" + s_szresult);
} else
s_szresult = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
Log.d(TAG, "Response Password:" + m_szEncryptedPassword);
Log.d(TAG, "Record Count:" + sz_RecordCount);
Log.d(TAG, "Last count:-" + sz_LastCount);
// 11. return s_szResult
return s_szresult;
}
#SuppressWarnings("StatementWithEmptyBody")
private void getResponse() throws JSONException {// getting response from serevr ..................
if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {//server based conditions
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Connection Lost !", getActivity());
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Deal List Not Found")) {// serevr based conditions .....
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "No more deals available", getActivity());
}else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Technical Failure")){
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout),"Technical Failure",getActivity());
}
}
// sending deal data to server and retreive Deal list......
class CDealDataSent extends AsyncTask<String, Void, String> {
public CDealAppDatastorage item;// declaring DealAppdataStorage
SpotsDialog dialog = new SpotsDialog(getActivity(),"Please wait while loading");
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.show();
}
#Override
protected String doInBackground(String... urls) {
return DealListing(urls[0]);// sending data to server...
}
// onPostExecute displays the results of the AsyncTask.
#SuppressWarnings("deprecation")
#SuppressLint("SetTextI18n")
#Override
protected void onPostExecute(final String result) {// this method Update UI
mSwipeRefresh.setRefreshing(false);
dialog.dismiss();
try {
m_oResponseobject = new JSONObject(result);// getting response from server
JSONArray posts = m_oResponseobject.optJSONArray("dealList");// get Deal list in array from response
for (int i = 0; i < posts.length(); i++) {// loop for counting deals from server
JSONObject post = posts.getJSONObject(i);// counting deal based on index
item = new CDealAppDatastorage();// creating object of DealAppdata storage
item.setM_szHeaderText(post.getString("dealname"));// get deal name from response
item.setM_szsubHeaderText(post.getString("dealcode"));// get dealcode from response
item.setM_szDealValue(post.getString("dealvalue"));// get deal value from response
item.setM_n_Image(m_n_FormImage[i]);//set Image Index wise(Dummy)
s_oDataset.add(item);// add all items in ArrayList
}
// LoadMore button
btnLoadMore = new Button(getActivity());// creating button
btnLoadMore.setText("LOAD MORE DEALS");// set Text in Button
btnLoadMore.setBackgroundResource(R.drawable.button_boarder);// set Background Resource
btnLoadMore.setTextAppearance(getActivity(), android.R.style.TextAppearance_DeviceDefault_Medium);// setting Text appearence of button text
btnLoadMore.setTextColor(Color.WHITE);// set Color of button text
btnLoadMore.setGravity(Gravity.CENTER);// set Gravity of button text
if (!s_oDataset.isEmpty()) {// condition if data in arraylist is not empty
// Adding Load More button to lisview at bottom
m_ListView.addFooterView(btnLoadMore);// add footer in listview
m_oAdapter = new CDealAppListingAdapter(getActivity(), s_oDataset);// create adapter object and add arraylist to adapter
m_ListView.setAdapter(m_oAdapter);//adding adapter to recyclerview
m_oAdapter.notifyDataSetChanged();// notify adapter about changes in List
} else {
btnLoadMore.setVisibility(View.GONE);// else Load buttonvisibility set to Gone
}
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {// load more button onclick listener
m_n_DefaultRecordCount = 5;// increment of record count by 5 on next load data
m_n_DeafalutLastCount = m_n_DeafalutLastCount + 5;// same here.....as above
String itemscount = String.valueOf(m_ListView.getAdapter().getCount());
System.out.println("Toatal item:-"+itemscount);
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// convert int value to string
sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// convert int value to string /////
new DealNext().execute(m_DealListingURL);// POST DATA TO SERVER TO LOAD MORE DATA......
}
});
getResponse();// get response from server....
} catch (JSONException e) {
e.printStackTrace();
}
}
}
// sending data and receive reponse on second hit T LOAD MORE DATA when show more Btn clicked..............
private class DealNext extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
m_LoadMoreProgressView.setVisibility(View.VISIBLE);// SHOW PROGRESS BAR
}
#Override
protected String doInBackground(String... urls) {
//My Background tasks are written here
synchronized (this) {
return DealListing(urls[0]);// POST DATA TO SERVER
}
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
m_LoadMoreProgressView.setVisibility(View.GONE);// DISMISS PROGRESS BAR..........
try {
m_oResponseobject = new JSONObject(result);// getting response from server
final JSONArray posts = m_oResponseobject.optJSONArray("dealList");// GETTING DEAL LIST
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.getJSONObject(i);// GETTING DEAL AT POSITION AT I
item = new CDealAppDatastorage();// object create of DealAppdatastorage
item.setM_szHeaderText(post.getString("dealname"));//getting deal name
item.setM_szsubHeaderText(post.getString("dealcode"));// getting deal code
item.setM_szDealValue(post.getString("dealvalue"));
if (!s_oDataset.contains(item)) {
s_oDataset.add(item);
}
}
// get listview current position - used to maintain scroll position
int currentPosition = m_ListView.getFirstVisiblePosition();
m_oAdapter = new CDealAppListingAdapter(getActivity(), s_oDataset);
m_ListView.setAdapter(m_oAdapter);
// Setting new scroll position
m_ListView.setSelectionFromTop(currentPosition + 1, 0);
getResponse();// getting response from server.....and also here response based logics...
} catch (JSONException e) {
e.printStackTrace();
}
}
}

Load more JSON data into listview on scrolling, using Volley library

I tried to implement the code given in the tutorial below to create an endless list.
https://github.com/codepath/android_guides/wiki/Endless-Scrolling-with-AdapterViews
But I'm not sure how to implement the customLoadMoreDataFromApi(int page) method referred to in the tutorial. My JSON Request and parsing method is below. I need help in adding the parameter 'page' to the request and appending new set of data to the list.
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "InitialResponse: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
I don't understand how to use the offset value and add it as a parameter to your API request to retrieve paginated data and deserialize API response and then construct new objects to append to the adapter. Pl Help.
I suggest to you a different solution:
Create a custom component that extends ListView
Custom adapter
Custom listener
..
public class EndlessListView extends ListView implements OnScrollListener {
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
}
..
Now you have to overwrite onScroll to implement the logic:
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (getAdapter() == null)
return ;
if (getAdapter().getCount() == 0)
return ;
int l = visibleItemCount + firstVisibleItem;
if (l >= totalItemCount && !isLoading) {
// It is time to add new data. We call the listener
this.addFooterView(footer);
isLoading = true;
listener.loadData();
}
}
where the listener is defined as:
public static interface EndlessListener {
public void loadData() ;
}
Now when the even is fired and the loadData is called in this method you update the listview content retrieving it remotely.
Hope it helps you. If you like more information i wrote a post about it.
Give a look.

Categories

Resources