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);
Related
If I have a JSON like below:
{
"Division": [
{
"DivisionId": 1,
"DivisionName" : "A"
},
{
"DivisionId": 2,
"DivisionName" : "B"
}
],
"Title": [
{
"TitleId": 11,
"Title": "Title 1"
},
{
"TitleId": 12,
"Title": "Title 2"
}
]
}
How can I get the Division only with its values inside? What I'm trying to achieve is to put the values of Division inside my ArrayList. I'm using Volley to get the JSON result and what I tried is on the onResponse I used JSONArray divisionArr = response.getJSONArray("Division"); and loop it here's my code
JSONArray divisionArr = response.getJSONArray("Division");
for (int i = 0; i < divisionArr.length(); i++) {
Division division = new Division();
JSONObject divisionObj = (JSONObject) divisionArr.get(i);
division.setId(divisionObj.getInt("DivisionId"));
division.setName(divisionObj.getString("DivisionName"));
divisionArrayList.add(division);
}
But I'm having an error ParseError, I maybe doing it wrong, but I don't know what is it. Please help, thank you.
///////
Here's my Volley request
public void getData(Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
try{
String syncCall = Constants.VOLLEY;
request = new JsonObjectRequest(Method.GET,
syncCall,
null,
listener,
errorListener);
request.setRetryPolicy(
new DefaultRetryPolicy(
60000,//DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, // 2500
1,//DefaultRetryPolicy.DEFAULT_MAX_RETRIES, // 1
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); //1f
mRequestQueue.add(request);
} catch (Exception e) {
e.printStackTrace();
}
}
Then in my Activity
private void callSyncVolley() {
final ProgressDialog pd = new ProgressDialog(this);
pd.setMessage("Fetching data....");
pd.show();
Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray divisionArr = response.getJSONArray("Division");
for (int i = 0; i < divisionArr.length(); i++) {
Division division = new Division();
JSONObject divisionObj = (JSONObject) divisionArr.get(i);
division.setId(divisionObj.getInt("DivisionId"));
division.setName(divisionObj.getString("DivisionName"));
divisionArrayList.add(division);
}
pd.dismiss();
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, "Error: " + e.getMessage());
pd.dismiss();
}
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error.networkResponse != null) {
Log.d(TAG, "Error Response code: " + error.networkResponse.statusCode);
pd.dismiss();
}
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
Log.d(TAG, "Error Response code: Timeout/NoConnection");
pd.dismiss();
} else if (error instanceof AuthFailureError) {
//TODO
Log.d(TAG, "Error Response code: AuthFailureError");
pd.dismiss();
} else if (error instanceof ServerError) {
//TODO
Log.d(TAG, "Error Response code: ServerError");
pd.dismiss();
} else if (error instanceof NetworkError) {
//TODO
Log.d(TAG, "Error Response code: NetworkError");
pd.dismiss();
} else if (error instanceof ParseError) {
//TODO
Log.d(TAG, "Error Response code: ParseError");
pd.dismiss();
}
}
};
VolleyRequestManager.getInstance().doRequest().getData(listener, errorListener);
}
The error only shows Error Response code: ParseError
Your JSON format is invalid,
{
"Division": [
{
"DivisionId": 1,
"DivisionName" : A
},
{
"DivisionId": 2,
"DivisionName" : B
}
],
"Title": [
{
"TitleId": 11,
"Title": "Title 1"
},
{
"TitleId": 12,
"Title": "Title 2"
}
],
}
I just pasted your format here
divisionArr.setName(divisionObj.getString("DivisionName")); &&
You are trying to access a String which is not wrapped in double quotes,the String A and String B is not wrapped in double quotes.
Unnecessary comma at the end of the array ],
You can try like this, If you try to get using opt it will get value or null, so you can check that produced further
get and opt type
Use getType() to retrieve a mandatory value. This fails with a JSONException if the requested name has no value or if the value
cannot be coerced to the requested type.
Use optType() to retrieve an optional value. This returns a system- or user-supplied default if the requested name has no value or if the
value cannot be coerced to the requested type.
Example:
getJSONArray - Returns the value mapped by name if it exists and is a JSONArray, or throws otherwise., so we can't handle the upcoming line of code it will go to try block,
But optJSONArray - Returns the value mapped by name if it exists and is a JSONArray, or null otherwise., so using that null value we can handle the code easily
try {
JSONArray divisionArr = response.optJSONArray("Division");
if(divisionArr != null) {
for (int i = 0; i < divisionArr.length(); i++) {
Division divisoin = new Division();
JSONObject divisionObj =divisionArr.optJSONObject(i);
if(divisionObj == null) {
continue;
}
divisionArr.setId(divisionObj.optInt("DivisionId"));
divisionArr.setName(divisionObj.optString("DivisionName"));
divisionArrayList.add(applicationType);
}
}
pd.dismiss();
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, "Error: " + e.getMessage());
pd.dismiss();
}
Instead of Volley use Retrofit coz it'll provide you each JSON Element seperately. And to know how to use Retrofit check this tutorial.
I finally got it right, I recode the whole thing, checked my json result and here's my code
Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray divisionArr = response.getJSONArray("Division");
if(!divisionArr.equals(null)){
for(int i = 0; i < divisionArr.length(); i++){
Division division = new Division();
JSONObject divisionObj = (JSONObject) divisionArr.get(i);
division.setId(divisionObj.getInt("DivisionId"));
division.setName(divisionObj.getString("DivisionName"));
divisionList.add(division);
}
}
pd.dismiss();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
e.getMessage(), Toast.LENGTH_SHORT).show();
pd.dismiss();
}
}
};
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.
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();
}
}
}
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>
I'm using Volley to interact with an API. I need to send a post request (with parameters) to a service that returns a JSON Array.
My Api code is having a function like:
public function Add($tripData) {
$response = "Unsuccessful";
if (isset($tripData)) {
//print_r($tripData);
$tripsModel = new TasksModel();
$tripsModel->user_id = $tripData["user_id"];
$tripsModel->date = $tripData["date"];
$tripsModel->latitude = $tripData["latitude"];
$tripsModel->longitude = $tripData["longitude"];
$tripsModel->location = $tripData["location"];
$tripsModel->notes = $tripData["notes"];
$tripsModel->trip = $tripData["trip"];
$tripsModel->city = $tripData["city"];
$method = new CommonMethods();
$response = $method->save("locationdetails", $tripsModel);
}
echo json_encode($response);
}
I just need to put params.put("data", data) to be in following kind of array:
$taskData["user_id"]=2;
$tripData["date"]="2015-06-02 16:01";
$tripData["latitude"]="41.213181";
$tripData["longitude"]="-124.004631";
$tripData["location"]="Redwood National";
$tripData["notes"]="hello";
$tripData["trip"]=3;
$tripData["city"]="California";
so that it could be used as:
$obj = new Myclass;
$var = $obj->Add($tripData);
I have checked the service already but could not post it from android code using hashmap.
private void insertTripData(final String[] tripData) {
// TODO Auto-generated method stub
// Tag used to cancel the request
String tag_string_req = "req_login";
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("inserttrip",
"inserttrip Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
// Launch main activity
Toast.makeText(getApplicationContext(),
"user data inserted", Toast.LENGTH_LONG)
.show();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
// String errorMsg =
// "Please check your network connection";
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("insertTripError",
"Data Error: " + error.getMessage());
String errorMsg = "Please check your network connection";
Toast.makeText(getApplicationContext(), errorMsg,
Toast.LENGTH_LONG).show();
}
}) {
#Override
protected HashMap<String, String> getParams() {
// Posting parameters to login url
JSONObject jsonObject = new JSONObject();
for (int i = 0; i <= tripData.length; i++) {
tripData[i] = "questionId_" + i + "_" + "ans_" + i;
try {
jsonObject.put("params_" + i, tripData[i]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String data= jsonObject.toString();
HashMap<String, String> params = new HashMap<String, String>();
params.put("tag", "trip");
params.put("action", "add");
params.put("data", data);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
You said, getting "ArrayIndexOutOfBound" error in your logcat.
May be problem with your getParams() method.
Change the for loop this:
for (int i = 0; i <= tripData.length; i++)
To:
for (int i = 0; i < tripData.length; i++)
Check now and if you get any other problem, please show your logcat here,.