How to update UI from separate AsynkTask class - android

I have a class CDealListing from where I execute AsynkTask class which is separate class,what I want is to update UI of class CDealListing on AsynkTask class onPost method .kindly help me .....
here is code of my class CDealListing
public class CDealAppListing extends Fragment {
public static String m_DealListingURL = "http://192.166.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 AppCompatButton m_showMore;
public ProgressBar mProgressBar;
public int m_n_DefaultRecordCount = 5;// intiallly record count is 5.
public int m_n_DeafalutLastCount = 0;//initally lastcount is 0.
public String sz_RecordCount, sz_LastCount;
//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.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.
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);
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// increment of record count
sz_LastCount = String.valueOf(m_n_DeafalutLastCount);
}
public void implementScroll() {
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;
m_n_DeafalutLastCount = m_n_DeafalutLastCount + 5;
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);
sz_LastCount = String.valueOf(m_n_DeafalutLastCount);
new DealNext().execute(m_DealListingURL);
}
});
} else {
m_showMore.setVisibility(View.GONE);
}
}
});
}
//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;
}
and here is my AsynkTask class
/ 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);
}
getResponse();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getResponse() throws JSONException {
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();
}else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Deal List Not Found")){
Toast.makeText(getActivity(),"No More Deals",Toast.LENGTH_SHORT).show();
}
System.out.println("agentCode...." + m_szMobileNumber);
System.out.println("password...." + m_szEncryptedPassword);
System.out.println("record////" + sz_RecordCount);
System.out.println("last:........" + sz_LastCount);
}
}
In asynkTask class get Response method update UI of class CDealListing

There are 3 ways
Call some method of your Fragment in onPostExecute()
Use BroadcastReceiver in onPostExecute()
use EventBus library for passing event to your Fragment.

One way would be to declare a listener interface and pass an instance of that interface (or perhaps a Runnable) into the AsyncTask's constructor.
In your fragment code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
new CDealDataSent(new Runnable() {
#Override
public void run() {
// perform update UI code here
}
}).execute(m_DealListingURL);
...
}
In your AsyncTask code:
class CDealDataSent extends AsyncTask<String, Void, String> {
private final Runnable mOnPostExecuteRunnable;
CDealDataSent(Runnable onPostExecuteRunnable) {
mOnPostExecuteRunnable = onPostExecuteRunnable;
}
...
#Override
protected void onPostExecute(String result) {
...
if (mPostExecuteRunnable != null) {
mPostExecuteRunnable.run();
}
...
}
}
You could also use an anonymous subclass of AsyncTask from your fragment and override onPostExecute():
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
new CDealDataSent() {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result); // be sure to call super first to do normal processing
... // update your UI here
}
}.execute(m_DealListingURL);
...
}
Note that both of these solutions are prone to Activity/Fragment leakage if you are not careful, as the parent class of the Runnable/anonymous subclass is retained as an implicit reference. Be sure to cancel any outstanding AsyncTasks if the user backs out of your activity in onDestroy().
You might be able to mitigate any potential leakage issues via a static nested class, or maybe pass a Handler instance to the AsyncTask for it to send a message on when onPostExecute() has done its job. See What's the correct way to implement AsyncTask? static or non static nested class? for a discussion on this.

Related

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 dismiss progress bar once otp read from Inbox in android?

I have a Otp verification Screen in which I have a progress bar with timer ,what I want is to dismiss this progressbar once Read Otp from inbox if read successfully from Inbox then dismiss progressbar and execute Jsons Url if not then show progressbar with timer until not read sms from Inbox.for this I am using Broadcast Receiver .Kindly help me .
here is my code of MainActivity :-
public class COtpAutoVerificationScreen extends Fragment {
private static String s_szResult = "";
private final String m_szOTPVERIFICATIONURL = "http://202.131.144.132:8080/resting/rest/json/metallica/validateOTPInJSON";
public ProgressBar pb;
private View m_Main;
private int m_n_ProgressStatus = 0;
private CRegistrationSessionManagement m_oSessionManagement;
private String m_szMobileNumber;
private String m_szEncryptedPassword;
private CircularProgressView m_ProgressView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
m_Main = inflater.inflate(R.layout.otp_auto_verified, container, false);
getUserDetails();// getuser deatails....
init();// initialize controls...
return m_Main;
}
private void getUserDetails() {
m_oSessionManagement = new CRegistrationSessionManagement(getActivity());
}
private void init() {
m_ProgressView = (CircularProgressView) m_Main.findViewById(R.id.progress_view);
m_ProgressView.startAnimation();
m_ProgressView.setVisibility(View.GONE);
pb = (ProgressBar) m_Main.findViewById(R.id.pb);
final TextView tv = (TextView) m_Main.findViewById(R.id.tv);
#SuppressWarnings("UnusedAssignment") final TextView validationText = (TextView) m_Main.findViewById(R.id.validatingmessage);
tv.setText("00:00");
//Initialize a new CountDownTimer instance
long m_MillisInFuture = 30000;
long m_CountDownInterval = 1000;
new CountDownTimer(m_MillisInFuture, m_CountDownInterval) {
public void onTick(long millisUntilFinished) {
#SuppressWarnings("UnusedAssignment") long millis = millisUntilFinished;
String hms = String.format("%02d:%02d", TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));
System.out.println(hms);
tv.setText(hms);
//Another one second passed
//Each second ProgressBar progress counter added one
m_n_ProgressStatus += 1;
pb.setProgress(m_n_ProgressStatus);
}
public void onFinish() {
// retreive user data from shared preferencce........
HashMap<String, String> user = m_oSessionManagement.getRegistrationDetails();
m_szEncryptedPassword = user.get(CRegistrationSessionManagement.s_szKEY_PASSWORD).trim();
m_szMobileNumber = user.get(CRegistrationSessionManagement.s_szKEY_MOBILENUMBER).trim();
// exc=ecuting request for otp verfiifcation to server
new COtpVerify().execute();
}
}.start();
// retreive progress bar count........
int progressBarMaximumValue = (int) (m_MillisInFuture / m_CountDownInterval);
//Set ProgressBar maximum value
//ProgressBar range (0 to maximum value)
pb.setMax(progressBarMaximumValue);
//Display the CountDownTimer initial value
tv.setText(progressBarMaximumValue + "Seconds...");
}
// sending OTP to server to verify Otp
private class COtpVerify extends AsyncTask<String, Void, String> {
public JSONObject m_oResponseobject;
public String m_szResponseAgentCode;
#Override
protected void onPreExecute() {
super.onPreExecute();
m_ProgressView.setVisibility(View.VISIBLE);
}
#SuppressWarnings("deprecation")
#Override
protected String doInBackground(String... args) {
InputStream inputStream;
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(m_szOTPVERIFICATIONURL);
String json;
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.put("agentCode", m_szMobileNumber);
jsonObject.put("pin", m_szEncryptedPassword);
jsonObject.put("otpCode", COTPVerificationDataStorage.getInstance().getM_szOtp());
// 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.print("InputStream...." + inputStream.toString());
System.out.print("Response...." + httpResponse.toString());
StatusLine statusLine = httpResponse.getStatusLine();
System.out.print("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);
// 11. return s_szResult
return s_szResult;
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(final String result) {
m_ProgressView.setVisibility(View.GONE);
try {
m_oResponseobject = new JSONObject(result);// getting response from server
getResponse();// getting response from server ...............
} catch (Exception e) {
e.printStackTrace();
}
}
public void getResponse() throws JSONException {
// if server response is successfull then......
if (m_oResponseobject.getString("resultDesc").equalsIgnoreCase("Transaction Successful")) {
// if server response is success then setting response odata in shared prefernce...
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CLoginScreen()).commit();
CSnackBar.getInstance().showSnackBarSuccess(m_Main.findViewById(R.id.mainLayout), "OTP verified successfully", getActivity());
}
// if response from server is m_szOtp mismatch.....
else if (m_oResponseobject.getString("resultDesc").equalsIgnoreCase("OTP MisMatch")) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "OTP not found", getActivity());
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new COtpManualVerificationScreen()).commit();
}
}, 3000);
}
// if response from server is m_szOtp empty then......
else if (m_oResponseobject.getString("resultDesc").equalsIgnoreCase("otpCode Can Not Be Empty")) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "OTP not found", getActivity());
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new COtpManualVerificationScreen()).commit();
}
}, 3000);
}
}
}
}
and here is my BroadcastReceiver class:-
public class CSmsBroadcastReceiver extends BroadcastReceiver {
private static final String s_szTAG = CSmsBroadcastReceiver.class.getSimpleName();
private static String m_szOtpCode;
#Override
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
Object[] pdusObj = (Object[]) bundle.get("pdus");
assert pdusObj != null;
for (Object aPdusObj : pdusObj) {
#SuppressWarnings("deprecation") SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) aPdusObj);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String message = currentMessage.getDisplayMessageBody();
Log.e(s_szTAG, "Received SMS: " + message + ", Sender: " + phoneNumber);
// checking sms sender address....
if (phoneNumber.toLowerCase().contains("+919971599707".toLowerCase())) {
// verification code from sms
m_szOtpCode = getVerificationCode(message);
assert m_szOtpCode != null;
String input = m_szOtpCode.trim();
Log.e(s_szTAG, "OTP received: " + m_szOtpCode);
COTPVerificationDataStorage.getInstance().setM_szOtp(input);// getting otp from SMS and set to otpverificationstorage class
} else {
return;
}
}
}
} catch (Exception e) {
Log.e(s_szTAG, "Exception: " + e.getMessage());
}
}
/**
* Getting the OTP from sms message body
* ':' is the separator of OTP from the message
*
* #param message
* #return
*/
#SuppressWarnings("JavaDoc")
private String getVerificationCode(String message) {
String code;
int index = message.indexOf(":");
if (index != -1) {
int start = index + 2;
int length = 6;
code = message.substring(start, start + length);
return code;
}
COTPVerificationDataStorage.getInstance().setM_szOtp(m_szOtpCode);
return null;
}
}
Basically you want to send data from broadcast receiver to activity whenever desired message comes.you can make use of interface to communicate
In you BroadcastReceiver create interface like this
public interface OnSmsReceivedListener {
public void onSmsReceived(String message);
}
add one method to initialize interface reference
OnSmsReceivedListener smsListener;
public void setOnSmsReceivedListener(Context context) {
this.smsListener = (OnSmsReceivedListener) context;
}
use this reference to call function inside onReceive() method
smsListener.onSmsReceived("Message Received!!!");
You are done with posting data ,now give implementation of interface in your Activity and dismiss your dialog.
public class SampleActivity extends Activity implements OnSmsReceivedListener
#Override
public void onSmsReceived(String message) {
//Dismiss your dialog here
}
Other then this approach you can make use of some good third party library like EventBus and Otto which will make your work simple and easy.

How to use Handler in AsynkTask in android

I am fetching data from server using AsynkTask which works fine but I want to use handler in AsynkTask to reduce load from main Thread.How can I use Handler in AsynkTask. Kindly help me to solve this problem.
Here is my code.
public class CLoginScreen extends Fragment {
public static String s_szLoginUrl = "http://192.168.0.999:8080/rest/json/metallica/getLoginInJSON";
public static String s_szresult = " ";
public static String s_szMobileNumber, s_szPassword;
public static String s_szResponseMobile, s_szResponsePassword;
public View m_Main;
public EditText m_InputMobile, m_InputPassword;
public AppCompatButton m_LoginBtn, m_ChangePass, m_RegisterBtn;
public CJsonsResponse m_oJsonsResponse;
public boolean isFirstLogin;
public JSONObject m_oResponseobject;
public LinearLayout m_MainLayout;
public CLoginSessionManagement m_oLoginSession;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
m_Main = inflater.inflate(R.layout.login_screen, container, false);
((AppCompatActivity) getActivity()).getSupportActionBar().hide();
m_oLoginSession = new CLoginSessionManagement(getActivity());
init();
return m_Main;
}
public void init() {
m_MainLayout = (LinearLayout) m_Main.findViewById(R.id.mainLayout);
m_InputMobile = (EditText) m_Main.findViewById(R.id.input_mobile);
m_InputPassword = (EditText) m_Main.findViewById(R.id.input_password);
m_LoginBtn = (AppCompatButton) m_Main.findViewById(R.id.btn_Login);
m_ChangePass = (AppCompatButton) m_Main.findViewById(R.id.btn_ChangePass);
m_ChangePass.setBackgroundColor(Color.TRANSPARENT);
m_ChangePass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CChangePasswordScreen()).commit();
}
});
m_RegisterBtn = (AppCompatButton) m_Main.findViewById(R.id.btn_Register);
m_RegisterBtn.setBackgroundColor(Color.TRANSPARENT);
m_RegisterBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CRegistrationScreen()).commit();
}
});
m_LoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new LoginAttempt().execute();
}
});
}
private class LoginAttempt extends AsyncTask<String, Void, String> {
public Dialog m_Dialog;
public ProgressBar m_ProgressBar;
#Override
protected void onPreExecute() {
super.onPreExecute();
m_Dialog = new Dialog(getActivity());
m_Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
m_Dialog.setContentView(R.layout.progress_bar);
showProgress("Please wait while Logging...");// showing progress ..........
}
#Override
protected String doInBackground(String... params) {
getLoginDetails();// getting login details from editText...........
InputStream inputStream = null;
m_oJsonsResponse = new CJsonsResponse();
isFirstLogin = true;
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(s_szLoginUrl);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.put("agentCode", s_szMobileNumber);
jsonObject.put("pin", s_szPassword);
jsonObject.put("firstloginflag", m_oLoginSession.isLogin());
// 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("Accept", "application/json"); ///not required
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.print("InputStream...." + inputStream.toString());
System.out.print("Response...." + httpResponse.toString());
StatusLine statusLine = httpResponse.getStatusLine();
System.out.print("statusLine......" + statusLine.toString());
////Log.d("resp_body", resp_body.toString());
int statusCode = statusLine.getStatusCode();
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("s_szResult....." + s_szresult);
System.out.println("password......" + s_szPassword);
// 11. return s_szResult
return s_szresult;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
hideProgress();// hide progressbar after getting response from server......
try {
m_oResponseobject = new JSONObject(response);// getting response from server
new Thread() {// making child thread...
public void run() {
Looper.prepare();
try {
getResponse();// getting response from server
Looper.loop();
} catch (JSONException e) {
e.printStackTrace();
}
}
}.start();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getResponse() throws JSONException {
if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) {
m_oLoginSession.setLoginData(s_szResponseMobile, s_szResponsePassword);
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CDealMainListing()).commit();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Agentcode Can Not Be Empty")) {
showToast("Please Enter Valid Mobile Number");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Pin Can Not Be Empty")) {
showToast("Please Enter Password");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Invalid PIN")) {
showToast("Invalid Password");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Blocked due to Wrong Attempts")) {
showToast("You are blocked as You finished you all attempt");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {
showToast("Connection Lost ! Please Try Again");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Not Found")) {
showToast("User not found ! Kindly Regiter before Login");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("OTP not verify")) {
showToast("Otp not Verify ! Kindly Generate Otp on Sign Up");
}
}
public void showToast(String message) {// method foe showing taost message
Toast toast = Toast.makeText(getActivity(), "" + message, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
public void getLoginDetails() {
s_szMobileNumber = m_InputMobile.getText().toString();
s_szPassword = m_InputPassword.getText().toString();
}
public void showProgress(String message) {
m_ProgressBar = (ProgressBar) m_Dialog.findViewById(R.id.progress_bar);
TextView progressText = (TextView) m_Dialog.findViewById(R.id.progress_text);
progressText.setText("" + message);
progressText.setVisibility(View.VISIBLE);
m_ProgressBar.setVisibility(View.VISIBLE);
m_ProgressBar.setIndeterminate(true);
m_Dialog.setCancelable(false);
m_Dialog.setCanceledOnTouchOutside(false);
m_Dialog.show();
}
public void hideProgress() {
m_Dialog.dismiss();
}
}
}
As per android docs here
An asynchronous task is defined by a computation that runs on a
background thread and whose result is published on the UI thread.
And loading data from URL with Handler is not a good thing. Instead use Executor or ThreadPoolExecutor to do heavy background tasks.
You Can Use
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
getResponse();
}
});
you can do like this:
class MyAsyncTask extends AsyncTask<Object,Object,Object>{
Private Context c;
private Handler handler;
private final static int YOUR_WORK_ID = 0x11;
public MyAsyncTask(Context c,Handler handler){
this.c = c;
this.handler = handler;
}
protected Object doInBackground(Object... params){
//do your work
...
Message m = handler.obtainMessage();
m.what = YOUR_WORK_ID;
...
handler.sendMessage().sendToTarget();
}
}
And in your fragment ,you can init a handler as params to MyAsyncTask,and deal with you work in handleMessage();

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

How to fetch data from server below recyclerview in android

I am trying to make show more data below recyclerview like endless scrolling ,the problem is that ,First I want to fetch data from url in Act onCreate and then again when scroll down send request and fetch data from server but data not comes below 5 data which I had fetched earlier instead of below data remove previous data and comes over that ,kindly help me.
public class MainActivity extends AppCompatActivity {
public static String m_DealListingURL = "http://192.163.0.110:8080/ireward/rest/json/metallica/getDealListInJSON";
public CJsonsResponse m_oJsonsResponse;
public String s_szresult = "";
private Toolbar mToolbar;
private RecyclerView mRecyclerView;
private List<User> mUsers;
private UserAdapter mUserAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setTitle("LoadMoreRecycleView");
mUsers = new ArrayList<User>();
new CDealDataSent().execute(m_DealListingURL);
mRecyclerView = (RecyclerView) findViewById(R.id.recycleView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mUserAdapter = new UserAdapter();
mRecyclerView.setAdapter(mUserAdapter);
mUserAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
Log.e("haint", "Load More");
mUsers.add(null);
mUserAdapter.notifyItemInserted(mUsers.size() - 1);
//Load more data for reyclerview
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Log.e("haint", "Load More 2");
//Remove loading item
mUsers.remove(mUsers.size() - 1);
mUserAdapter.notifyItemRemoved(mUsers.size());
new CDealDataSent().execute(m_DealListingURL);
}
}, 5000);
}
});
}
//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", "9555517491");
jsonObject.put("pin", "05E0901648FD6439207FA74FC3E07734");
jsonObject.put("recordcount", "5");
jsonObject.put("lastcountvalue", "0");
//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;
}
static class UserViewHolder extends RecyclerView.ViewHolder {
public TextView tvName;
public TextView tvEmailId;
public UserViewHolder(View itemView) {
super(itemView);
tvName = (TextView) itemView.findViewById(R.id.tvName);
tvEmailId = (TextView) itemView.findViewById(R.id.tvEmailId);
}
}
static class LoadingViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
public LoadingViewHolder(View itemView) {
super(itemView);
progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar1);
}
}
// 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 User item;
// #Override
protected void onPreExecute() {
super.onPreExecute();
m_PDialog = new ProgressDialog(MainActivity.this);
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");
mUsers = new ArrayList<User>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.getJSONObject(i);
item = new User();
item.setName(post.getString("dealname"));
item.setEmail(post.getString("dealcode"));
mUsers.add(item);
}
getResponse();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getResponse() throws JSONException {
if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) {
mUserAdapter = new UserAdapter();//creating object of adapter and addd setting odata to adapter for use.
mRecyclerView.setAdapter(mUserAdapter);//adding adapter to recyclerview
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {
Toast.makeText(MainActivity.this, "Connection not avaliable", Toast.LENGTH_SHORT).show();
}
}
}
class UserAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;
private OnLoadMoreListener mOnLoadMoreListener;
private boolean isLoading;
private int visibleThreshold = 5;
private int lastVisibleItem, totalItemCount;
public UserAdapter() {
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
if (mOnLoadMoreListener != null) {
mOnLoadMoreListener.onLoadMore();
}
isLoading = true;
}
}
});
}
public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
this.mOnLoadMoreListener = mOnLoadMoreListener;
}
#Override
public int getItemViewType(int position) {
return mUsers.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_ITEM) {
View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout_user_item, parent, false);
return new UserViewHolder(view);
} else if (viewType == VIEW_TYPE_LOADING) {
View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout_loading_item, parent, false);
return new LoadingViewHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof UserViewHolder) {
User user = mUsers.get(position);
UserViewHolder userViewHolder = (UserViewHolder) holder;
userViewHolder.tvName.setText(user.getName());
userViewHolder.tvEmailId.setText(user.getEmail());
} else if (holder instanceof LoadingViewHolder) {
LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
loadingViewHolder.progressBar.setIndeterminate(true);
}
}
#Override
public int getItemCount() {
return mUsers == null ? 0 : mUsers.size();
}
public void setLoaded() {
isLoading = false;
}
}
}
At first remove these two lines from public void run()
mUsers.remove(mUsers.size() - 1);
mUserAdapter.notifyItemRemoved(mUsers.size());
and modify your onPostExecute() something to this
protected void onPostExecute(String result) {
m_PDialog.dismiss();
try {
m_oResponseobject = new JSONObject(result);// getting response from server
if(m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Deal List Not Found"))
return;
final JSONArray posts = m_oResponseobject.optJSONArray("dealList");
if(isFirstTime) {
mUsers = new ArrayList<User>();
isFirstTime = false;
} else {
mUsers.remove(mUsers.size() - 1);
mUserAdapter.notifyItemRemoved(mUsers.size());
}
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.getJSONObject(i);
item = new User();
item.setName(post.getString("dealname"));
item.setEmail(post.getString("dealcode"));
mUsers.add(item);
mUserAdapter.notifyItemInserted(mUsers.size());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Define isFirstTime variable and inside onCreate() initialize isFirstTime = true; before new CDealDataSent().execute(m_DealListingURL);

Categories

Resources