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
Related
I am new in android. I am trying to fetch data in spinner from database. But I don't know why my list is not set in spinner.
My code is
public class AddBasicDetail extends Fragment implements AdapterView.OnItemSelectedListener {
// array list for spinner adapter
private ArrayList<State> categoriesList;
ProgressDialog pDialog;
Spinner sp_state;
// API urls
// Url to create new category
private String URL_NEW_CATEGORY = "http://mandirdekhoo.com/app/md_eng/state.php";
public AddBasicDetail() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.add_basic_detail, container, false);
sp_state = (Spinner) v.findViewById(R.id.sp_state);
categoriesList = new ArrayList<State>();
// spinner item select listener
//sp_state.setOnItemSelectedListener((AdapterView.OnItemSelectedListener) getActivity());
new GetCategories().execute();
return v;
}
/**
* Adding spinner data
* */
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
//txtCategory.setText("");
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(getContext(),
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
sp_state.setAdapter(spinnerAdapter);
}
/**
* Async task to get all food categories
* */
private class GetCategories extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getContext());
pDialog.setMessage("Fetching food categories..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_NEW_CATEGORY, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
Log.e("my response: ", "> " + jsonObj);
if (jsonObj != null) {
JSONArray categories = jsonObj .getJSONArray("result");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
State cat = new State(catObj.getInt("id"),
catObj.getString("state_name"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
//populateSpinner();
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(
getContext(),
parent.getItemAtPosition(position).toString() + " Selected" ,
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
my service handler class is
public class ServiceHandler {
static InputStream is = null;
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
response = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error: " + e.toString());
}
return response;
}
}
and
public class State {
private int id;
private String name;
public State(){}
public State(int id, String name){
this.id = id;
this.name = name;
}
public void setId(int id){
this.id = id;
}
public void setName(String name){
this.name = name;
}
public int getId(){
return this.id;
}
public String getName(){
return this.name;
}
}
Please help
Hey after getting the correct response try to add this code
for e.g i am trying hardcoded values.replace this with your json.
final List<String> yourlist=new ArrayList<String>();
yourlist.add("Item 1");
yourlist.add("Item 2");
yourlist.add("Item 3");
yourlist.add("Item 4");
yourlist.add("Item 5");
final Spinner sp1= (Spinner) findViewById(R.id.spinner1);
final Spinner sp2= (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<String> adp1=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,yourlist);
adp1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp1.setAdapter(adp1);
Hope this helps.:)
Change your method like this
private void populateSpinner(List<String> categoriesList) {
List<String> lables = new ArrayList<String>();
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(getContext(),
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
sp_state.setAdapter(spinnerAdapter);
}
And after calling this method notifydatasetchanged() call this method.
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner(categoriesList);
}
Hope this will help you
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();
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
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.
I am developing an app in which a login screen is visible to user and what I have to send to server is mobilenumber,password and isfirst true to server when user logging in first time and when user logout and again login I have to send isFirst false to server ,How can I achieve this problem.
Note:- I dont have to check value from shared Preference, I have to send isFirst true or false on user login first time and second time,first time is true and second time false to server using Jsons.
public class CLoginScreen extends Fragment {
public static String s_szLoginUrl = "http://543.168.0.110:8080/ireward/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 ProgressDialog m_PDialog;
public CJsonsResponse m_oJsonsResponse;
public boolean isFirstLogin;
public JSONObject m_oResponseobject;
public Snackbar m_SnackBar;
public LinearLayout m_MainLayout;
public CLoginSessionManagement m_oLoginSession;
public boolean isFirstTimeLogin = true;
#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());
Toast.makeText(getActivity(), "User Login Status: " + m_oLoginSession.isLogin(), Toast.LENGTH_LONG).show();
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> {
#Override
protected void onPreExecute() {
super.onPreExecute();
m_PDialog = new ProgressDialog(getActivity());
m_PDialog.setMessage("Please wait while Logging...");
m_PDialog.setCancelable(false);
m_PDialog.show();
}
#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);
m_PDialog.dismiss();
try {
m_oResponseobject = new JSONObject(response);// getting response from server
new Thread() {// making child thread...
public void run() {
Looper.prepare();
try {
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")) {
m_SnackBar = Snackbar.make(m_MainLayout, "Please enter valid mobile number", Snackbar.LENGTH_SHORT);
m_SnackBar.show();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Pin Can Not Be Empty")) {
m_SnackBar = Snackbar.make(m_MainLayout, "Please enter Password", Snackbar.LENGTH_SHORT);
m_SnackBar.show();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Invalid PIN")) {
m_SnackBar = Snackbar.make(m_MainLayout, "Invalid Password", Snackbar.LENGTH_SHORT);
m_SnackBar.show();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Blocked due to Wrong Attempts")) {
m_SnackBar = Snackbar.make(m_MainLayout, "You are bloacked", Snackbar.LENGTH_SHORT);
m_SnackBar.show();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {
m_SnackBar = Snackbar.make(m_MainLayout, "Connection Lost", Snackbar.LENGTH_SHORT);
m_SnackBar.show();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Not Found")) {
m_SnackBar = Snackbar.make(m_MainLayout, "User not found ! Kindly Register", Snackbar.LENGTH_LONG);
m_SnackBar.show();
}
Looper.loop();
} catch (JSONException e) {
e.printStackTrace();
}
}
}.start();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getLoginDetails() {
s_szMobileNumber = m_InputMobile.getText().toString();
s_szPassword = m_InputPassword.getText().toString();
}
}
}