Fetching data in onResume doubling the data in android? - android

I have a fragment where the onCreateView method sends a request to a server and fetches some data. This is working fine but when I send another request in onResume, it doubles the data in the listview. How can I fix this problem?
Code:
#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();// here sending request in onCreate
} else {
Toast.makeText(getActivity(), "Please check internet connection !", Toast.LENGTH_LONG).show();
}
}
#Override
public void onResume() {
super.onResume();
if (NetworkUtil.isConnected(getActivity())) {
postDealListingDatatoServer();// here in on Resume send request which double data
} 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.mainLayout);
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.mainLayout), "Connection lost ! Please try again", getActivity());
} else if (error instanceof NetworkError) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "No internet connection", getActivity());
}
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}

You should clear s_oDataset before adding the new data to it.
You could do something like this:
JSONArray posts = response.optJSONArray("dealList");// get Deal list in array from response
s_oDataset.clear(); // clear the old values
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
}
To prevent your Button from being doubled, instead of this:
m_ListView.addFooterView(btnLoadMore);
You could check if your ListView has a FooterView and create your Button accordingly:
if(m_ListView.getFooterViewsCount() == 0) {
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);
m_ListView.addFooterView(btnLoadMore);
}

onResume() is always called after onCreate() so no reason to have them do the same thing. Just implement onResume to call the data updating code not the onCreate()

Please remove calling getDetails() from onCreateView which is calling postDealListingDatatoServer(). Call getDetails() method from onResume
You can remove if-else block which is in onResume() now and just call getDetails() from onResume
one more way is, clear s_oDataset before calling postDealListingDatatoServer(), this will avoid adding same data to the list

Related

How to make progress dialog in fragment tab in Android?

I have MainActivity which added two fragment tab namely "tab1 and "tab2.tab 1 sends some request to server during this process I Want to show a progress dialog but when I do this through a error message "android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application" and also have some implementation of Broadcast receiver in tab 1 fragment which also through error "unable to register receiver"
Progress dialog code:
public class DialogUtils {
public static ProgressDialog showProgressDialog(Context context, String message) {
ProgressDialog m_Dialog = new ProgressDialog(context);
m_Dialog.setMessage(message);
m_Dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
m_Dialog.setCancelable(false);
m_Dialog.show();
return m_Dialog;
}
}
Mainactivity code:
m_TabLayout = (TabLayout) findViewById(R.id.tab_layout);// finding Id of tablayout
m_ViewPager = (ViewPager) findViewById(R.id.pager);//finding Id of ViewPager
m_TabLayout.addTab(m_TabLayout.newTab().setText("Deals"));// add deal listin tab
m_TabLayout.addTab(m_TabLayout.newTab().setText("Stories"));
m_TabLayout.setTabGravity(TabLayout.GRAVITY_FILL);// setting Gravity of Tab
CDealMainListingPager m_oDealMainScreenPager = new CDealMainListingPager(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) {
}
});
and tab1 fragment tab code:
public static final String TAG = CDealAppListing.class.getSimpleName();
public static final int m_TRANSACTION_SUCCESSFUL = 0;
public static String m_szMobileNumber;//declaring String mobile number variable
public static String m_szEncryptedPassword;//declaring string password variable
public static String sz_RecordCount;// //declaring String record count variable variable
public static String sz_LastCount;//declaring String lastcount variable
private static ListView m_ListView;// declaring Listview variable..
private static CDealAppListingAdapter m_oAdapter;// declaring DealListingAdapter..
public CDealAppDatastorage item;// declaring DealAppdataStorage
public View mFooter;
public AppCompatButton m_BtnRetry;
/*This Broadcast receiver will listen network state accordingly
which enable or disable create an account button*/
private final BroadcastReceiver m_oInternetChecker = new BroadcastReceiver() {// creating broadcast to receive otp sent by server from Inbox...
#Override
public void onReceive(Context context, Intent intent) {// on receive method to read OTP sent by server
changeButtonState();// check whether edit text is empty or not
}
};
RequestQueue requestQueue;
JsonObjectRequest jsonObjectRequest;
private ArrayList<CDealAppDatastorage> s_oDataset;// declaring Arraylist variable
private int[] m_n_FormImage;//declaring integer array varaible
private View m_Main;//declaring View variable
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 ProgressDialog m_Dialog;
private boolean bBottomOfView;
private LinearLayout m_NoInternetWarning;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
m_Main = inflater.inflate(R.layout.deal_listing, container, false);//intialize mainLayout
Log.i(TAG, "OnCreateView.........");
init();
return m_Main;
}
#Override
public void onResume() {
super.onResume();
Log.i(TAG, "onResume.........");
/*Registered Broadcast receiver*/
IntentFilter m_intentFilter = new IntentFilter();// creating object of Intentfilter class user for defining permission
m_intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");// action to check Internet connection
getActivity().registerReceiver(m_oInternetChecker, m_intentFilter);// register receiver....
getDetails();
}
public void changeButtonState() {
if (NetworkUtil.isConnected(getActivity())) {
m_BtnRetry.setEnabled(true);
m_BtnRetry.setBackgroundColor(Color.rgb(0, 80, 147));// set background color on eabled
} else {
m_BtnRetry.setEnabled(false);
m_BtnRetry.setBackgroundColor(Color.rgb(192, 192, 192));// color of login button
}
}
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
m_n_DeafalutLastCount = 0;
sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// increment of last count...
s_oDataset = new ArrayList<>();// making object of Arraylist
if (NetworkUtil.isConnected(getActivity())) {
m_NoInternetWarning.setVisibility(View.GONE);
postDealListingDatatoServer();// here sending request in onCreate
} else {
mSwipeRefresh.setVisibility(View.GONE);
m_NoInternetWarning.setVisibility(View.VISIBLE);
m_BtnRetry.setEnabled(false);
m_BtnRetry.setBackgroundColor(Color.rgb(192, 192, 192));// color of login button
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy...............");
getActivity().unregisterReceiver(m_oInternetChecker);// unregistaer broadcast receiver.
}
private void init() {// initialize controls
m_NoInternetWarning = (LinearLayout) m_Main.findViewById(R.id.no_internet_warning);
m_BtnRetry = (AppCompatButton) m_Main.findViewById(R.id.btn_retry);
m_BtnRetry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
retryRequest(v);
}
});
m_ListView = (ListView) m_Main.findViewById(R.id.dealList);// findind Id of Listview
m_ListView.setFadingEdgeLength(0);
m_ListView.setOnScrollListener(this);
/*Swipe to refresh code*/
mSwipeRefresh = (SwipeRefreshLayout) m_Main.findViewById(R.id.swipe);
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())) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// increment of record count
m_n_DeafalutLastCount = 0;
sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// increment of last count...
swipeData();
}
}, 3500);
} else {
m_NoInternetWarning.setVisibility(View.VISIBLE);
mSwipeRefresh.setVisibility(View.GONE);
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};
}
public void retryRequest(View v) {
if (NetworkUtil.isConnected(getActivity())) {
m_BtnRetry.setEnabled(true);
m_BtnRetry.setBackgroundColor(Color.rgb(0, 80, 147));// set background color on eabled
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// increment of record count
m_n_DeafalutLastCount = 0;
sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// increment of last count...
postDealListingDatatoServer();
} else {
m_BtnRetry.setEnabled(false);
m_BtnRetry.setBackgroundColor(Color.rgb(192, 192, 192));// color of login button
}
}
/*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
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
System.out.println("Record Count:-" + sz_RecordCount);
System.out.println("LastCount:-" + 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().getApplicationContext(), "Loading...");
final String m_DealListingURL = "http://202.131.144.132:8080/json/metallica/getDealListInJSON";
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);
m_Dialog.dismiss();
try {
int nResultCodeFromServer = Integer.parseInt(response.getString("resultcode"));
if (nResultCodeFromServer == m_TRANSACTION_SUCCESSFUL) {
JSONArray posts = response.optJSONArray("dealList");// get Deal list in array from response
s_oDataset.clear();
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
}
if (!s_oDataset.isEmpty()) {// condition if data in arraylist is not empty
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_NoInternetWarning.setVisibility(View.GONE);
mSwipeRefresh.setVisibility(View.VISIBLE);
} else {
m_ListView.removeFooterView(mFooter);// else Load buttonvisibility set to Gone
}
}
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) {
Log.e(TAG, "Server error:-" + error);
m_Dialog.dismiss();
if (error instanceof TimeoutError) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Connection lost ! Please try again", getActivity());
} else if (error instanceof NetworkError) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "No internet connection", getActivity());
mSwipeRefresh.setVisibility(View.GONE);
m_NoInternetWarning.setVisibility(View.VISIBLE);
}
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
Step1: Change DialogUtils class:
public static ProgressDialog showProgressDialog(Activity activity, String message) {
ProgressDialog m_Dialog = new ProgressDialog(activity);
m_Dialog.setMessage(message);
m_Dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
m_Dialog.setCancelable(false);
m_Dialog.show();
return m_Dialog;
}
Step2: Change the postDealListingDatatoServer() method.
m_Dialog = DialogUtils.showProgressDialog(getActivity(), "Loading...");
Step3: About broadcast receiver. Please register at the onResume() method and unregister at the onPause() method.
public static ProgressDialog showProgressDialog(Context context, String message) {
ProgressDialog m_Dialog = new ProgressDialog(context);
m_Dialog.setMessage(message);
m_Dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
m_Dialog.setCancelable(false);
if (!((Activity) context).isFinishing()) {
m_Dialog.show();
}
return m_Dialog;
}
To dismiss dialog:
if ((m_Dialog!= null) && m_Dialog.isShowing())
m_Dialog.dismiss();
Check if fragment is visible or not.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (this.isVisible()) {
// If we are becoming invisible, then...
if (!isVisibleToUser) {
}
} else {
}
}
}

how to make show more footer with progressbar at bottom of listview?

I have a fragment which contain listview that have some data from server and I am adding progressbar footer at bottom of listview when user scroll down listview a progress bar at bottom of listview is shown to user and send server request and add some more data in listview ,problem is that when scroll to end progressbar is also visible but sending server request back to back .How can I archeive this problem.
here is my code for listview scroll
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
Log.i("a", "scrolling stopped...");
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem + visibleItemCount == totalItemCount-1 && totalItemCount != 0) {
if (!isloading) {
// It is time to add new data. We call the listener
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
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();
}
}
}
}
and here is my code for sending request when progressbar footer is shown to user in listview
public void loadmoreData() {
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
System.out.println("Server Request:-" + json);
requestQueue = Volley.newRequestQueue(getActivity());
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());
m_ListView.removeFooterView(mFooter);
requestQueue.cancelAll(TAG);
} 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.mainLayout), "Connection lost ! Please try again", getActivity());
} else if (error instanceof NetworkError) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "No internet connection", getActivity());
}
}
});
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
All you need to do is maintain a flag for network request and one for noMoreDataLeft.
boolean noMoreDataLeft;
boolean requestGoingOn;
Everytime when you make a network call just change the value of requestGoingOn to true. And whene you come to know throught your api that there is no more data on server make the noMoreDataLeft true.
Now define two constants for show loading and data row -
private final static int TYPE_LOADING = 0;
private final static int TYPE_DATA = 1;
Now -
#Override
public int getItemCount() {
return data.size() + (requestGoingOn && !isNoMoreDataLeft ? 1 : 0);
}
It will add a more row when request is going on. Now you just need to check the current position if it is more than data.size then return type as loading.
#Override
public int getItemViewType(int position) {
return position >= data.size() ? TYPE_LOADING : TYPE_DATA;
}
That's it, now itemType will be available so you can decide which view you need to show. Hope it will help :)

Issues with Volley caching mechanism

I have a website which publishes news on daily basis.
Now, I'm sending a JsonArrayRequest to retrieve and parse the title and summary of each news published on the website. The parsed items are then used to populate RecyclerView.
The problem I'm having is the way volley implements caching .
Let's take this scenario: the app is installed, launched and the RecyclerView is populated. The user reads the news and forgets about the app
Later, the user launches the app and the items are fetched and RecyclerView is populated.
Between the first and the second launch, new news are published on the website. But in the second launch, these new items are not displayed. However, if the user manually go to app settings and clear cache of the app, and relaunch, the new items are displayed.
You get my point?
While I don't want to disable Volley caching, how do I make it to always fetch new items?
EDIT
MainActivity
public class MainActivity extends AppCompatActivity {
private final String TAG = "MainActivity";
//Creating a list of newss
private List<NewsItems> mNewsItemsList;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate called");
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.news_recycler);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Initializing the newslist
mNewsItemsList = new ArrayList<>();
adapter = new NewsAdapter(mNewsItemsList, this);
recyclerView.setAdapter(adapter);
if (NetworkCheck.isAvailableAndConnected(this)) {
//Calling method to get data
getData();
} else {
//Codes for building Alert Dialog
alertDialogBuilder.setPositiveButton(R.string.alert_retry, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!NetworkCheck.isAvailableAndConnected(mContext)) {
alertDialogBuilder.show();
} else {
getData();
}
}
});
alertDialogBuilder.setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialogBuilder.show();
}
}
//This method will get data from the web api
private void getData(){
Log.d(TAG, "getData called");
//Codes for Showing progress dialog
//Creating a json request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigNews.GET_URL + getNumber(),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called");
//Dismissing the progress dialog
if (mProgressDialog != null) {
mProgressDialog.hide();
}
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
NewsItems newsItem = new NewsItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
newsItem.setNews_title(jsonObject.getString(ConfigNews.TAG_VIDEO_TITLE));
newsItem.setNews_body(jsonObject.getString(ConfigNews.TAG_VIDEO_BODY));
} catch (JSONException w) {
w.printStackTrace();
}
mNewsItemsList.add(newsItem);
}
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy called");
if (mProgressDialog != null){
mProgressDialog.dismiss();
Log.d(TAG, "mProgress dialog dismissed");
}
}
}
Option 1) Delete Cache
before you make a call you can delete the whole cache by myDiskBasedCache.clear() or specific entries by myDiskBasedCache.remove(entryUrl)
Option 2) Custom CacheParser (in the Request)
#Override
protected Response<Bitmap> parseNetworkResponse(NetworkResponse response) {
Response<Bitmap> resp = super.parseNetworkResponse(response);
if(!resp.isSuccess()) {
return resp;
}
long now = System.currentTimeMillis();
Cache.Entry entry = resp.cacheEntry;
if(entry == null) {
entry = new Cache.Entry();
entry.data = response.data;
entry.responseHeaders = response.headers;
entry.ttl = now + 60 * 60 * 1000; //keeps cache for 1 hr
}
entry.softTtl = 0; // will always refresh
return Response.success(resp.result, entry);
}
Option 3) send requests that does not cache
myRequest.setShouldCache(false);
Option 4) use custom Cache implementation
UPDATE:
Example with your code:
//Creating a json request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigNews.GET_URL + getNumber(),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called");
//Dismissing the progress dialog
if (mProgressDialog != null) {
mProgressDialog.hide();
}
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
Response<JSONArray> resp = super.parseNetworkResponse(response);
if(!resp.isSuccess()) {
return resp;
}
long now = System.currentTimeMillis();
Cache.Entry entry = resp.cacheEntry;
if(entry == null) {
entry = new Cache.Entry();
entry.data = response.data;
entry.responseHeaders = response.headers;
entry.ttl = now + 60 * 60 * 1000; //keeps cache for 1 hr
}
entry.softTtl = 0; // will always refresh
return Response.success(resp.result, entry);
}
};
UPDATE 2
Http protocol caching supports many ways to define how the client can cache responses and when to update them. Volley simplifies those rules to:
entry.ttl (time to live in ms) if greater than the current time then cache can be used otherwise fresh request needs to be made
and
entry.softTtl (soft time to live in ms :) if greater than the current time
cache is absolutely valid and no request to the server needs to be made, otherwise new request is still made (even if the ttl is good) and if there is a change new response will be delivered.
note that if ttl is valid and softTtl is not you can receive 2 onResponse calls

How to load more data in Recyclerview in android

I am using recyclerview in which I want to fetch more data from server using json.
scenario is something like that :- On first hit I want to display 5 page in list and a show more button below recyclerview is there when user click show more button on second hit display 5 more pages.how can I do that
here is my init():
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.GONE);
// 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
mLayoutManager = new LinearLayoutManager(getActivity());
m_RecyclerView.setLayoutManager(mLayoutManager);//showing odata vertically to user.
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// increment of record count
sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// increment of last count...
m_Handler = new Handler();
}
public void implementScroll() {// on scroll load more data from server.............
m_RecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
}
}
#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.GONE);
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......
}
});
} else {
m_showMore.setVisibility(View.GONE);
}
}
});
}
here is my first serevr hit:-
//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", 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();
// 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;
}
public void getResponse() throws JSONException {// getting response from serevr ..................
if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) {// server based condition
m_oAdapter = new CDealAppListingAdapter(s_oDataset);// create adapter object and add arraylist to adapter
m_oAdapter.notifyDataSetChanged();
m_RecyclerView.setAdapter(m_oAdapter);//adding adapter to recyclerview
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {//server based conditions
CToastMessage.getInstance().showToast(getActivity(), "Connection not avaliable");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Deal List Not Found")) {// serevr based conditions .....
CToastMessage.getInstance().showToast(getActivity(), "No More Deals Available");
}
}
// sending deal data to server and retreive response......
class CDealDataSent extends AsyncTask<String, Void, String> {
public CRegistrationDataStorage oRegisterStorage;
public CDealAppDatastorage item;
#Override
protected void onPreExecute() {
super.onPreExecute();
CProgressBar.getInstance().showProgressBar(getActivity(), "Please wait while Loading Deals...");
}
#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(final String result) {
new Thread(new Runnable() {
#Override
public void run() {
m_Handler.post(new Runnable() {
#Override
public void run() {
CProgressBar.getInstance().hideProgressBar();// hide progress bar after getting response from server.......
try {
m_oResponseobject = new JSONObject(result);// getting response from server
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);
}
getResponse();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}).start();
}
}
here is my second serevr hit
// 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> {
public CRegistrationDataStorage oRegisterStorage;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressBar.setVisibility(View.VISIBLE);// SHOW PROGRESS BAR
}
#Override
protected String doInBackground(String... urls) {
//My Background tasks are written here
synchronized (this) {
return DealListing(urls[0], oRegisterStorage);// POST DATA TO SERVER
}
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
new Thread(new Runnable() {
#Override
public void run() {
m_Handler.post(new Runnable() {
#Override
public void run() {
mProgressBar.setVisibility(View.INVISIBLE);// 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_n_Image(m_n_FormImage[i]);// static image for testing purpose not original....
s_oDataset.add(item);// add items to arraylist....
m_oAdapter.notifyItemInserted(s_oDataset.size());// notify adapter when deal added to recylerview
}
getResponse();// getting response from server.....and also here response based logics...
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}).start();
}
}
here is my adapter class:
public class CDealAppListingAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static CDealAppDatastorage list;
private static ArrayList<CDealAppDatastorage> s_oDataset;
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;
public CDealAppListingAdapter(ArrayList<CDealAppDatastorage> mDataList) {
s_oDataset = mDataList;
}
#Override
public int getItemViewType(int position) {
return s_oDataset.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
if (i == VIEW_TYPE_ITEM) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.deallisting_card_view, viewGroup, false);
return new DealAppViewHolder(view);
} else if (i == VIEW_TYPE_LOADING) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_loading_item, viewGroup, false);
return new LoadingViewHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof DealAppViewHolder) {
list = s_oDataset.get(position);// receiving item on position on index i
DealAppViewHolder dealAppViewHolder = (DealAppViewHolder) holder;
dealAppViewHolder.s_szAppImage.setImageResource(list.getM_n_Image());
dealAppViewHolder.s_szheadingText.setText(list.getM_szHeaderText());
dealAppViewHolder.s_szSubHeader.setText(list.getM_szsubHeaderText());
} else if (holder instanceof LoadingViewHolder) {
LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
loadingViewHolder.progressBar.setIndeterminate(true);
}
}
#Override
public int getItemCount() {
return (s_oDataset == null ? 0 : s_oDataset.size());//counting size of odata in ArrayList
}
static class LoadingViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
public LoadingViewHolder(View itemView) {
super(itemView);
progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar1);
}
}
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 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);
i.putExtra("DealCode", s_oDataset.get(getPosition()).getM_szsubHeaderText());
i.putExtra("headerText", s_oDataset.get(getPosition()).getM_szHeaderText());
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);
i.putExtra("DealCode", list.getM_szsubHeaderText());
i.putExtra("headerText", list.getM_szHeaderText());
v.getContext().startActivity(i);
}
});
}
}
}
Either store two lists in your adapter, the currently displayed list and the full list, or get only the content you need if your API allows it.
You can then set your adapter size in getItemCount to be your displayed list size + 1 (for the view more items). You will need to add a separate view type to return in getItemViewType for your view more cell (the logic to display it would be if the position is currently displayed list size). You will also need to add a new view and view holder for the load more cell.
After you've set up your new view more cell you can simply add a click listener to it, if clicked add 5 items from your full list into your currently displayed list (making sure to start at the currently displayed list - 1 index of the full list, and call notifyDataSetChanged, or notifyItemAdded x 5.
I'm sorry I currently don't have time to write an appropriate adapter for you but I hope the above explanation will suffice.

Android passing values of JSON object to another activity on list item click

i want to pass the correct json object on the list item click in the first activity to the second activity. If i click any list item, the json object from JSONArray response should be passed to intent and my next activity must get it.
Here is my code
JsonArrayRequest postReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Consumer user = new Consumer();
user.setTitle(obj.getString("name"));
user.setUserid(obj.getString("user"));
user.setThumbnailUrl(obj.getString("image"));
user.setAmountreq(obj.getString("price"));
user.setTime(obj.getString("date"));
user.setCounty(obj.getString("county"));
// adding request to consumer class
userList.add(user);
} catch (JSONException e) {
e.printStackTrace();
}
}
/*notifying list adapter about data changes
so that it renders the list view with updated data*/
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(postReq);
// listening to single list item on click
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(!obj.isNull(position)){
//start new activity
Intent myIntent = new Intent(RequestFeedActivity.this,RequestFeed.class);
myIntent.putExtra("name", obj.getJSONObject(position).toString());
startActivity(myIntent);
}
// ListView Clicked
}
});
}
On the other activity here is my sample code of the variables i want to be passed
TextView rname, rtitle,rprice, rdate, rdesc, rcounty;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.requestfeed);
rtitle = (TextView)findViewById(R.id.IDRproduct);
rprice = (TextView)findViewById(R.id.IDRquote);
rdate = (TextView)findViewById(R.id.IDRdate);
rdesc = (TextView)findViewById(R.id.IDRdesc);
rname = (TextView)findViewById(R.id.IDRname);
Intent myIntent = getIntent();
//Assign values
rname.setText(myIntent.getExtras().getString("name"));
rtitle.setText(myIntent.getExtras().getString("title"));
rprice.setText(myIntent.getExtras().getString("pricetag"));
rdate.setText(myIntent.getExtras().getString("timereq"));
rdesc.setText(myIntent.getExtras().getString("description"));
rcounty.setText(myIntent.getExtras().getString("county"));
}
I tried this answer but didnt work .Any much help is much appreciated
Try to replace this peace of code:
myIntent.getExtras().getString("name")
With this code:
myIntent.getStringExtra("name");
Just try this
Intent i =new Intent(this,ActivityA.class);
Bundle b =new Bundle();
i.putExtra("KEY","VALUE");
i.putExtras(b);
startActivity(i)
At the receiver side
Bundle b=getIntent().getExtras();
b.getInt("KEY") //useaccording to ur need
If it doesn't work check this answer

Categories

Resources