Forráskód Böngészése

Finish GET data from the server

Yiupang 9 éve
szülő
commit
b21a69206f

+ 1 - 12
app/src/main/AndroidManifest.xml

@@ -10,7 +10,7 @@
         android:label="@string/app_name"
         android:roundIcon="@mipmap/ic_launcher_round"
         android:supportsRtl="true"
-        android:theme="@style/AppTheme">
+        android:theme="@style/Theme.AppCompat.Light.NoActionBar">
         <meta-data android:name="com.facebook.sdk.ApplicationId"
             android:value="@string/facebook_app_id"/>
         <meta-data
@@ -35,17 +35,6 @@
                 <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
         </activity>
-
-        <activity
-            android:name=".AboutUsScreen"
-            android:label="@string/app_name"
-            android:theme="@style/AppTheme.NoActionBar">
-            <intent-filter>
-                <action android:name="android.intent.action.aboutus" />
-
-                <category android:name="android.intent.category.LAUNCHER" />
-            </intent-filter>
-        </activity>
     </application>
 
 </manifest>

BIN
app/src/main/back_icon-web.png


+ 12 - 9
app/src/main/java/com/example/yiupang/freefoodfinder/Event.java

@@ -10,8 +10,8 @@ public class Event
     private Date time;
     private String foodType;
     private String description;
-    private double latitude;
-    private double longitude;
+    private double lat;
+    private double lng;
 
     public Event(){
         //Empty Constructor
@@ -60,13 +60,13 @@ public class Event
         }
     }
 
-    public double getLatitude(){
-        return latitude;
+    public double getLat(){
+        return lat;
     }
 
     public boolean setLatitude(double latitude){
         if(latitude >= -90.0 && latitude <= 90.0){
-            this.latitude = latitude;
+            this.lat = latitude;
             return true;
         }
         else{
@@ -74,13 +74,13 @@ public class Event
         }
     }
 
-    public double getLongitude(){
-        return longitude;
+    public double getLng(){
+        return lng;
     }
 
     public boolean setLongitude(double longitude){
         if(longitude >= -180.0 && longitude <= 180.0){
-            this.longitude = longitude;
+            this.lng = longitude;
             return true;
         }
         else{
@@ -91,7 +91,10 @@ public class Event
     public String getDescription(){return this.description;}
     public void setDescription(String desc){description = desc;}
 
-
+    @Override
+    public String toString(){
+        return "name: " + this.name;
+    }
 
 }
 

+ 27 - 14
app/src/main/java/com/example/yiupang/freefoodfinder/EventsScreen.java

@@ -1,21 +1,28 @@
 package com.example.yiupang.freefoodfinder;
 
-import android.content.Intent;
 import android.os.Bundle;
 import android.support.annotation.Nullable;
+import android.util.Log;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 
 //CODE SMELL: unused import
 import android.widget.AdapterView;
-import android.widget.ArrayAdapter;
 
 import android.widget.ListView;
+
+import java.net.HttpURLConnection;
+import java.net.URL;
 import java.util.ArrayList;
 
 //CODE SMELL: unised import
-import java.lang.reflect.Array;
+import java.util.HashMap;
+import java.util.List;
+import java.io.DataOutputStream;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.BufferedReader;
 
 /**
  * Created by yiupang on 5/6/2017.
@@ -29,17 +36,23 @@ public class EventsScreen extends android.support.v4.app.Fragment
     @Override
     public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
     {
-        View view = inflater.inflate(R.layout.events_screen, container, false);
-        ArrayList<Event> dataArray = new ArrayList<>();
-        dataArray.add(new Event("Free Food 1", "Pizza", "Come !!"));
-        dataArray.add(new Event("Free Food 5", "GoodPizza", "Come Again!"));
-        dataArray.add(new Event("Free Food 4", "NicePizza", "Come Again"));
-        dataArray.add(new Event("Free Food 8", "SuperPizza", "Come Again!!"));
-
-        EventArrayAdapter adapter = new EventArrayAdapter(view.getContext(), R.layout.events_list_item, dataArray);
-        ListView listView = (ListView) view.findViewById(R.id.events_screen);
-        listView.setAdapter(adapter);
-        setItemListener(listView);
+        final View view = inflater.inflate(R.layout.events_screen, container, false); /*Make it final so that the inner class can't change it*/
+
+        /*Make a GET call to initialize the table*/
+        HttpCall httpCall = new HttpCall();
+        httpCall.setMethodType(HttpCall.GET);
+        httpCall.setUrl("http://free-food-finder.herokuapp.com/events");
+        new HttpRequest(){
+            @Override
+            public void onResponse(List<Event> response)
+            {
+                super.onResponse(response);
+                ListView listView = (ListView) view.findViewById(R.id.events_screen);
+                listView.setAdapter(new EventArrayAdapter(view.getContext(), R.layout.events_list_item, response));
+                setItemListener(listView);
+            }
+        }.execute(httpCall);
+
         return view;
     }
 

+ 42 - 0
app/src/main/java/com/example/yiupang/freefoodfinder/HttpCall.java

@@ -0,0 +1,42 @@
+package com.example.yiupang.freefoodfinder;
+
+import java.util.HashMap;
+
+/**
+ * Created by yiupang on 5/27/2017.
+ *
+ */
+
+public class HttpCall
+{
+    public static final int GET = 1;
+    public static final int POST = 2;
+
+    private String url;
+    private int methodType;
+    private HashMap<String, String> params;
+
+    public String getUrl() {
+        return url;
+    }
+
+    public void setUrl(String url) {
+        this.url = url;
+    }
+
+    public int getMethodType() {
+        return methodType;
+    }
+
+    public void setMethodType(int methodType) {
+        this.methodType = methodType;
+    }
+
+    public HashMap<String, String> getParams() {
+        return params;
+    }
+
+    public void setParams(HashMap<String, String> params) {
+        this.params = params;
+    }
+}

+ 154 - 0
app/src/main/java/com/example/yiupang/freefoodfinder/HttpRequest.java

@@ -0,0 +1,154 @@
+package com.example.yiupang.freefoodfinder;
+
+import android.os.AsyncTask;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.type.TypeFactory;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.UnsupportedEncodingException;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Created by yiupang on 5/27/2017.
+ *
+ */
+class HttpRequest extends AsyncTask<HttpCall, String, String>
+{
+    private static final String UTF_8 = "UTF-8";
+
+    /**
+     * Handle the input and result of the HTTP call
+     *
+     * @param params - The parameters of the asynchronous task from the caller are passed to this step
+     * */
+    @Override
+    protected String doInBackground(HttpCall... params)
+    {
+        HttpURLConnection urlConnection = null;
+        StringBuilder response = new StringBuilder();
+
+        try
+        {
+            HttpCall httpCall = params[0];
+            String dataParams = "";
+            boolean hasDataFromCaller = httpCall.getParams() != null;
+            URL url;
+            OutputStream os;
+            BufferedWriter writer;
+            int responseCode;
+
+            if(hasDataFromCaller)/*if no data is passed from the caller*/
+            {
+                dataParams = getDataString(httpCall.getParams(), httpCall.getMethodType());
+            }
+
+            url = new URL(httpCall.getMethodType() == HttpCall.GET ? httpCall.getUrl() + dataParams : httpCall.getUrl());
+            urlConnection = (HttpURLConnection) url.openConnection();
+            urlConnection.setRequestMethod(httpCall.getMethodType() == HttpCall.GET ? "GET":"POST");
+            urlConnection.setReadTimeout(10000 /* milliseconds */);
+            urlConnection.setConnectTimeout(15000 /* milliseconds */);
+
+            if(hasDataFromCaller && httpCall.getMethodType() == HttpCall.POST)
+            {
+                os = urlConnection.getOutputStream();
+                writer = new BufferedWriter(new OutputStreamWriter(os, UTF_8));
+                writer.append(dataParams);
+                writer.flush();
+                writer.close();
+                os.close();
+            }
+
+            /*Handle the response*/
+            responseCode = urlConnection.getResponseCode();
+            if(responseCode == HttpURLConnection.HTTP_OK)
+            {
+                String line;
+                BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
+                while ((line = br.readLine()) != null)
+                {
+                    response.append(line);
+                }
+            }
+        }
+        catch (Exception e)
+        {
+            e.printStackTrace();
+        }
+        finally
+        {
+            if(urlConnection != null) {
+                urlConnection.disconnect();
+            }
+        }
+
+        return response.toString();
+    }
+
+    /**
+     * Invoke on the UI thread after the background computation finishes.
+     *
+     * @param s - the returned value from doInBackground()
+     * */
+    @Override
+    protected void onPostExecute(String s)
+    {
+        super.onPostExecute(s);
+        try
+        {
+            ObjectMapper mapper = new ObjectMapper();
+            TypeFactory typeFactory = mapper.getTypeFactory();
+            List<Event> events = mapper.readValue(s, typeFactory.constructCollectionType(List.class, Event.class));/*Parse to Event Objs*/
+            onResponse(events);
+        }
+        catch (IOException e)
+        {
+            List<Event> eventsError = new LinkedList<>();
+            eventsError.add(new Event("Error", "Error", "Error"));
+            onResponse(eventsError);
+        }
+    }
+
+    /**
+     * It needs to be overwritten by the caller to handle the response
+    * */
+    public void onResponse(List<Event> response)
+    {
+
+    }
+
+    /**
+     * Create the string for parameters in the URL based on the attributes and data passed by the caller
+     * */
+    private String getDataString(HashMap<String, String> params, int methodType) throws UnsupportedEncodingException
+    {
+        StringBuilder result = new StringBuilder();
+        boolean isFirst = true;
+        for(Map.Entry<String, String> entry : params.entrySet())
+        {
+            if(isFirst)
+            {
+                isFirst = false;
+                if(methodType == HttpCall.GET)
+                    result.append("?");
+                else
+                    result.append("&");
+                result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
+                result.append("=");
+                result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
+            }
+        }
+        return result.toString();
+    }
+}

+ 1 - 1
app/src/main/java/com/example/yiupang/freefoodfinder/MainActivity.java

@@ -71,7 +71,6 @@ public class MainActivity extends ActionBarActivity
         });*/
         setContentView(R.layout.activity_main);
         bottomBar = BottomBar.attach(this, savedInstanceState);
-
         //CODE SMELL: It's complicated
         bottomBar.setItemsFromMenu(R.menu.menu_main, new OnMenuTabClickListener()
         {
@@ -117,6 +116,7 @@ public class MainActivity extends ActionBarActivity
     public boolean onCreateOptionsMenu(Menu menu) {
         // Inflate the menu; this adds items to the action bar if it is present.
         getMenuInflater().inflate(R.menu.menu_main, menu);
+        getMenuInflater().inflate(R.menu.top_menu, menu);
         return true;
     }
 

BIN
app/src/main/res/drawable-hdpi/back_icon.png


BIN
app/src/main/res/drawable-mdpi/back_icon.png


BIN
app/src/main/res/drawable-xhdpi/back_icon.png


BIN
app/src/main/res/drawable-xxhdpi/back_icon.png


+ 16 - 0
app/src/main/res/menu/top_menu.xml

@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="utf-8"?>
+<menu xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:app="http://schemas.android.com/apk/res-auto"
+    android:id="@+id/top_bar">
+    <!-- "Mark Favorite", should appear as action button if possible -->
+    <item
+        android:id="@+id/action_favorite"
+        android:icon="@drawable/back_icon"
+        android:title="action_favorite"
+        app:showAsAction="ifRoom"/>
+
+    <!-- Settings, should always be in the overflow -->
+    <item android:id="@+id/action_settings"
+        android:title="@string/action_settings"
+        app:showAsAction="never"/>
+</menu>