How to make Swipe to refresh using json in android? - 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();
}
}
}

Related

How do I show result from server response to app in Android?

I am developing and I want to show user login or not. Following is my code in this it shows correct response in Logcat but not show the message on app side(i.e login success or login failed message). How do I do this?
How do I parse json data in this?
Please suggest me!!
// Following is response from server shows inside Logcat
{
"login": [
{
"sessionid": 12973,
"responsetypes": "success"
}
]
}
// Following is my code
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
private EditText usernameEditText;
private EditText passwordEditText;
private Button sendGetReqButton;
TextView tv_forgot;
Button register;
Toolbar toolbar;
private boolean loggedIn = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
tv_forgot= (TextView)findViewById(R.id.tv_forgot);
tv_forgot.setOnClickListener(this);
usernameEditText = (EditText) findViewById(R.id.ed_email);
passwordEditText = (EditText) findViewById(R.id.ed_passowrd);
register = (Button) findViewById(R.id.btn_reg);
sendGetReqButton = (Button) findViewById(R.id.btn_login);
sendGetReqButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.btn_login){
// Get the values given in EditText fields
String userID = usernameEditText.getText().toString();
String password = passwordEditText.getText().toString();
System.out.println("Givennames is :" + userID + " Given password is :" + password);
// Pass those values to connectWithHttpGet() method
connectWithHttpGet(userID, password);
}
else {
Toast.makeText(LoginActivity.this, "Please Fill the fields", Toast.LENGTH_LONG).show();
}
}
private void connectWithHttpGet(String userID, String password) {
// Connect with a server is a time consuming process.
//Therefore we use AsyncTask to handle it
// From the three generic types;
//First type relate with the argument send in execute()
//Second type relate with onProgressUpdate method which I haven't use in this code
//Third type relate with the return type of the doInBackground method, which also the input type of the onPostExecute method
class HttpGetAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// As you can see, doInBackground has taken an Array of Strings as the argument
//We need to specifically get the givenUsername and givenPassword
String paramUsername = params[0];
String paramPassword = params[1];
System.out.println("userID" + paramUsername + " password is :" + paramPassword);
// Create an intermediate to connect with the Internet
HttpClient httpClient = new DefaultHttpClient();
// Sending a GET request to the web page that we want
// Because of we are sending a GET request, we have to pass the values through the URL
HttpGet httpGet = new HttpGet("http://www.example.com/ypAndroid/api/doLogin?userID=" + paramUsername + "&password=" + paramPassword);
try {
// execute(); executes a request using the default context.
// Then we assign the execution result to HttpResponse
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("httpResponse// getEntity() ; obtains the message entity of this response");
// getContent() ; creates a new InputStream object of the entity.
// Now we need a readable source to read the byte stream that comes as the httpResponse
InputStream inputStream = httpResponse.getEntity().getContent();
// We have a byte stream. Next step is to convert it to a Character stream
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
// Then we have to wraps the existing reader (InputStreamReader) and buffer the input
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
// InputStreamReader contains a buffer of bytes read from the source stream and converts these into characters as needed.
//The buffer size is 8K
//Therefore we need a mechanism to append the separately coming chunks in to one String element
// We have to use a class that can handle modifiable sequence of characters for use in creating String
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
// There may be so many buffered chunks. We have to go through each and every chunk of characters
//and assign a each chunk to bufferedStrChunk String variable
//and append that value one by one to the stringBuilder
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
// Now we have the whole response as a String value.
//We return that value then the onPostExecute() can handle the content
System.out.println("Returninge of doInBackground :" + stringBuilder.toString());
// If the Username and Password match, it will return "working" as response
// If the Username or Password wrong, it will return "invalid" as response
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("Exceptionrates caz of httpResponse :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Secondption generates caz of httpResponse :" + ioe);
ioe.printStackTrace();
}
return null;
}
// Argument comes for this method according to the return type of the doInBackground() and
//it is the third generic type of the AsyncTask
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Post result :" + result);
if(result.equals("success"))
Toast.makeText(getApplicationContext(), "HTTP GET is working...", Toast.LENGTH_LONG).show();
else {
Toast.makeText(getApplicationContext(), "Invalid...", Toast.LENGTH_LONG).show();
}
}
}
// Initialize the AsyncTask class
HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
// Parameter we pass in the execute() method is relate to the first generic type of the AsyncTask
// We are passing the connectWithHttpGet() method arguments to that
httpGetAsyncTask.execute(userID, password);
}
}
You can do like this.
In the onPostExecute() method
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Post result :" + result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray login = jsonObject.getJSONArray("login");
JSONObject jsonObject1 = login.getJSONObject(0);
// edited second, you response was responsetype, but I parsed was responsetypes,so you can have a look.
String responsetypes = jsonObject1.optString("responsetypes");
// edited
String sessionid = jsonObject1.getString("sessionid");
if (TextUtils.equals(responsetypes, "success")) {
Toast.makeText(getApplicationContext(), "HTTP GET is working...", Toast.LENGTH_LONG).show();
} else if (TextUtils.equals(responsetypes, "failure")) {
// edited
String message = jsonObject1.getString("message");
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
for example method get error response use volley.
private void getLogin() {
JSONObject param = new JSONObject();
try {
param.put("username", username.getText().toString());
param.put("password", password.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST, url, param, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("login");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.d("sessionid>> ", jsonObject.getString("sessionid"));
}
dissmissPDialog();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error >> ", error.toString());
streror = error.toString();
dissmissPDialog();
}
}
);
normal.add(jsonObjectRequest);
}
Update your onPostExecute() method like this.
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject1 = new JSONObject(result);
JSONArray jsonArray = jsonObject1.getJSONArray("login");
JSONObject jsonObjectLogin = jsonArray.getJSONObject(0);
String response = jsonObjectLogin.getString("responsetypes");
Toast.makeText(getApplicationContext(), +response, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
Let me know this is working or not.

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 execute URL on Fragment change in android?

I have a fragment in my app named"A" and "B" in A fragment I execute URL that fetch data from server when I change to "B" It still loading data.what I want when I change to "B" A stop executing URL when I again switch to A then A start executing.How can I do that.
#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 deatisl of user from sharedpreference......
init();//initialize metho
return m_Main;
}
private void getDetails() {
CLoginSessionManagement m_oSessionManagement = new CLoginSessionManagement(getActivity());
HashMap<String, String> user = m_oSessionManagement.getLoginDetails();
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...
s_oDataset = new ArrayList<>();
m_ProgressView = (CircularProgressView) m_Main.findViewById(R.id.progress_view);
m_ProgressView.startAnimation();
m_ProgressView.setVisibility(View.GONE);
}
#Override
public void onStart() {
super.onStart();
new CDealDataSent().execute(m_DealListingURL);
}
private String DealListing(String url) {
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();
jsonObject.put("agentCode", m_szMobileNumber);
jsonObject.put("pin", m_szEncryptedPassword);
jsonObject.put("recordcount", sz_RecordCount);
jsonObject.put("lastcountvalue", sz_LastCount);
//jsonObject.put("emailId", "nirajk1190#gmail.com");
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
System.out.println("Jsons:-" + 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();
System.out.println("InputStream....:" + inputStream.toString());
System.out.println("Response....:" + httpResponse.toString());
StatusLine statusLine = httpResponse.getStatusLine();
System.out.println("statusLine......:" + statusLine.toString());
////Log.d("resp_body", resp_body.toString());
int statusCode = statusLine.getStatusCode();
// 10. convert inputstream to string
if (statusCode == 200) {
// 10. convert inputstream to string
s_szresult = CJsonsResponse.convertInputStreamToString(inputStream);
//String resp_body =
} else
s_szresult = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
System.out.println("resul.....:" + s_szresult);
System.out.println("pin:" + m_szEncryptedPassword);
System.out.println("recordCount:" + sz_RecordCount);
System.out.println("LastCount:" + 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("Transaction Successful")) {// server based condition
} else 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());
}
}
// sending deal data to server and retreive response......
class CDealDataSent extends AsyncTask<String, Void, String> {
public CDealAppDatastorage item;
#Override
protected void onPreExecute() {
super.onPreExecute();
m_ProgressView.setVisibility(View.VISIBLE);
}
#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) {
m_ProgressView.setVisibility(View.GONE);
try {
m_oResponseobject = new JSONObject(result);// getting response from server
JSONArray posts = m_oResponseobject.optJSONArray("dealList");
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.getJSONObject(i);
item = new CDealAppDatastorage();
item.setM_szHeaderText(post.getString("dealname"));
item.setM_szsubHeaderText(post.getString("dealcode"));
item.setM_szDealValue(post.getString("dealvalue"));
item.setM_n_Image(m_n_FormImage[i]);
s_oDataset.add(item);
}
// LoadMore button
Button btnLoadMore = new Button(getActivity());
btnLoadMore.setText("LOAD MORE DEALS");
btnLoadMore.setBackgroundResource(R.drawable.button_boarder);
btnLoadMore.setTextAppearance(getActivity(), android.R.style.TextAppearance_DeviceDefault_Small);
btnLoadMore.setTextColor(Color.WHITE);
btnLoadMore.setGravity(Gravity.CENTER);
if (!s_oDataset.isEmpty()) {
// Adding Load More button to lisview at bottom
m_ListView.addFooterView(btnLoadMore);
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();
} else {
btnLoadMore.setVisibility(View.GONE);
}
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
m_n_DefaultRecordCount = 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
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(getActivity()).execute(m_DealListingURL);// POST DATA TO SERVER TO LOAD MORE DATA......
}
});
getResponse();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public class CDealMainListing extends Fragment {
// --Commented out by Inspection (11-04-2016 10:45):public LinearLayout m_MainLayout;
private ViewPager m_ViewPager;
private View m_Main;
#SuppressWarnings("ConstantConditions")
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
m_Main = inflater.inflate(R.layout.deals_main_screen, container, false);
//noinspection ConstantConditions
((AppCompatActivity) getActivity()).getSupportActionBar().show();
init();
return m_Main;
}
private void init() {
TabLayout m_TabLayout = (TabLayout) m_Main.findViewById(R.id.tab_layout);
m_TabLayout.addTab(m_TabLayout.newTab().setText("Deals"));
m_TabLayout.addTab(m_TabLayout.newTab().setText("Stories"));
m_TabLayout.setTabGravity(TabLayout.GRAVITY_FILL);// setting Gravity of Tab
m_ViewPager = (ViewPager) m_Main.findViewById(R.id.pager);//finding Id of ViewPager
CDealMainListingPager m_oDealMainScreenPager = new CDealMainListingPager
(getActivity().getSupportFragmentManager(), m_TabLayout.getTabCount());
m_ViewPager.setAdapter(m_oDealMainScreenPager);// adiing adapter to ViewPager
m_ViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(m_TabLayout));// performing action of page changing
m_TabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
m_ViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
private HttpClient httpclient;
private shutDownClient(){
httpclient.getConnectionManager().shutdown()
}
use this method when you are switching b/w fragments

How to refresh content of listview coming from server in android?

I have a listview in my app contain content coming in response from server and have a load more Button below listview. In onCreate I execute content URL it works what I want is to in onResume method when I again execute content URL List view get double with same content and Loadmore button.How can I solve this problem.
here is my code :-
class CDealDataSent extends AsyncTask<String, Void, String> {
public CDealAppDatastorage item;
#Override
protected void onPreExecute() {
super.onPreExecute();
m_ProgressView.setVisibility(View.VISIBLE);
}
#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) {
m_ProgressView.setVisibility(View.GONE);
try {
m_oResponseobject = new JSONObject(result);// getting response from server
JSONArray posts = m_oResponseobject.optJSONArray("dealList");
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.getJSONObject(i);
item = new CDealAppDatastorage();
item.setM_szHeaderText(post.getString("dealname"));
item.setM_szsubHeaderText(post.getString("dealcode"));
item.setM_szDealValue(post.getString("dealvalue"));
item.setM_n_Image(m_n_FormImage[i]);
s_oDataset.add(item);
}
// LoadMore button
Button btnLoadMore = new Button(getActivity());
btnLoadMore.setText("LOAD MORE DEALS");
btnLoadMore.setBackgroundResource(R.drawable.button_boarder);
btnLoadMore.setTextAppearance(getActivity(), android.R.style.TextAppearance_DeviceDefault_Small);
btnLoadMore.setTextColor(Color.WHITE);
btnLoadMore.setGravity(Gravity.CENTER);
if (!s_oDataset.isEmpty()) {
// Adding Load More button to lisview at bottom
m_ListView.addFooterView(btnLoadMore);
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();
} else {
btnLoadMore.setVisibility(View.GONE);
}
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
m_n_DefaultRecordCount = 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
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();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Before doing:
s_oDataset.add(item);
check if it already has this value:
if(!s_oDataset.contains(item)){
s_oDataset.add(item);
}
you have 2 solution:
1. check if the item exist in your data, don't add it.
if(!s_oDataset.contains(item)){
s_oDataset.add(item);
}
remove all data before add new data.
s_oDataset.removeAll();

How to show more in Recylerview in android [duplicate]

This question already has answers here:
How to implement endless list with RecyclerView?
(36 answers)
Closed 6 years ago.
I am developing an app in which there is recyclerview in which I have to show more at bottom on which user scroll load more data. Please help me out from this problem.
Here is my fragment class where I show Recycler View:
public class CDealAppListing extends Fragment {
public static String m_DealListingURL = "http://192.143.0.110:8080/ireward/rest/json/metallica/getDealListInJSON";
public static String s_szresult = " ";
public static RecyclerView m_RecyclerView;
public static CDealAppListingAdapter m_oAdapter;
public static CDealAppDatastorage item;
public ArrayList<CDealAppDatastorage> s_oDataset;
public int[] m_n_FormImage;
public View m_Main;
public CRegistrationSessionManagement m_oSessionManagement;
public String m_szMobileNumber, m_szEncryptedPassword;
public LinearLayoutManager mLayoutManager;
public RelativeLayout loadProgress;
public AppCompatButton m_showMore;
public ProgressBar mProgressBar;
int r = 4;
int u = 0;
String record = String.valueOf(r);
String last = String.valueOf(u);
//declare boolean
private CJsonsResponse m_oJsonsResponse;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
m_Main = inflater.inflate(R.layout.deal_app_listing, container, false);//intialize mainLayout
new CDealDataSent().execute(m_DealListingURL);
init();//initialize method
implementScroll();
return m_Main;
}
public void init() {
mProgressBar = (ProgressBar) m_Main.findViewById(R.id.progressBar1);
mProgressBar.setVisibility(View.GONE);
m_showMore = (AppCompatButton) m_Main.findViewById(R.id.show_more);
m_showMore.setBackgroundColor(Color.TRANSPARENT);
m_showMore.setVisibility(View.INVISIBLE);
// Getting the string array from strings.xml
m_n_FormImage = new int[]{
R.drawable.amazon,
R.drawable.whatsapp,
R.drawable.zorpia,
R.drawable.path,
R.drawable.app_me,
R.drawable.evernote,
R.drawable.app_me};
m_RecyclerView = (RecyclerView) m_Main.findViewById(R.id.my_recycler_view);//finding id of recyclerview
m_RecyclerView.setItemAnimator(new DefaultItemAnimator());//setting default animation to recyclerview
m_RecyclerView.setHasFixedSize(true);//fixing size of recyclerview
//Layout manager for Recycler view
mLayoutManager = new LinearLayoutManager(getActivity());
m_RecyclerView.setLayoutManager(mLayoutManager);//showing odata vertically to user.
m_oSessionManagement = new CRegistrationSessionManagement(getActivity());
HashMap<String, String> user = m_oSessionManagement.getRegistrationDetails();
m_szEncryptedPassword = user.get(m_oSessionManagement.s_szKEY_PASSWORD);
m_szMobileNumber = user.get(m_oSessionManagement.s_szKEY_MOBILENUMBER);
}
public void implementScroll() {
m_RecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (dy > 0) {
m_showMore.setVisibility(View.VISIBLE);
m_showMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//change boolean value
m_showMore.setVisibility(View.INVISIBLE);
r = r + 4;
u = u + 4;
record = String.valueOf(r);
last = String.valueOf(u);
new DealNext().execute(m_DealListingURL);
}
});
} else {
m_showMore.setVisibility(View.INVISIBLE);
}
}
});
}
//sending deal data to retreive response from server
public String DealListing(String url, CRegistrationDataStorage login) {
InputStream inputStream = null;
m_oJsonsResponse = new CJsonsResponse();
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();
jsonObject.put("agentCode", "989899999");
jsonObject.put("pin", "05E0901648FD6439207FA74FC3E07734");
jsonObject.put("recordcount", record);
jsonObject.put("lastcountvalue", last);
//jsonObject.put("emailId", "nirajk1190#gmail.com");
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// 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();
System.out.println("InputStream....:" + inputStream.toString());
System.out.println("Response....:" + httpResponse.toString());
StatusLine statusLine = httpResponse.getStatusLine();
System.out.println("statusLine......:" + statusLine.toString());
////Log.d("resp_body", resp_body.toString());
int statusCode = statusLine.getStatusCode();
// 10. convert inputstream to string
if (statusCode == 200) {
// 10. convert inputstream to string
if (inputStream != null)
s_szresult = m_oJsonsResponse.convertInputStreamToString(inputStream);
//String resp_body =
EntityUtils.toString(httpResponse.getEntity());
} else
s_szresult = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
System.out.println("resul.....:" + s_szresult);
// 11. return s_szResult
return s_szresult;
}
// sending deal data to server and retreive response......
class CDealDataSent extends AsyncTask<String, Void, String> {
public JSONObject m_oResponseobject;
public ProgressDialog m_PDialog;
public CRegistrationDataStorage oRegisterStorage;
public CDealAppDatastorage item;
// #Override
protected void onPreExecute() {
super.onPreExecute();
m_PDialog = new ProgressDialog(getActivity());
m_PDialog.setMessage("Please wait while Loading Deals...");
m_PDialog.setCancelable(false);
m_PDialog.show();
}
#Override
protected String doInBackground(String... urls) {
return DealListing(urls[0], oRegisterStorage);// sending data to server...
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
m_PDialog.dismiss();
try {
m_oResponseobject = new JSONObject(result);// getting response from server
final JSONArray posts = m_oResponseobject.optJSONArray("dealList");
s_oDataset = new ArrayList<CDealAppDatastorage>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.getJSONObject(i);
item = new CDealAppDatastorage();
item.setM_szHeaderText(post.getString("dealname"));
item.setM_szsubHeaderText(post.getString("dealcode"));
item.setM_n_Image(m_n_FormImage[i]);
s_oDataset.add(item);
}
if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) {
m_oAdapter = new CDealAppListingAdapter(s_oDataset);//creating object of adapter and addd setting odata to adapter for use.
m_RecyclerView.setAdapter(m_oAdapter);//adding adapter to recyclerview
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {
Toast.makeText(getActivity(), "Connection not avaliable", Toast.LENGTH_SHORT).show();
}
System.out.println("agentCode...." + m_szMobileNumber);
System.out.println("password...." + m_szEncryptedPassword);
System.out.println("record////" + record);
System.out.println("last:........" + last);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class DealNext extends AsyncTask<String, Void, String> {
public JSONObject m_oResponseobject;
public CRegistrationDataStorage oRegisterStorage;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... urls) {
//My Background tasks are written here
synchronized (this) {
return DealListing(urls[0], oRegisterStorage);
}
}
#Override
protected void onPostExecute(String result) {
mProgressBar.setVisibility(View.INVISIBLE);
super.onPostExecute(result);
try {
m_oResponseobject = new JSONObject(result);// getting response from server
final JSONArray posts = m_oResponseobject.optJSONArray("dealList");
s_oDataset = new ArrayList<CDealAppDatastorage>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.getJSONObject(i);
item = new CDealAppDatastorage();
item.setM_szHeaderText(post.getString("dealname"));
item.setM_szsubHeaderText(post.getString("dealcode"));
item.setM_n_Image(m_n_FormImage[i]);
s_oDataset.add(item);
}
if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) {
m_oAdapter = new CDealAppListingAdapter(s_oDataset);//creating object of adapter and addd setting odata to adapter for use.
m_RecyclerView.setAdapter(m_oAdapter);//adding adapter to recyclerview
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {
Toast.makeText(getActivity(), "Connection not avaliable", Toast.LENGTH_SHORT).show();
}
System.out.println("agentCode...." + m_szMobileNumber);
System.out.println("password...." + m_szEncryptedPassword);
System.out.println("record////" + record);
System.out.println("last:........" + last);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
And here is Adapter class:-
public class CDealAppListingAdapter extends RecyclerView.Adapter<CDealAppListingAdapter.DealAppViewHolder> {
private static ArrayList<CDealAppDatastorage> s_oDataset;
public CDealAppListingAdapter(ArrayList<CDealAppDatastorage> mDataList) {
s_oDataset = mDataList;
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
public DealAppViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.deallisting_card_view, viewGroup, false);
DealAppViewHolder viewHolder = new DealAppViewHolder(itemLayoutView);//creating object of ViewHolder containg component
return viewHolder;
}
#Override
public void onBindViewHolder(DealAppViewHolder viewHolder, int i) {
CDealAppDatastorage list = s_oDataset.get(i);// receiving item on position on index i
DealAppViewHolder.s_szAppImage.setImageResource(list.getM_n_Image());//adding m_n_Image to viewHolder
DealAppViewHolder.s_szheadingText.setText(list.getM_szHeaderText());
DealAppViewHolder.s_szSubHeader.setText(list.getM_szsubHeaderText());
viewHolder.m_oDealAppDatastorage = list;
}
#Override
public int getItemCount() {
return (null != s_oDataset ? s_oDataset.size() : 0);//counting size of odata in ArrayList
}
public static class DealAppViewHolder extends RecyclerView.ViewHolder {
public static ImageView s_szAppImage;
public static TextView s_szheadingText, s_szSubHeader;
public static Button s_szGetDealBtn;
public CDealAppDatastorage m_oDealAppDatastorage;
public DealAppViewHolder(View itemLayoutView) {
super(itemLayoutView);
s_szheadingText = (TextView) itemLayoutView.findViewById(R.id.headingText);// finding id of headerText...
s_szSubHeader = (TextView) itemLayoutView.findViewById(R.id.subHeaderText);// finding id of subHeader.....
s_szAppImage = (ImageView) itemLayoutView.findViewById(R.id.appImage);//finding Id of Imgae in CardView
s_szGetDealBtn = (Button) itemLayoutView.findViewById(R.id.getDealBtn);// finding id of getdeal Btn
Random rnd = new Random();//creating object of Random class
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));//genrating random color
s_szGetDealBtn.setBackgroundColor(color);//backgraound color of getDeal Btn
s_szGetDealBtn.setOnClickListener(new View.OnClickListener() {// onclick getDeal Btn
#Override
public void onClick(View v) {//send to deal detail page onclick getDeal Btn
Intent i = new Intent(v.getContext(), CDealAppListingDetails.class);
Bundle b = new Bundle();
b.putSerializable("DATA", s_oDataset.get(getPosition()));// sending data to deal detail page
i.putExtras(b);
v.getContext().startActivity(i);
}
});
itemLayoutView.setOnClickListener(new View.OnClickListener() {// onclick cardview
#Override
public void onClick(View v) {// onclick cardview send to deal app listing details page .....
Intent i = new Intent(v.getContext(), CDealAppListingDetails.class);
Bundle b = new Bundle();
b.putSerializable("DATA", s_oDataset.get(getPosition()));
i.putExtras(b);
v.getContext().startActivity(i);
}
});
}
}
}
How I've implemented similar thing is, I added a footer in my RecyclerView named 'Load More' and then by clicking on the load more footer i called a service again to fetch more data and then notify the recycler view to repopulate the data.
So let me put a discussion of my server side implementation. When the RecyclerView is loaded for the first time I called a service to fetch the data from server with page number 0. When the response is received I populated the RecyclerView and added a load more footer at the end of RecyclerView. When the load more footer is clicked I called the service again with page number 1 and when I got the response back I appended the data with the previously saved list and then called notifyDataSetChanged on the Adapter. That's how a simple pagination is done in my case.
I had to put a boolean which was returned in every single response from server indicating if I have any more data to show. So that when the boolean hasNext was found false I had to change the text of the load more footer to 'no more results to show', so that user can understand there's no more data.
Here's now you can add a footer in your RecyclerView

Categories

Resources