Browse Source

API connection for registration, login, logout, restaurants list, restaurants map

master
Apostolos Fanakis 6 years ago
parent
commit
f492a93105
  1. 61
      UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/activities/LoginActivity.java
  2. 60
      UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/activities/SignUpActivity.java
  3. 106
      UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/activities/main/MainActivity.java
  4. 63
      UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/activities/main/MainAdapter.java
  5. 35
      UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/activities/main/fragments/MainListFragment.java
  6. 133
      UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/activities/main/fragments/MainMapFragment.java
  7. 41
      UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/base/BaseActivity.java
  8. 2
      UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/base/BaseApplication.java
  9. 61
      UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/model/Restaurant.java
  10. 147
      UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/session/SessionManager.java

61
UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/activities/LoginActivity.java

@ -1,20 +1,37 @@
package gr.auth.databases.flavours.activities; package gr.auth.databases.flavours.activities;
import android.content.Intent; import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.view.View; import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.widget.AppCompatButton;
import gr.auth.databases.flavours.R; import gr.auth.databases.flavours.R;
import gr.auth.databases.flavours.activities.main.MainActivity; import gr.auth.databases.flavours.activities.main.MainActivity;
import gr.auth.databases.flavours.base.BaseActivity; import gr.auth.databases.flavours.base.BaseActivity;
public class LoginActivity extends BaseActivity { public class LoginActivity extends BaseActivity {
private AppCompatButton loginButton;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login); setContentView(R.layout.activity_login);
if (!sessionManager.isLoginScreenDefault()) {
//Go to main
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
return; //Avoid executing the code below
}
final EditText usernameInput = findViewById(R.id.login_username);
final EditText passwordInput = findViewById(R.id.login_password);
findViewById(R.id.login_btn_sign_up).setOnClickListener(new View.OnClickListener() { findViewById(R.id.login_btn_sign_up).setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View view) { public void onClick(View view) {
@ -24,13 +41,49 @@ public class LoginActivity extends BaseActivity {
} }
}); });
findViewById(R.id.login_btn_login).setOnClickListener(new View.OnClickListener() { loginButton = findViewById(R.id.login_btn_login);
loginButton.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View view) { public void onClick(View view) {
Intent intent = new Intent(view.getContext(), MainActivity.class); LoginTask loginTask = new LoginTask();
startActivity(intent); loginTask.execute(usernameInput.getText().toString(), passwordInput.getText().toString());
finish();
} }
}); });
} }
private class LoginTask extends AsyncTask<String, Void, Integer> {
@Override
protected void onPreExecute() { //Show a progress dialog until done
loginButton.setEnabled(false);
View view = getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
@Override
protected Integer doInBackground(String... params) {
return sessionManager.login(params[0], params[1]);
}
@Override
protected void onPostExecute(Integer result) { //Handle attempt result
Toast.makeText(getApplicationContext(),
"Welcome, " + sessionManager.getUsername() + "!", Toast.LENGTH_LONG)
.show();
Intent intent = new Intent(getBaseContext(), MainActivity.class);
startActivity(intent);
finish();
}
@Override
protected void onCancelled() {
super.onCancelled();
loginButton.setEnabled(true); //Re-enable login button
}
}
} }

60
UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/activities/SignUpActivity.java

@ -4,21 +4,28 @@ import android.annotation.SuppressLint;
import android.app.DatePickerDialog; import android.app.DatePickerDialog;
import android.app.Dialog; import android.app.Dialog;
import android.content.Intent; import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.view.MotionEvent; import android.view.MotionEvent;
import android.view.View; import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.DatePicker; import android.widget.DatePicker;
import android.widget.EditText; import android.widget.EditText;
import android.widget.Toast;
import java.util.Calendar; import java.util.Calendar;
import java.util.Objects; import java.util.Objects;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatButton;
import androidx.fragment.app.DialogFragment; import androidx.fragment.app.DialogFragment;
import gr.auth.databases.flavours.R; import gr.auth.databases.flavours.R;
import gr.auth.databases.flavours.activities.main.MainActivity;
import gr.auth.databases.flavours.base.BaseActivity; import gr.auth.databases.flavours.base.BaseActivity;
public class SignUpActivity extends BaseActivity { public class SignUpActivity extends BaseActivity {
private EditText emailInput, usernameInput, passwordInput, birthdayInput;
private AppCompatButton signupButton;
@SuppressLint("ClickableViewAccessibility") @SuppressLint("ClickableViewAccessibility")
@Override @Override
@ -35,7 +42,10 @@ public class SignUpActivity extends BaseActivity {
} }
}); });
EditText birthdayInput = findViewById(R.id.sign_up_birthday); emailInput = findViewById(R.id.sign_up_email);
usernameInput = findViewById(R.id.sign_up_username);
passwordInput = findViewById(R.id.sign_up_password);
birthdayInput = findViewById(R.id.sign_up_birthday);
birthdayInput.setOnTouchListener(new View.OnTouchListener() { birthdayInput.setOnTouchListener(new View.OnTouchListener() {
@Override @Override
public boolean onTouch(View view, MotionEvent motionEvent) { public boolean onTouch(View view, MotionEvent motionEvent) {
@ -46,6 +56,18 @@ public class SignUpActivity extends BaseActivity {
return false; return false;
} }
}); });
signupButton = findViewById(R.id.sign_up_btn_sign_up);
signupButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SignupTask signupTask = new SignupTask();
signupTask.execute(emailInput.getText().toString(),
usernameInput.getText().toString(),
passwordInput.getText().toString(),
birthdayInput.getText().toString());
}
});
} }
public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
@ -69,4 +91,40 @@ public class SignUpActivity extends BaseActivity {
birthdayInput.setText(getResources().getString(R.string.sign_up_birthday_placeholder, year, month + 1, day)); birthdayInput.setText(getResources().getString(R.string.sign_up_birthday_placeholder, year, month + 1, day));
} }
} }
private class SignupTask extends AsyncTask<String, Void, Integer> {
@Override
protected void onPreExecute() { //Show a progress dialog until done
signupButton.setEnabled(false);
View view = getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
@Override
protected Integer doInBackground(String... params) {
return sessionManager.signup(params[0], params[1], params[2], params[3]);
}
@Override
protected void onPostExecute(Integer result) { //Handle attempt result
Toast.makeText(getApplicationContext(),
"Welcome, " + sessionManager.getUsername() + "!", Toast.LENGTH_LONG)
.show();
Intent intent = new Intent(getBaseContext(), MainActivity.class);
startActivity(intent);
finish();
}
@Override
protected void onCancelled() {
super.onCancelled();
signupButton.setEnabled(true); //Re-enable login button
}
}
} }

106
UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/activities/main/MainActivity.java

@ -2,7 +2,9 @@ package gr.auth.databases.flavours.activities.main;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.Menu; import android.view.Menu;
import android.view.MenuItem; import android.view.MenuItem;
@ -11,6 +13,9 @@ import android.widget.EditText;
import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.floatingactionbutton.FloatingActionButton;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList; import java.util.ArrayList;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
@ -28,10 +33,17 @@ import gr.auth.databases.flavours.activities.AddRestaurantActivity;
import gr.auth.databases.flavours.activities.main.fragments.MainListFragment; import gr.auth.databases.flavours.activities.main.fragments.MainListFragment;
import gr.auth.databases.flavours.activities.main.fragments.MainMapFragment; import gr.auth.databases.flavours.activities.main.fragments.MainMapFragment;
import gr.auth.databases.flavours.base.BaseActivity; import gr.auth.databases.flavours.base.BaseActivity;
import gr.auth.databases.flavours.model.Restaurant;
import okhttp3.HttpUrl;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends BaseActivity { public class MainActivity extends BaseActivity {
private static final HttpUrl restaurantsUrl = HttpUrl.parse("http://83.212.109.171:8181/api/restaurant/");
private static final int NUM_PAGES = 2; private static final int NUM_PAGES = 2;
private ArrayList<Restaurant> restaurants = new ArrayList<>();
private ViewPager viewPager; private ViewPager viewPager;
private MenuItem menuMapItem; private MenuItem menuMapItem;
private FloatingActionButton FAB; private FloatingActionButton FAB;
@ -88,6 +100,9 @@ public class MainActivity extends BaseActivity {
PagerAdapter pagerAdapter = new MainPagerAdapter(getSupportFragmentManager()); PagerAdapter pagerAdapter = new MainPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter); viewPager.setAdapter(pagerAdapter);
MainTask mainTask = new MainTask();
mainTask.execute();
} }
@Override @Override
@ -223,6 +238,44 @@ public class MainActivity extends BaseActivity {
return super.onOptionsItemSelected(item); return super.onOptionsItemSelected(item);
} }
/*private void setupViewPager(ViewPager viewPager) {
RestaurantPagerAdapter adapter = new RestaurantPagerAdapter(getSupportFragmentManager());
adapter.addFrag(DrinkInfoFragment.newInstance(64), "INFO");
adapter.addFrag(DrinkIngredientsFragment.newInstance(64), "INGREDIENTS");
adapter.addFrag(DrinkRatingsFragment.newInstance(64), "RATINGS");
viewPager.setAdapter(adapter);
}
private class MainPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
MainPagerAdapter(FragmentManager manager) {
super(manager);
}
@NonNull
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}*/
private class MainPagerAdapter extends FragmentStatePagerAdapter { private class MainPagerAdapter extends FragmentStatePagerAdapter {
MainPagerAdapter(FragmentManager fm) { MainPagerAdapter(FragmentManager fm) {
super(fm); super(fm);
@ -232,9 +285,9 @@ public class MainActivity extends BaseActivity {
@Override @Override
public Fragment getItem(int position) { public Fragment getItem(int position) {
if (position == 0) { if (position == 0) {
return new MainListFragment(); return MainListFragment.newInstance(restaurants);
} else { } else {
return new MainMapFragment(); return MainMapFragment.newInstance(restaurants);
} }
} }
@ -243,4 +296,53 @@ public class MainActivity extends BaseActivity {
return NUM_PAGES; return NUM_PAGES;
} }
} }
private class MainTask extends AsyncTask<Void, Void, Integer> {
private static final String JSON_TAG_RESTAURANT_ID = "restaurant_id";
private static final String JSON_TAG_RESTAURANT_NAME = "restaurant_name";
private static final String JSON_TAG_RESTAURANT_CATEGORY = "restaurant_category";
private static final String JSON_TAG_RESTAURANT_LONGITUDE = "restaurant_longitude";
private static final String JSON_TAG_RESTAURANT_LATITUDE = "restaurant_latitude";
private static final String JSON_TAG_RESTAURANT_OPENING = "restaurant_opening";
private static final String JSON_TAG_RESTAURANT_CLOSING = "restaurant_closing";
@Override
protected void onPreExecute() { //Show a progress dialog until done
}
@Override
protected Integer doInBackground(Void... params) {
//Builds the signup request
Request request = new Request.Builder()
.url(restaurantsUrl)
.build();
try {
//Makes request & handles response
Response response = client.newCall(request).execute();
String result = response.body().string();
JSONArray jsonRestaurants = new JSONArray(result);
for (int restaurantIndex = 0; restaurantIndex < jsonRestaurants.length(); ++restaurantIndex) {
JSONObject jsonRestaurant = jsonRestaurants.getJSONObject(restaurantIndex);
restaurants.add(new Restaurant(
jsonRestaurant.getInt(JSON_TAG_RESTAURANT_ID),
jsonRestaurant.getString(JSON_TAG_RESTAURANT_NAME),
jsonRestaurant.getString(JSON_TAG_RESTAURANT_CATEGORY),
jsonRestaurant.getDouble(JSON_TAG_RESTAURANT_LONGITUDE),
jsonRestaurant.getDouble(JSON_TAG_RESTAURANT_LATITUDE),
jsonRestaurant.getString(JSON_TAG_RESTAURANT_OPENING),
jsonRestaurant.getString(JSON_TAG_RESTAURANT_CLOSING)));
}
return 1;
} catch (Exception e) {
return 2;
}
}
@Override
protected void onPostExecute(Integer result) { //Handle attempt result
}
}
} }

63
UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/activities/main/MainAdapter.java

@ -2,12 +2,15 @@ package gr.auth.databases.flavours.activities.main;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.TextView; import android.widget.TextView;
import java.util.ArrayList;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView; import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
@ -17,9 +20,9 @@ import gr.auth.databases.flavours.model.Restaurant;
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.RestaurantViewHolder> { public class MainAdapter extends RecyclerView.Adapter<MainAdapter.RestaurantViewHolder> {
private Context context; private Context context;
private Restaurant[] restaurants; private ArrayList<Restaurant> restaurants;
public MainAdapter(Context context, Restaurant[] restaurants) { public MainAdapter(Context context, ArrayList<Restaurant> restaurants) {
this.context = context; this.context = context;
this.restaurants = restaurants; this.restaurants = restaurants;
} }
@ -42,40 +45,42 @@ public class MainAdapter extends RecyclerView.Adapter<MainAdapter.RestaurantView
context.startActivity(intent); context.startActivity(intent);
} }
}); });
holder.name.setText(restaurants[position].getName()); holder.name.setText(restaurants.get(position).getName());
holder.workingHours.setText(context.getString(R.string.main_row_working_hours_placeholder, holder.workingHours.setText(context.getString(R.string.main_row_working_hours_placeholder,
restaurants[position].getOpeningTime().substring(0, 5), restaurants.get(position).getOpeningTime().substring(0, 5),
restaurants[position].getClosingTime().substring(0, 5))); restaurants.get(position).getClosingTime().substring(0, 5)));
if (restaurants[position].getType().equals("restaurant")) { switch (restaurants.get(position).getType()) {
holder.typeImage.setImageResource(R.drawable.restaurant_marker); case "restaurant":
holder.typeText.setText(context.getResources().getString(R.string.main_restaurant_type)); holder.typeImage.setImageResource(R.drawable.restaurant_marker);
} holder.typeText.setText(context.getResources().getString(R.string.main_restaurant_type));
if (restaurants[position].getType().equals("bar")) { break;
holder.typeImage.setImageResource(R.drawable.bar_marker); case "bar":
holder.typeText.setText(context.getResources().getString(R.string.main_bar_type)); holder.typeImage.setImageResource(R.drawable.bar_marker);
} holder.typeText.setText(context.getResources().getString(R.string.main_bar_type));
if (restaurants[position].getType().equals("cafeteria")) { break;
holder.typeImage.setImageResource(R.drawable.cafeteria_marker); case "cafeteria":
holder.typeText.setText(context.getResources().getString(R.string.main_cafeteria_type)); holder.typeImage.setImageResource(R.drawable.cafeteria_marker);
} holder.typeText.setText(context.getResources().getString(R.string.main_cafeteria_type));
if (restaurants[position].getType().equals("pub")) { break;
holder.typeImage.setImageResource(R.drawable.pub_marker); case "pub":
holder.typeText.setText(context.getResources().getString(R.string.main_pub_type)); holder.typeImage.setImageResource(R.drawable.pub_marker);
} holder.typeText.setText(context.getResources().getString(R.string.main_pub_type));
if (restaurants[position].getType().equals("fast_food")) { break;
holder.typeImage.setImageResource(R.drawable.fast_food_marker); case "fast_food":
holder.typeText.setText(context.getResources().getString(R.string.main_fast_food_type)); holder.typeImage.setImageResource(R.drawable.fast_food_marker);
} holder.typeText.setText(context.getResources().getString(R.string.main_fast_food_type));
if (restaurants[position].getType().equals("ethnic")) { break;
holder.typeImage.setImageResource(R.drawable.restaurant_marker); case "ethnic":
holder.typeText.setText(context.getResources().getString(R.string.main_ethnic_type)); holder.typeImage.setImageResource(R.drawable.restaurant_marker);
holder.typeText.setText(context.getResources().getString(R.string.main_ethnic_type));
break;
} }
} }
@Override @Override
public int getItemCount() { public int getItemCount() {
return restaurants.length; return restaurants.size();
} }
static class RestaurantViewHolder extends RecyclerView.ViewHolder { static class RestaurantViewHolder extends RecyclerView.ViewHolder {

35
UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/activities/main/fragments/MainListFragment.java

@ -5,6 +5,8 @@ import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import java.util.ArrayList;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager;
@ -14,7 +16,24 @@ import gr.auth.databases.flavours.activities.main.MainAdapter;
import gr.auth.databases.flavours.model.Restaurant; import gr.auth.databases.flavours.model.Restaurant;
public class MainListFragment extends Fragment { public class MainListFragment extends Fragment {
private Restaurant[] restaurants = new Restaurant[13]; private static final String RESTAURANTS_TAG = "RESTAURANTS_TAG";
private ArrayList<Restaurant> restaurants;
public static MainListFragment newInstance(ArrayList<Restaurant> restaurants) {
MainListFragment fragment = new MainListFragment();
Bundle args = new Bundle();
args.putParcelableArrayList(RESTAURANTS_TAG, restaurants);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
assert getArguments() != null;
this.restaurants = getArguments().getParcelableArrayList(RESTAURANTS_TAG);
}
@Override @Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
@ -25,20 +44,6 @@ public class MainListFragment extends Fragment {
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext()); LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager); recyclerView.setLayoutManager(layoutManager);
restaurants[0] = new Restaurant("U Fleků", "pub", "18:00:00", "04:00:00");
restaurants[1] = new Restaurant("Σ σύγχρονα εστιατόρια", "restaurant", "12:00:00", "22:00:00");
restaurants[2] = new Restaurant("U Fleků Garden", "pub", "18:00:00", "02:00:00");
restaurants[3] = new Restaurant("McDonald\'s", "fast_food", "12:00:00", "23:59:00");
restaurants[4] = new Restaurant("Grill 15", "fast_food", "12:00:00", "01:30:00");
restaurants[5] = new Restaurant("Butterflies and Hurricanes", "cafeteria", "08:00:00", "20:00:00");
restaurants[6] = new Restaurant("The Hoppy Pub", "pub", "17:30:00", "01:30:00");
restaurants[7] = new Restaurant("Belleville sin patron", "bar", "12:00:00", "02:00:00");
restaurants[8] = new Restaurant("Αιθερόπλοο", "pub", "08:00:00", "02:00:00");
restaurants[9] = new Restaurant("Οδυσσέας", "restaurant", "12:30:00", "18:00:00");
restaurants[10] = new Restaurant("Pulp", "bar", "09:00:00", "23:59:00");
restaurants[11] = new Restaurant("McDonald\'s", "fast_food", "12:00:00", "23:59:00");
restaurants[12] = new Restaurant("Γιαννούλα", "restaurant", "13:30:00", "01:00:00");
MainAdapter mainAdapter = new MainAdapter(getContext(), restaurants); MainAdapter mainAdapter = new MainAdapter(getContext(), restaurants);
recyclerView.setAdapter(mainAdapter); recyclerView.setAdapter(mainAdapter);

133
UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/activities/main/fragments/MainMapFragment.java

@ -1,6 +1,7 @@
package gr.auth.databases.flavours.activities.main.fragments; package gr.auth.databases.flavours.activities.main.fragments;
import android.os.Bundle; import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
@ -13,12 +14,33 @@ import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.MarkerOptions;
import java.util.ArrayList;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
import gr.auth.databases.flavours.R; import gr.auth.databases.flavours.R;
import gr.auth.databases.flavours.model.Restaurant;
public class MainMapFragment extends Fragment implements OnMapReadyCallback { public class MainMapFragment extends Fragment implements OnMapReadyCallback {
private MapView gMapView = null; private MapView gMapView = null;
private static final String RESTAURANTS_TAG = "RESTAURANTS_TAG";
private ArrayList<Restaurant> restaurants;
public static MainMapFragment newInstance(ArrayList<Restaurant> restaurants) {
MainMapFragment fragment = new MainMapFragment();
Bundle args = new Bundle();
args.putParcelableArrayList(RESTAURANTS_TAG, restaurants);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
assert getArguments() != null;
this.restaurants = getArguments().getParcelableArrayList(RESTAURANTS_TAG);
}
@Override @Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
@ -89,72 +111,49 @@ public class MainMapFragment extends Fragment implements OnMapReadyCallback {
@Override @Override
public void onMapReady(GoogleMap googleMap) { public void onMapReady(GoogleMap googleMap) {
// Add markers and move the camera // Add markers and move the camera
LatLng uFleku = new LatLng(40.6357, 22.9367); for (Restaurant restaurant : restaurants) {
LatLng sSyxronaEstiatoria = new LatLng(40.6173, 22.9597); LatLng restaurantPosition = new LatLng(restaurant.getLongitude(), restaurant.getLatitude());
LatLng uFlekuGarden = new LatLng(40.6354, 22.937);
LatLng mcDonalds = new LatLng(40.6463, 22.9206); switch (restaurant.getType()) {
LatLng grill15 = new LatLng(40.6215, 22.961); case "restaurant":
LatLng butterfliesAndHurricanes = new LatLng(40.6147, 22.9609); googleMap.addMarker(new MarkerOptions()
LatLng theHoppyPub = new LatLng(40.6279, 22.9489); .position(restaurantPosition)
LatLng bellevilleSinPatron = new LatLng(40.6337, 22.9518); .title(restaurant.getName())
LatLng aitheroploo = new LatLng(40.6144, 22.9598); .icon(BitmapDescriptorFactory.fromResource(R.drawable.restaurant_marker)));
LatLng odysseas = new LatLng(40.6369, 22.9534); break;
LatLng pulp = new LatLng(40.6321, 22.9479); case "bar":
LatLng mcDonalds2 = new LatLng(40.5745, 22.9715); googleMap.addMarker(new MarkerOptions()
LatLng gianoula = new LatLng(40.64, 22.9468); .position(restaurantPosition)
.title(restaurant.getName())
googleMap.addMarker(new MarkerOptions() .icon(BitmapDescriptorFactory.fromResource(R.drawable.bar_marker)));
.position(uFleku) break;
.title("U Fleků") case "cafeteria":
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pub_marker))); googleMap.addMarker(new MarkerOptions()
googleMap.addMarker(new MarkerOptions() .position(restaurantPosition)
.position(sSyxronaEstiatoria) .title(restaurant.getName())
.title("Σ σύγχρονα εστιατόρια") .icon(BitmapDescriptorFactory.fromResource(R.drawable.cafeteria_marker)));
.icon(BitmapDescriptorFactory.fromResource(R.drawable.restaurant_marker))); break;
googleMap.addMarker(new MarkerOptions() case "pub":
.position(uFlekuGarden) googleMap.addMarker(new MarkerOptions()
.title("U Fleků Garden") .position(restaurantPosition)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pub_marker))); .title(restaurant.getName())
googleMap.addMarker(new MarkerOptions() .icon(BitmapDescriptorFactory.fromResource(R.drawable.pub_marker)));
.position(mcDonalds) break;
.title("McDonald\'s") case "fast_food":
.icon(BitmapDescriptorFactory.fromResource(R.drawable.fast_food_marker))); googleMap.addMarker(new MarkerOptions()
googleMap.addMarker(new MarkerOptions() .position(restaurantPosition)
.position(grill15) .title(restaurant.getName())
.title("Grill 15") .icon(BitmapDescriptorFactory.fromResource(R.drawable.fast_food_marker)));
.icon(BitmapDescriptorFactory.fromResource(R.drawable.fast_food_marker))); break;
googleMap.addMarker(new MarkerOptions() case "ethnic":
.position(butterfliesAndHurricanes) googleMap.addMarker(new MarkerOptions()
.title("Butterflies and Hurricanes") .position(restaurantPosition)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.cafeteria_marker))); .title(restaurant.getName())
googleMap.addMarker(new MarkerOptions() .icon(BitmapDescriptorFactory.fromResource(R.drawable.pub_marker)));
.position(theHoppyPub) break;
.title("The Hoppy Pub") }
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pub_marker))); }
googleMap.addMarker(new MarkerOptions()
.position(bellevilleSinPatron) googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(40.6215, 22.961), 12.0f));
.title("Belleville sin patron")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.bar_marker)));
googleMap.addMarker(new MarkerOptions()
.position(aitheroploo)
.title("Αιθερόπλοο")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pub_marker)));
googleMap.addMarker(new MarkerOptions()
.position(odysseas)
.title("Οδυσσέας")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.restaurant_marker)));
googleMap.addMarker(new MarkerOptions()
.position(pulp)
.title("Pulp")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.bar_marker)));
googleMap.addMarker(new MarkerOptions()
.position(mcDonalds2)
.title("McDonald\'s")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.fast_food_marker)));
googleMap.addMarker(new MarkerOptions()
.position(gianoula)
.title("Γιαννούλα")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.restaurant_marker)));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(grill15, 12.0f));
} }
} }

41
UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/base/BaseActivity.java

@ -4,6 +4,7 @@ import android.Manifest;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.view.View; import android.view.View;
@ -203,18 +204,17 @@ public abstract class BaseActivity extends AppCompatActivity {
.withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() { .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
@Override @Override
public boolean onProfileChanged(View view, IProfile profile, boolean current) { public boolean onProfileChanged(View view, IProfile profile, boolean current) {
//if (sessionManager.isLoggedIn()) { if (sessionManager.isLoggedIn()) {
Intent intent = new Intent(BaseActivity.this, ProfileActivity.class); Intent intent = new Intent(BaseActivity.this, ProfileActivity.class);
Bundle extras = new Bundle(); Bundle extras = new Bundle();
extras.putInt(BUNDLE_USER_ID, sessionManager.getUserId()); extras.putInt(BUNDLE_USER_ID, sessionManager.getUserId());
intent.putExtras(extras); intent.putExtras(extras);
intent.setFlags(FLAG_ACTIVITY_NEW_TASK); intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
startActivity(intent); startActivity(intent);
return false; return false;
//TODO } else
/*} else startLoginActivity();
startLoginActivity();*/ return true;
//return true;
} }
}) })
.build(); .build();
@ -242,8 +242,8 @@ public abstract class BaseActivity extends AppCompatActivity {
} else if (drawerItem.equals(LOG_ID)) { } else if (drawerItem.equals(LOG_ID)) {
if (!sessionManager.isLoggedIn()) //When logged out or if user is guest if (!sessionManager.isLoggedIn()) //When logged out or if user is guest
startLoginActivity(); startLoginActivity();
/*else else
new LogoutTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);*/ new LogoutTask().execute();
} }
drawer.closeDrawer(); drawer.closeDrawer();
@ -313,4 +313,17 @@ public abstract class BaseActivity extends AppCompatActivity {
Intent intent = new Intent(BaseActivity.this, LoginActivity.class); Intent intent = new Intent(BaseActivity.this, LoginActivity.class);
startActivity(intent); startActivity(intent);
} }
private class LogoutTask extends AsyncTask<Void, Void, Integer> {
protected Integer doInBackground(Void... voids) {
return sessionManager.logout();
}
protected void onPreExecute() {
}
protected void onPostExecute(Integer result) {
updateDrawer();
}
}
} }

2
UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/base/BaseApplication.java

@ -21,7 +21,7 @@ public class BaseApplication extends Application {
private OkHttpClient client; private OkHttpClient client;
private SessionManager sessionManager; private SessionManager sessionManager;
private static final String SHARED_PREFS = "ThmmySharedPrefs"; private static final String SHARED_PREFS = "FlavoursSharedPrefs";
private static float dpWidth; private static float dpWidth;

61
UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/model/Restaurant.java

@ -1,8 +1,11 @@
package gr.auth.databases.flavours.model; package gr.auth.databases.flavours.model;
import android.os.Parcel;
import android.os.Parcelable;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
public class Restaurant { public class Restaurant implements Parcelable {
public enum RestaurantType { public enum RestaurantType {
CAFETERIA(0), PUB(1), BAR(2), RESTAURANT(3), FAST_FOOD(4), ETHNIC(5), UNSUPPORTED(-1); CAFETERIA(0), PUB(1), BAR(2), RESTAURANT(3), FAST_FOOD(4), ETHNIC(5), UNSUPPORTED(-1);
@ -56,15 +59,25 @@ public class Restaurant {
} }
} }
private final int id;
private final String name, type, openingTime, closingTime; private final String name, type, openingTime, closingTime;
private final double longitude, latitude;
public Restaurant(String name, String type, String openingTime, String closingTime) { public Restaurant(int id, String name, String type, double longitude, double latitude,
String openingTime, String closingTime) {
this.id = id;
this.name = name; this.name = name;
this.type = type; this.type = type;
this.longitude = longitude;
this.latitude = latitude;
this.openingTime = openingTime; this.openingTime = openingTime;
this.closingTime = closingTime; this.closingTime = closingTime;
} }
public int getId() {
return id;
}
public String getName() { public String getName() {
return name; return name;
} }
@ -73,6 +86,14 @@ public class Restaurant {
return type; return type;
} }
public double getLongitude() {
return longitude;
}
public double getLatitude() {
return latitude;
}
public String getOpeningTime() { public String getOpeningTime() {
return openingTime; return openingTime;
} }
@ -80,4 +101,40 @@ public class Restaurant {
public String getClosingTime() { public String getClosingTime() {
return closingTime; return closingTime;
} }
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(id);
out.writeString(name);
out.writeString(type);
out.writeDouble(longitude);
out.writeDouble(latitude);
out.writeString(openingTime);
out.writeString(closingTime);
}
public static final Parcelable.Creator<Restaurant> CREATOR = new Parcelable.Creator<Restaurant>() {
public Restaurant createFromParcel(Parcel in) {
return new Restaurant(in);
}
public Restaurant[] newArray(int size) {
return new Restaurant[size];
}
};
private Restaurant(Parcel in) {
id = in.readInt();
name = in.readString();
type = in.readString();
longitude = in.readDouble();
latitude = in.readDouble();
openingTime = in.readString();
closingTime = in.readString();
}
} }

147
UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/session/SessionManager.java

@ -1,6 +1,7 @@
package gr.auth.databases.flavours.session; package gr.auth.databases.flavours.session;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.util.Log;
import com.franmontiel.persistentcookiejar.PersistentCookieJar; import com.franmontiel.persistentcookiejar.PersistentCookieJar;
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor; import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor;
@ -44,8 +45,9 @@ public class SessionManager {
} }
//Generic constants //Generic constants
public static final HttpUrl indexUrl = HttpUrl.parse("https://www.thmmy.gr/smf/index.php?theme=4"); private static final HttpUrl loginUrl = HttpUrl.parse("http://83.212.109.171:8181/api/rest-auth/login/");
private static final HttpUrl loginUrl = HttpUrl.parse("https://www.thmmy.gr/smf/index.php?action=login2"); private static final HttpUrl signupUrl = HttpUrl.parse("http://83.212.109.171:8181/api/rest-auth/registration/");
private static final HttpUrl logoutUrl = HttpUrl.parse("http://83.212.109.171:8181/api/rest-auth/logout/");
// Client & Cookies // Client & Cookies
private final OkHttpClient client; private final OkHttpClient client;
@ -57,7 +59,6 @@ public class SessionManager {
private static final String USERNAME = "Username"; private static final String USERNAME = "Username";
private static final String USER_ID = "UserID"; private static final String USER_ID = "UserID";
private static final String USER_TYPE = "USER_TYPE"; private static final String USER_TYPE = "USER_TYPE";
private static final String LOGOUT_LINK = "LogoutLink";
private static final String LOGGED_IN = "LoggedIn"; private static final String LOGGED_IN = "LoggedIn";
private static final String LOGIN_SCREEN_AS_DEFAULT = "LoginScreenAsDefault"; private static final String LOGIN_SCREEN_AS_DEFAULT = "LoginScreenAsDefault";
@ -73,63 +74,78 @@ public class SessionManager {
public int login(String... strings) { public int login(String... strings) {
//Builds the login request for each case //Builds the login request for each case
Request request; Request request;
if (strings.length == 2) { clearSessionData();
clearSessionData();
String username = strings[0];
String password = strings[1];
RequestBody formBody = new FormBody.Builder()
.add("username", username)
.add("password", password)
.build();
request = new Request.Builder()
.url(loginUrl)
.post(formBody)
.build();
String loginName = strings[0];
String password = strings[1]; try {
//Makes request & handles response
RequestBody formBody = new FormBody.Builder() Response response = client.newCall(request).execute();
.add("user", loginName)
.add("passwrd", password) setPersistentCookieSession(loginUrl); //Store cookies
.add("cookielength", "-1") //-1 is forever
.build(); //Edit SharedPreferences, save session's data
request = new Request.Builder() SharedPreferences.Editor editor = sharedPrefs.edit();
.url(loginUrl) setLoginScreenAsDefault(false);
.post(formBody) editor.putBoolean(LOGGED_IN, true);
.build(); editor.putString(USERNAME, username);
} else { editor.putInt(USER_ID, 10);
request = new Request.Builder() editor.putInt(USER_TYPE, UserType.USER.getId());
.url(loginUrl) editor.apply();
.build(); return 0;
} catch (Exception e) {
return 2;
} }
}
public int signup(String... strings) {
//Builds the signup request
Request request;
clearSessionData();
String email = strings[0];
String username = strings[1];
String password = strings[2];
String birthday = strings[3];
RequestBody formBody = new FormBody.Builder()
.add("email", email)
.add("username", username)
.add("password1", password)
.add("password2", password)
.build();
request = new Request.Builder()
.url(signupUrl)
.post(formBody)
.build();
try { try {
//Makes request & handles response //Makes request & handles response
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
if (validateRetrievedCookies()) { setPersistentCookieSession(signupUrl); //Store cookies
setPersistentCookieSession(); //Store cookies
//Edit SharedPreferences, save session's data
//Edit SharedPreferences, save session's data SharedPreferences.Editor editor = sharedPrefs.edit();
SharedPreferences.Editor editor = sharedPrefs.edit(); setLoginScreenAsDefault(false);
setLoginScreenAsDefault(false); editor.putBoolean(LOGGED_IN, true);
editor.putBoolean(LOGGED_IN, true); editor.putString(USERNAME, username);
editor.putString(USERNAME, "Username"); editor.putInt(USER_ID, 10);
editor.putInt(USER_ID, 10); editor.putInt(USER_TYPE, UserType.USER.getId());
editor.putInt(USER_TYPE, UserType.USER.getId()); editor.apply();
editor.apply(); return 0;
return 0;
} else {
//Investigates login failure
/*if (error.size() > 0) { //Wrong username
return WRONG_USER;
}
if (error.size() > 0) { //Wrong password
return WRONG_PASSWORD;
}
if (error.size() > 0) { //User is banned
return BANNED_USER;
}*/
//Other error e.g. session was reset server-side
clearSessionData(); //Clear invalid saved data
return 1;
}
//Handles exceptions
} catch (Exception e) { } catch (Exception e) {
return 2; return 2;
} }
@ -149,7 +165,7 @@ public class SessionManager {
public int logout() { public int logout() {
Request request = new Request.Builder() Request request = new Request.Builder()
.url(sharedPrefs.getString(LOGOUT_LINK, "LogoutLink")) .url(logoutUrl)
.build(); .build();
try { try {
@ -177,15 +193,6 @@ public class SessionManager {
return UserType.fromInteger(sharedPrefs.getInt(USER_TYPE, -1)); return UserType.fromInteger(sharedPrefs.getInt(USER_TYPE, -1));
} }
public Cookie getThmmyCookie() {
List<Cookie> cookieList = cookieJar.loadForRequest(indexUrl);
for (Cookie cookie : cookieList) {
if (cookie.name().equals("THMMYgrC00ki3"))
return cookie;
}
return null;
}
public boolean isLoggedIn() { public boolean isLoggedIn() {
return sharedPrefs.getBoolean(LOGGED_IN, false); return sharedPrefs.getBoolean(LOGGED_IN, false);
} }
@ -194,18 +201,8 @@ public class SessionManager {
return sharedPrefs.getBoolean(LOGIN_SCREEN_AS_DEFAULT, true); return sharedPrefs.getBoolean(LOGIN_SCREEN_AS_DEFAULT, true);
} }
private boolean validateRetrievedCookies() { private void setPersistentCookieSession(HttpUrl forUrl) {
List<Cookie> cookieList = cookieJar.loadForRequest(indexUrl); List<Cookie> cookieList = cookieJar.loadForRequest(forUrl);
for (Cookie cookie : cookieList) {
if (cookie.name().equals("THMMYgrC00ki3"))
return true;
}
return false;
}
// Call validateRetrievedCookies() first
private void setPersistentCookieSession() {
List<Cookie> cookieList = cookieJar.loadForRequest(indexUrl);
Cookie.Builder builder = new Cookie.Builder(); Cookie.Builder builder = new Cookie.Builder();
builder.name(cookieList.get(1).name()) builder.name(cookieList.get(1).name())
.value(cookieList.get(1).value()) .value(cookieList.get(1).value())

Loading…
Cancel
Save