TRiBByX
4/28/2017 - 12:15 PM

Cantina Application

Cantina Application

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.tribbyx.cantinaapplication"
        minSdkVersion 25
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile 'com.android.support:support-v4:24.2.1'
    compile 'com.google.firebase:firebase-crash:10.0.0'
    compile 'com.google.android.gms:play-services-ads:10.0.0'
    compile 'com.google.firebase:firebase-analytics:9.0.0'
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:support-v13:25.1.1'
}
apply plugin: 'com.google.gms.google-services'
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.google.gms:google-services:3.0.0'
        classpath 'com.android.tools.build:gradle:2.2.3'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_settings"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.tribbyx.cantinaapplication.SettingsActivity"
    android:orientation="vertical">

    <TextView
        android:id="@+id/DarkMode"
        android:text="DarkMode"
        android:textSize="25dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:id="@+id/DarkModeToggle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="DarkMode"/>

</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_rate_dish"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.tribbyx.cantinaapplication.RateDish"
    android:orientation="vertical">


    <EditText
        android:id="@+id/DishID"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Dish ID"/>
    <EditText
        android:id="@+id/UserID"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="User ID"/>
    <EditText
        android:id="@+id/Rateing"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Rating"/>
    <Button
        android:id="@+id/Rate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Rate!"
        android:onClick="AddRating"/>

</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_menu"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.tribbyx.cantinaapplication.Menu">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/MenuItemList"
        />
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.tribbyx.cantinaapplication.MainActivity"
    android:orientation="vertical">

    <Button
        android:text="Menu"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:id="@+id/Menu"
        android:elevation="0dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentStart="true"
        android:onClick="GotoMenu" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="GotoRateDish"
        android:id="@+id/GotoRateDish"
        android:text="Rate a Dish" />

    <Button
        android:text="Settings"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:id="@+id/Settings"
        android:elevation="0dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentStart="true"
        android:onClick="GotoSettings"/>

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_ad_unit_id">
    </com.google.android.gms.ads.AdView>

</LinearLayout>
package com.example.tribbyx.cantinaapplication;

import android.content.SharedPreferences;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import org.w3c.dom.Text;

public class SettingsActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        SharedPreferences darkMode = getSharedPreferences("DarkMode", MODE_PRIVATE);
        boolean dm = darkMode.getBoolean("DarkModeToggle", true);
        if (dm) {
            LinearLayout ll = (LinearLayout) findViewById(R.id.activity_settings);
            ll.setBackgroundColor(Color.BLACK);

            TextView tv = (TextView) findViewById(R.id.DarkMode);
            tv.setTextColor(Color.WHITE);
        }
    }

    public void DarkMode(View view){
        SharedPreferences darkMode = getSharedPreferences("DarkMode", MODE_PRIVATE);
        SharedPreferences.Editor editor = darkMode.edit();

        boolean dm = darkMode.getBoolean("DarkModeToggle", false);
        if (!dm){
            editor.putBoolean("DarkModeToggle", true);
            editor.commit();
            LinearLayout ll = (LinearLayout) findViewById(R.id.activity_settings);
            ll.setBackgroundColor(Color.BLACK);
            TextView tv = (TextView) findViewById(R.id.DarkMode);
            tv.setTextColor(Color.WHITE);
        } else if (dm){
            editor.putBoolean("DarkModeToggle", false);
            editor.commit();
            LinearLayout ll = (LinearLayout) findViewById(R.id.activity_settings);
            ll.setBackgroundColor(Color.WHITE);
            TextView tv = (TextView) findViewById(R.id.DarkMode);
            tv.setTextColor(Color.BLACK);
        } else {
            Toast.makeText(SettingsActivity.this, "A problem accured with setting the shared prefrences", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onBackPressed(){
        super.onBackPressed();
        finish();
    }
}
package com.example.tribbyx.cantinaapplication;

import android.os.AsyncTask;
import android.util.Log;

import java.io.IOException;

/**
 * Created by anders on 2/23/2016.
 */
public class ReadHttpTask extends AsyncTask<String, Void, CharSequence> {
    @Override
    protected CharSequence doInBackground(String... urls) {
        String urlString = urls[0];
        try {
            CharSequence result = HttpHelper.GetHttpResponse(urlString);
            return result;
        } catch (IOException ex) {
            cancel(true);
            String errorMessage = ex.getMessage() + "\n" + urlString;
            Log.e("DISH", errorMessage);
            return errorMessage;
        }
    }
}
package com.example.tribbyx.cantinaapplication;

import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import static android.content.Context.MODE_PRIVATE;

public class RateDish extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rate_dish);

        SharedPreferences darkMode = getSharedPreferences("DarkMode", MODE_PRIVATE);
        boolean dm = darkMode.getBoolean("DarkModeToggle", true);
        if (dm) {
            LinearLayout ll = (LinearLayout) findViewById(R.id.activity_rate_dish);
            ll.setBackgroundColor(Color.BLACK);

            EditText cID = (EditText) findViewById(R.id.UserID);
            EditText dID = (EditText) findViewById(R.id.DishID);
            EditText rating = (EditText) findViewById(R.id.Rateing);

            cID.setBackgroundColor(Color.GRAY);
            dID.setBackgroundColor(Color.GRAY);
            rating.setBackgroundColor(Color.GRAY);
        }
    }

    public void AddRating(View view){
        String customerIDString = ((EditText) findViewById(R.id.UserID)).getText().toString();
        String dishIDString = ((EditText) findViewById(R.id.DishID)).getText().toString();
        String ratingString = ((EditText) findViewById(R.id.Rateing)).getText().toString();
        int rating = Integer.parseInt(ratingString);
        int dishID = Integer.parseInt(dishIDString);
        int customerID = Integer.parseInt(customerIDString);

        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("CustomerId", customerID);
            jsonObject.put("DishId", dishID);
            jsonObject.put("Rate", rating);

            String jsonDoc = jsonObject.toString();
            Toast.makeText(RateDish.this, jsonDoc, Toast.LENGTH_SHORT).show();
            RateDishPost task = new RateDishPost();
            task.execute("http://anbo-canteen.azurewebsites.net/Service1.svc/ratings", jsonDoc);
        } catch (JSONException e){
            Toast.makeText(RateDish.this, "Json Exception: "+e, Toast.LENGTH_SHORT).show();
        }
    }

    public class RateDishPost extends AsyncTask<String, Void, CharSequence>{
        @Override
        protected CharSequence doInBackground(String... params) {
            String urlString = params[0];
            String jsonDocument = params[1];
            try {
                URL url = new URL(urlString);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Type", "application/json");
                connection.setRequestProperty("Accept", "application/json");
                OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
                osw.write(jsonDocument);
                osw.flush();
                osw.close();
                int responseCode = connection.getResponseCode();
                if (responseCode / 100 != 2) {
                    String responseMessage = connection.getResponseMessage();
                    throw new IOException("HTTP response code: " + responseCode + " " + responseMessage);
                }
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()));
                String line = reader.readLine();
                return line;
            } catch (MalformedURLException ex) {
                cancel(true);
                String message = ex.getMessage() + " " + urlString;
                Log.e("DISH", message);
                return message;
            } catch (IOException ex) {
                cancel(true);
                Log.e("DISH", ex.getMessage());
                return ex.getMessage();
            }
        }

        @Override
        protected void onPostExecute(CharSequence charSequence) {
            super.onPostExecute(charSequence);
            Toast.makeText(RateDish.this, charSequence, Toast.LENGTH_SHORT).show();
        }

        @Override
        protected void onCancelled(CharSequence charSequence) {
            super.onCancelled(charSequence);
            Toast.makeText(RateDish.this, charSequence, Toast.LENGTH_SHORT).show();
        }
    }
}

package com.example.tribbyx.cantinaapplication;

import android.graphics.Picture;
import android.view.Menu;

import java.util.List;

/**
 * Created by TRiBByX on 07/04/2017.
 */

public class MenuItem {
    public int Alcohol;
    public int Carbohydrates;
    public String Description;
    public int Energy;
    public double Fat;
    public int ID;
    public String PictureUrl;
    public int Price;
    public double Protein;
    public String Title;
    public double Weight;

    public MenuItem(int alcohol, int carbohydrates, String description, int energy, double fat, int id, String pictureUrl,
                    int price, double protein, String title, double weight){

        Alcohol = alcohol;
        Carbohydrates = carbohydrates;
        Description = description;
        Energy = energy;
        Fat = fat;
        ID = id;
        PictureUrl = pictureUrl;
        Price = price;
        Protein = protein;
        Title = title;
        Weight = weight;
    }

    public String toString(){
        return "Title: " + Title + " \nPrice: " + Price;
    }

}
package com.example.tribbyx.cantinaapplication;


import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.example.tribbyx.cantinaapplication.R.id.MenuItemList;

public class Menu extends AppCompatActivity {

    public final List<MenuItem> items = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);

        SharedPreferences darkMode = getSharedPreferences("DarkMode", MODE_PRIVATE);
        boolean dm = darkMode.getBoolean("DarkModeToggle", true);

        if (dm) {
            RelativeLayout ll = (RelativeLayout) findViewById(R.id.activity_menu);
            ll.setBackgroundColor(Color.BLACK);
            ListView lv = (ListView) findViewById(R.id.MenuItemList);
            lv.setBackgroundColor(Color.GRAY);
        }
    }

    private static final int SWIPE_THRESHOLD = 1000;
    private float _downX;
    @Override
    public boolean onTouchEvent(MotionEvent evt) {
        Toast.makeText(Menu.this, "Swiped!", Toast.LENGTH_SHORT).show();
        switch(evt.getAction()) {
            case MotionEvent.ACTION_DOWN:
                _downX = evt.getX();
            case MotionEvent.ACTION_UP:
                float deltaX = evt.getX() - _downX;

                if(Math.abs(deltaX) > SWIPE_THRESHOLD && deltaX < 0)
                    onLeftSwipe();
        }

        return true;
    }
    public void onLeftSwipe(){
        finish();
    }

    @Override
    protected void onStart(){
        super.onStart();

        ReadTask task = new ReadTask();

        task.execute("http://anbo-canteen.azurewebsites.net/Service1.svc/dishes");

    }
    public class ReadTask extends ReadHttpTask{
        @Override
        protected void onPostExecute(CharSequence charSequence){
            super.onPostExecute(charSequence);
            try {
                JSONArray array = new JSONArray(charSequence.toString());

                for (int i = 0; i < array.length(); i++) {
                    JSONObject obj = array.getJSONObject(i);
                    int alcohol = obj.getInt("Alcohol");
                    int carbs = obj.getInt("Carbohydrates");
                    String description = obj.getString("Description");
                    int energy = obj.getInt("Energy");
                    double fat = obj.getDouble("Fat");
                    int id = obj.getInt("Id");
                    String picUrl = obj.getString("PictureUrl");
                    int price = obj.getInt("Price");
                    double protein = obj.getDouble("Protein");
                    String title = obj.getString("Title");
                    double weight = obj.getDouble("Weight");

                    MenuItem item = new MenuItem(alcohol, carbs, description, energy, fat, id, picUrl, price, protein, title, weight);
                    items.add(item);
                }
                ListView listView = (ListView) findViewById(MenuItemList);
                ArrayAdapter<MenuItem> arrayAdapter = new ArrayAdapter<MenuItem>(getBaseContext(), android.R.layout.simple_list_item_1, items);
                listView.setAdapter(arrayAdapter);
            }
            catch (JSONException ex){
                Toast.makeText(Menu.this, ex.toString(), Toast.LENGTH_SHORT).show();
            }
            if (items.isEmpty() || items == null) Toast.makeText(Menu.this, "No Content in link provided", Toast.LENGTH_SHORT).show();

        }
    }
}

package com.example.tribbyx.cantinaapplication;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.nfc.Tag;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.firebase.crash.FirebaseCrash;

import java.io.IOError;

public class MainActivity extends AppCompatActivity {
    private AdView mAdView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SharedPreferences pref = getApplicationContext().getSharedPreferences("DarkMode", MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();

        editor.putBoolean("DarkModeToggle", false);
        editor.commit();


        MobileAds.initialize(getApplicationContext(), "ca-app-pub-3940256099942544~3347511713");
        AdView mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

        //Firebase
        FirebaseCrash.logcat(Log.ERROR, "Main Activity", "Crash caused");
        FirebaseCrash.report(new Exception("Fucked up"));
    }

    @Override
    protected void onRestart() {
        super.onRestart();

        SharedPreferences darkMode = getSharedPreferences("DarkMode", MODE_PRIVATE);
        boolean dm = darkMode.getBoolean("DarkModeToggle", true);
        if (dm) {
            LinearLayout ll = (LinearLayout) findViewById(R.id.activity_main);
            ll.setBackgroundColor(Color.BLACK);
        }
    }

    public void GotoRateDish(View view){
        Intent intent = new Intent(this, RateDish.class);
        startActivity(intent);
    }

    public void GotoMenu(View view){
        Intent intent = new Intent(this, Menu.class);
        startActivity(intent);
    }

    public void GotoSettings(View view){
        Intent intent = new Intent(this, SettingsActivity.class);
        startActivity(intent);
    }

}
package com.example.tribbyx.cantinaapplication;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/***
 * Created by anders on 2/18/2016.
 * Methods to make HTTP related operations
 */
public class HttpHelper {

    /***
     * Read an HTTP response
     *
     * @param urlString the URL to read from
     * @return the contents of the HTTP response body
     * @throws IOException if urlString is malformed, no connection to server, or another IO related problem
     */
    public static CharSequence GetHttpResponse(String urlString) throws IOException {
        URL url = new URL(urlString);
        URLConnection connection = url.openConnection();
        if (!(connection instanceof HttpURLConnection)) {
            throw new IOException("Not an HTTP connection");
        }
        HttpURLConnection httpConnection = (HttpURLConnection) connection;
        int responseCode = httpConnection.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            String responseMessage = httpConnection.getResponseMessage();
            throw new IOException("HTTP response code: " + responseCode + " " + responseMessage);
        }
        InputStream inputStream = httpConnection.getInputStream();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(inputStream));
            int contentLength = httpConnection.getContentLength();
            // Some services does not include a proper Content-Length in the response:
            StringBuilder result = (contentLength > 0) ? new StringBuilder(contentLength) : new StringBuilder();
            while (true) {
                String line = reader.readLine();
                if (line == null) break;
                result.append(line);
            }
            return result;
        } finally {
            if (reader != null) reader.close();
        }
    }
}