Advertisement
stevekamau

Untitled

Feb 23rd, 2017
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.63 KB | None | 0 0
  1. package com.pathways.fundilist.fragment;
  2.  
  3. import android.content.DialogInterface;
  4. import android.content.Intent;
  5. import android.os.Bundle;
  6. import android.support.annotation.Nullable;
  7. import android.support.v4.app.Fragment;
  8. import android.support.v4.widget.SwipeRefreshLayout;
  9. import android.support.v7.app.AlertDialog;
  10. import android.support.v7.widget.DefaultItemAnimator;
  11. import android.support.v7.widget.LinearLayoutManager;
  12. import android.support.v7.widget.RecyclerView;
  13. import android.util.Log;
  14. import android.view.LayoutInflater;
  15. import android.view.View;
  16. import android.view.ViewGroup;
  17. import android.widget.Toast;
  18.  
  19. import com.android.volley.Request;
  20. import com.android.volley.Response;
  21. import com.android.volley.VolleyError;
  22. import com.android.volley.toolbox.StringRequest;
  23. import com.pathways.fundilist.R;
  24. import com.pathways.fundilist.activity.ProviderLogin;
  25. import com.pathways.fundilist.adapter.ProviderJobsRecyclerAdapter;
  26. import com.pathways.fundilist.model.Bid;
  27.  
  28. import org.json.JSONArray;
  29. import org.json.JSONException;
  30. import org.json.JSONObject;
  31.  
  32. import java.text.SimpleDateFormat;
  33. import java.util.ArrayList;
  34. import java.util.HashMap;
  35. import java.util.Map;
  36.  
  37. import helper.SQLiteHandler;
  38. import helper.SessionManager;
  39. import volley.AppController;
  40. import volley.ConfigUrl;
  41.  
  42. /**
  43.  * Created by curv3r on 12/15/16.
  44.  */
  45.  
  46. public class Bids extends Fragment {
  47.  
  48.     private final String LOG_TAG = Bids.class.getSimpleName();
  49.  
  50.     // Create an {@link ArrayList} that stores Bids
  51.     final ArrayList<Bid> bids = new ArrayList<>();
  52.  
  53.     // Create {@link SessionManager} instance
  54.     private SessionManager sessionManager;
  55.  
  56.     private SQLiteHandler db;
  57.  
  58.     private Bid bid;
  59.  
  60.     RecyclerView recyclerView;
  61.     SwipeRefreshLayout swipeRefreshLayout;
  62.     ProviderJobsRecyclerAdapter jobsRecyclerAdapter;
  63.  
  64.     HashMap<String, String> provider;
  65.     String providerId;
  66.     String providerSkill;
  67.     String providerLocation;
  68.     String providerFirstName;
  69.     String providerLastName;
  70.     String providerEmail;
  71.  
  72.     /**
  73.      * Set a hint to the system about whether this fragment's UI is currently visible
  74.      * to the user. This hint defaults to true and is persistent across fragment instance
  75.      * state save and restore.
  76.      * <p>
  77.      * <p>An app may set this to false to indicate that the fragment's UI is
  78.      * scrolled out of visibility or is otherwise not directly visible to the user.
  79.      * This may be used by the system to prioritize operations such as fragment lifecycle updates
  80.      * or loader ordering behavior.</p>
  81.      * <p>
  82.      * <p><strong>Note:</strong> This method may be called outside of the fragment lifecycle.
  83.      * and thus has no ordering guarantees with regard to fragment lifecycle method calls.</p>
  84.      *
  85.      * @param isVisibleToUser true if this fragment's UI is currently visible to the user (default),
  86.      *                        false if it is not.
  87.      */
  88.     @Override
  89.     public void setUserVisibleHint(boolean isVisibleToUser) {
  90.         super.setUserVisibleHint(isVisibleToUser);
  91.         if (isVisibleToUser && isResumed()) {
  92.             if (bids.isEmpty()) {
  93.                 getBids(providerLocation, providerSkill);
  94.             }
  95.         }
  96.     }
  97.  
  98.     /**
  99.      * Called to have the fragment instantiate its user interface view.
  100.      * This is optional, and non-graphical fragments can return null (which
  101.      * is the default implementation).  This will be called between
  102.      * {@link #onCreate(Bundle)} and {@link #onActivityCreated(Bundle)}.
  103.      * <p>
  104.      * <p>If you return a View from here, you will later be called in
  105.      * {@link #onDestroyView} when the view is being released.
  106.      *
  107.      * @param inflater           The LayoutInflater object that can be used to inflate
  108.      *                           any views in the fragment,
  109.      * @param container          If non-null, this is the parent view that the fragment's
  110.      *                           UI should be attached to.  The fragment should not add the view itself,
  111.      *                           but this can be used to generate the LayoutParams of the view.
  112.      * @param savedInstanceState If non-null, this fragment is being re-constructed
  113.      *                           from a previous saved state as given here.
  114.      * @return Return the View for the fragment's UI, or null.
  115.      */
  116.     @Nullable
  117.     @Override
  118.     public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
  119.        View  rootView = inflater.inflate(R.layout.frag_bids, container, false);
  120.  
  121.         swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh_layout_provider_bids);
  122.         recyclerView = (RecyclerView) rootView.findViewById(R.id.provider_bid_recycler_view);
  123.         RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
  124.         recyclerView.setLayoutManager(layoutManager);
  125.         recyclerView.setItemAnimator(new DefaultItemAnimator());
  126.  
  127.         sessionManager = new SessionManager(getActivity().getApplicationContext());
  128.         db = new SQLiteHandler(getActivity().getApplicationContext());
  129.  
  130.         if (sessionManager.isLoggedIn()) {
  131.             provider = db.getProvider();
  132.             if (!provider.isEmpty()) {
  133.                 providerId = provider.get("service_provider_id");
  134.                 providerFirstName = provider.get("provider_first_name");
  135.                 providerLastName = provider.get("provider_last_name");
  136.                 providerEmail = provider.get("provider_email");
  137.                 providerSkill = provider.get("provider_skill");
  138.                 providerLocation = provider.get("provider_location");
  139.  
  140.                 Log.d(LOG_TAG, providerId + " " + providerSkill + " " + providerLocation);
  141.             } else {
  142.                 startActivity(new Intent(getActivity(), ProviderLogin.class));
  143.  
  144.             }
  145.         } else {
  146.             Toast.makeText(getActivity(), "You need to login first", Toast.LENGTH_SHORT).show();
  147.             startActivity(new Intent(getActivity(), ProviderLogin.class));
  148.         }
  149.  
  150.         swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
  151.             @Override
  152.             public void onRefresh() {
  153.                 updateJobs();
  154.             }
  155.         });
  156. //of course bids arraylist is empty when this fragment is created for the first time,
  157. //so dont bother with bids.isEmpty() check
  158.  
  159.  getBids(providerLocation, providerSkill);
  160.      //   if (bids.isEmpty()) {
  161.        //     getBids(providerLocation, providerSkill);
  162.        // }
  163.  
  164.         return rootView;
  165.     }
  166.  
  167. void setUpAdapter(){
  168.   jobsRecyclerAdapter = new ProviderJobsRecyclerAdapter(bids);
  169.   recyclerView.setAdapter(jobsRecyclerAdapter);
  170. }
  171.     private void updateJobs() {
  172.         getBids(providerLocation, providerSkill);
  173.         jobsRecyclerAdapter.notifyDataSetChanged();
  174.         swipeRefreshLayout.setRefreshing(false);
  175.     }
  176.  
  177.     /**
  178.      * Returns a formatted date and time string for when the earthquake happened.
  179.      */
  180.     private String getDateString(String jsonString) {
  181.         SimpleDateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy 'at' HH:mm:ss z");
  182.         return formatter.format(jsonString);
  183.     }
  184.  
  185.  
  186.     public void getBids(final String locationID, final String skillID) {
  187.  
  188.         StringRequest stringRequest = new StringRequest(Request.Method.POST,
  189.                 ConfigUrl.PROVIDER_AVAILABLE_JOBS, new Response.Listener<String>() {
  190.  
  191.  
  192.             @Override
  193.             public void onResponse(String response) {
  194.                 Log.d(LOG_TAG, "Response: " + response);
  195.  
  196.  
  197.                 try {
  198.                     JSONObject jsonObject = new JSONObject(response);
  199.                     boolean error = jsonObject.getBoolean("error");
  200.                     if (!error) {
  201.                         // getting JSONArray node
  202.                         JSONArray result = jsonObject.getJSONArray("data");
  203.                         Log.d(LOG_TAG, "" + result.length());
  204.  
  205.                         if (result.length() > 0) {
  206.                             // loop through the results
  207.                             for (int i = 0; i < result.length(); i++) {
  208.                                 JSONObject obj = result.getJSONObject(i);
  209.                                 String bidId = obj.getString("job_id");
  210.                                 String clientID = obj.getString("client_id");
  211.                                 String clientName = obj.getString("client_name");
  212.                                 String location = obj.getString("job_location_label");
  213.                                 String description = obj.getString("job_detail");
  214.                                 String jobDate = obj.getString("job_date");
  215.                                 String timeline = obj.getString("job_time");
  216.                                 String dateCreated = obj.getString("date_created");
  217.  
  218.  
  219.                                 bids.add(new Bid(clientName, description, location, jobDate, bidId, clientID, timeline, dateCreated));
  220.                                 Log.d(LOG_TAG, bidId + " " + clientID + " Bids size " + bids.size());
  221.                                 Log.v(LOG_TAG, bids.get(0).getClientName());
  222. //dont set your adapter within this loop, it's not okay. It means you are resetting the adapter with every iteration
  223.                               //  jobsRecyclerAdapter = new ProviderJobsRecyclerAdapter(bids);
  224.                               //  recyclerView.setAdapter(jobsRecyclerAdapter);
  225.                             }
  226. //instead do it outside the loop
  227. setUpAdapter();
  228.                         } else {
  229.                             getActivity().runOnUiThread(new Runnable() {
  230.                                 @Override
  231.                                 public void run() {
  232.                                     Toast.makeText(getActivity(), "No jobs at this time, please try again later", Toast.LENGTH_LONG).show();
  233.                                 }
  234.                             });
  235.  
  236.                         }
  237.                     } else {
  238.                         AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
  239.                         builder.setTitle("No Jobs");
  240.                         builder.setMessage("No jobs available at the moment");
  241.                         builder.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
  242.                             @Override
  243.                             public void onClick(DialogInterface dialogInterface, int i) {
  244.  
  245.                             }
  246.                         });
  247.                         AlertDialog alertDialog = builder.create();
  248.                         alertDialog.show();
  249.                     }
  250.                 } catch (JSONException e) {
  251.                     e.printStackTrace();
  252.                 }
  253.  
  254.  
  255.             }
  256.         }, new Response.ErrorListener() {
  257.  
  258.             @Override
  259.             public void onErrorResponse(VolleyError error) {
  260.                 Log.e(LOG_TAG, "Error: " + error.getMessage());
  261.                 Toast.makeText(getActivity(),
  262.                         "Problem connecting. Please check your network connection and try again.", Toast.LENGTH_LONG).show();
  263.  
  264.             }
  265.         }) {
  266.  
  267.             @Override
  268.             protected Map<String, String> getParams() {
  269.                 // Posting parameters to login url
  270.                 Map<String, String> params = new HashMap<>();
  271.                 params.put("location_id", locationID);
  272.                 params.put("skill_id", skillID);
  273.                 return params;
  274.             }
  275.  
  276.         };
  277.  
  278.         // Adding request to request queue
  279.         AppController.getInstance().addToRequestQueue(stringRequest);
  280.     }
  281.  
  282. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement