restarant source code
TRANSCRIPT
-
8/4/2019 Restarant Source Code
1/31
AndroidManifest.xml
FoodoApp.java
-
8/4/2019 Restarant Source Code
2/31
package is.hi.foodo;
import is.hi.foodo.net.FoodoService;import is.hi.foodo.net.WebService;
import is.hi.foodo.user.FoodoUserManager;import is.hi.foodo.user.UserManager;import android.app.Application;import android.content.Intent;import android.util.Log;
public class FoodoApp extends Application {private static final String TAG = "FoodoApp";
private FoodoService service;private UserManager userManager;
@Overridepublic void onCreate() {
this.service = newWebService(this.getResources().getString(R.string.api_path));
this.userManager = new FoodoUserManager(this.service,FoodoApp.this);
Log.d(TAG, this.getResources().getString(R.string.api_path));super.onCreate();
//Should maybe only start the service this when a userorders...
this.startService(new Intent(this,FoodoOrderService.class));}
public UserManager getUserManager() {return userManager;}
public FoodoService getService() {return service;
}
}
FoodoMenu.java
-
8/4/2019 Restarant Source Code
3/31
package is.hi.foodo;
import is.hi.foodo.net.FoodoServiceException;
import is.hi.foodo.user.UserManager;
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;
import android.app.AlertDialog;import android.app.Dialog;import android.app.ListActivity;
import android.app.ProgressDialog;import android.content.Context;import android.content.DialogInterface;import android.database.Cursor;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.widget.Button;import android.widget.ListView;import android.widget.SimpleAdapter;
import android.widget.TextView;import android.widget.Toast;
public class FoodoMenu extends ListActivity{
private static final String TAG = "FoodoMenu";
private static final int GETMENU = 0;private static final int SENDORDER = 1;
public static final String ID = "ID";public static final String ITEMID = "ITEMID";
public static final String ITEMNAME = "ITEMNAME";public static final String PRICE = "PRICE";public static final String AMOUNT = "AMOUNT";public static final String SELECTED = "SELECTED";
private static final String TAB = "\t";private static final String TIMES = "x";private static final String NEWLINE = "\n";
-
8/4/2019 Restarant Source Code
4/31
private static int item;
private ProgressDialog pd;private RestaurantDbAdapter mDbHelper;private Long mRowId;private String dialogItem;private static int amount = 0;private Button btnConfOrder, btnUp, btnDown;private View itemLayout, orderLayout;private TextView txtItemCounter, txtItemText;
View listViewItem;private int tempPrice;private UserManager uManager;
static final int MENU_DIALOG = 0;static final int ORDER_DIALOG = 1;//private Cursor mRestaurantCursor;
List< Map > mMenu;
List< Map > mOrder;
@Overrideprotected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
mDbHelper = new RestaurantDbAdapter(this);mDbHelper.open();
uManager =((FoodoApp)this.getApplicationContext()).getUserManager();
LayoutInflater factory = LayoutInflater.from(this);itemLayout = factory.inflate(R.layout.menudialog, null);LayoutInflater factoryOrder = LayoutInflater.from(this);orderLayout = factoryOrder.inflate(R.layout.orderdialog,
null);
getListView().setTextFilterEnabled(true);getListView().setClickable(true);registerForContextMenu(getListView());
setupButtons();
//Check if resuming from a saved instance state
mRowId = (savedInstanceState != null ?savedInstanceState.getLong(RestaurantDbAdapter.KEY_ROWID) : null);
//Get id from intent if not setif (mRowId == null){
Bundle extras = getIntent().getExtras();mRowId = extras != null ?
extras.getLong(RestaurantDbAdapter.KEY_ROWID) : null;}
-
8/4/2019 Restarant Source Code
5/31
Log.d(TAG, "ReId is: " + mRowId);
populateView();mDbHelper.close();
}
@Overrideprotected void onResume() {
super.onResume();
mMenu = new ArrayList();mOrder = new ArrayList();loadMenu();setupList();
}
private void populateView() {if (mRowId != null){
Cursor restaurant = mDbHelper.fetchRestaurant(mRowId);startManagingCursor(restaurant);
TextView mPlaceName = (TextView)this.findViewById(R.id.menuPlace);mPlaceName.setText(restaurant.getString(restaurant.getColumnIndexOrThrow(RestaurantDbAdapter.KEY_NAME)));
}}
public void setupList() {SimpleAdapter adapter = new SimpleAdapter(
this,mMenu,R.layout.listmenu,new String[] {ITEMNAME, PRICE, SELECTED},new int[] {R.id.nameMenu, R.id.priceMenu,
R.id.itemSelected});setListAdapter(adapter);
}
public String createOrder(){String result = "";int sum = 0;for(int i = 0; i < mOrder.size(); i++){
result += mOrder.get(i).get(ITEMNAME);result += NEWLINE;result += mOrder.get(i).get(AMOUNT);result += TIMES;result += mOrder.get(i).get(PRICE);result += TAB;result += "=";result += TAB;result +=
Integer.parseInt(mOrder.get(i).get(PRICE))*Integer.parseInt(mOrder.get(i).get
-
8/4/2019 Restarant Source Code
6/31
(AMOUNT));result += NEWLINE;result += NEWLINE;sum +=
Integer.parseInt(mOrder.get(i).get(PRICE))*Integer.parseInt(mOrder.get(i).get(AMOUNT));
}result += NEWLINE;result += "Total cost: "+ sum;return result;
}
/*** Use: setupButtons()** Finds the buttonview for the confirm button in the view,* and adds a click listener*/public void setupButtons() {
this.btnConfOrder =
(Button)this.findViewById(R.id.bConfOrder);btnConfOrder.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Context context = getApplicationContext();
if(v==btnConfOrder){if(uManager.isAuthenticated()){
if(mOrder.size() > 0){TextView totalOrder =
(TextView) orderLayout.findViewById(R.id.totalOrder);totalOrder.setText(createOrder());showDialog(ORDER_DIALOG);
}else{
Toast.makeText(context, "You haven't picked any items.",Toast.LENGTH_SHORT).show();
}}else {
Toast.makeText(context, "Youhave to be signed in", Toast.LENGTH_SHORT).show();
}}
}});
}
@Overrideprotected void onPrepareDialog (int id, Dialog dialog) {
switch(id) {case MENU_DIALOG:
dialog.setTitle(dialogItem);
-
8/4/2019 Restarant Source Code
7/31
tempPrice =Integer.parseInt( mMenu.get(item).get(PRICE));
txtItemText.setText("Total price: " +(tempPrice*amount));
}}@Overrideprotected Dialog onCreateDialog(int id) {
switch(id) {case MENU_DIALOG:
txtItemText = (TextView)itemLayout.findViewById(R.id.itemText);
tempPrice =Integer.parseInt( mMenu.get(item).get(PRICE));
txtItemText.setText("Total price: " +(tempPrice*amount));
btnUp = (Button) itemLayout.findViewById(R.id.btnUp);btnUp.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v){
amount++;txtItemCounter.setText("" + amount);txtItemText.setText("Total price: " +
(tempPrice*amount));
}});btnDown = (Button)
itemLayout.findViewById(R.id.btnDown);btnDown.setOnClickListener(new
Button.OnClickListener(){@Overridepublic void onClick(View v){
if(amount>0){amount--;
}txtItemCounter.setText("" + amount);txtItemText.setText("Total price: " +
(tempPrice*amount));
}
});return new AlertDialog.Builder(FoodoMenu.this)
.setTitle(dialogItem)
.setView(itemLayout)
.setPositiveButton(R.string.save, newDialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int whichButton) {
boolean itemNotFound = true;// Adds a * for selected item on the
menu thats added to the order.if((amount > 0) &&
-
8/4/2019 Restarant Source Code
8/31
(mMenu.get(item).get(SELECTED).length() == 0)){mMenu.get(item).put(SELECTED,
"*");}else if(amount == 0){
mMenu.get(item).put(SELECTED,"");
}for(int i = 0; i < mOrder.size(); i+
+){if(Integer.parseInt(mOrder.get(i).get(ID)) == item){
if(amount > 0){mOrder.get(i).put(AMOUNT, Integer.toString(amount));
}else{
mOrder.remove(i);
}itemNotFound = false;break;
}}if(itemNotFound){
// Map for the orderinformation
Map map = newHashMap();
map.put(ID,mMenu.get(item).get(ID));
map.put(ITEMID,mMenu.get(item).get(ITEMID));
map.put(ITEMNAME,mMenu.get(item).get(ITEMNAME));
map.put(AMOUNT,Integer.toString(amount));
map.put(PRICE,mMenu.get(item).get(PRICE));
mOrder.add(map);}setupList();getListView().setSelection(item);
}})
.setNegativeButton("Cancel", newDialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int whichButton) {
//amount = 0;dismissDialog(MENU_DIALOG);// removeDialog(MENU_DIALOG);
}}).create();
-
8/4/2019 Restarant Source Code
9/31
case ORDER_DIALOG://LayoutInflater factoryOrder =
LayoutInflater.from(this);//final View layoutOrder =
factoryOrder.inflate(R.layout.orderdialog, null);return new AlertDialog.Builder(FoodoMenu.this).setTitle(R.string.your_order).setView(orderLayout).setPositiveButton(R.string.change_order, new
DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog,
int whichButton) {dismissDialog(ORDER_DIALOG);
}}).setNegativeButton(R.string.confirm_order, new
DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog,
int whichButton) {dismissDialog(ORDER_DIALOG);
pd =ProgressDialog.show(FoodoMenu.this, "Sending...", "Sending order");
Thread thread = new Thread( newRunnable(){
public void run(){FoodoApp app =
((FoodoApp)FoodoMenu.this.getApplicationContext());String api_key =
app.getUserManager().getApiKey();try {
app.getService().submitOrder(mRowId,
api_key,
mOrder);
//FoodoMenu.this.startService(new Intent(FoodoMenu.this,FoodoOrderService.class));
} catch(FoodoServiceException e) {
Log.d(TAG,"Not able to send order", e);
Toast.makeText(FoodoMenu.this, "Order could not be processed! Please tryagain", Toast.LENGTH_LONG).show();
}handler.sendEmptyMessage(SENDORDER);
}});thread.start();
Log.d(TAG,"rur stopp");}
-
8/4/2019 Restarant Source Code
10/31
}).create();
default:return null;
}}@Overrideprotected void onListItemClick(ListView l, View v, int position, long
id) {super.onListItemClick(l, v, position, id);item = position;amount = 0;
dialogItem = mMenu.get(item).get(ITEMNAME);Log.i(TAG, dialogItem);
for(int i = 0; i < mOrder.size(); i++){if(Integer.parseInt(mOrder.get(i).get(ID)) == item){
amount =Integer.parseInt(mOrder.get(i).get(AMOUNT));
break;}
}txtItemCounter = (TextView)
itemLayout.findViewById(R.id.itemCounter);txtItemCounter.setText(Integer.toString(amount));
showDialog(MENU_DIALOG);}
private void loadMenu() {pd = ProgressDialog.show(FoodoMenu.this, "Loading..",
"Getting menu");Thread thread = new Thread( new Runnable(){
public void run(){try {
JSONArray jMenu =((FoodoApp)getApplicationContext()).getService().getRestaurantMenu(mRowId);
int n = jMenu.length();
for (int i = 0; i < n; i++){
JSONObject r =jMenu.getJSONObject(i);
Map map = newHashMap();
map.put(ID,
Integer.toString(i));map.put(ITEMID,
r.getString("id"));map.put(ITEMNAME,
r.getString("name"));map.put(PRICE,
r.getString("price"));map.put(SELECTED, "");mMenu.add(map);
}
-
8/4/2019 Restarant Source Code
11/31
}catch (JSONException e) {
//TODOLog.d(TAG, "Menu", e);
}catch (FoodoServiceException e){
Log.d(TAG, "Exception while gettingmenu", e);
}
handler.sendEmptyMessage(GETMENU);
}});thread.start();
}
private final Handler handler = new Handler() {@Override
public void handleMessage(Message msg) {if(msg.what == GETMENU){
setupList();pd.dismiss();
}else if(msg.what == SENDORDER){
pd.dismiss();setResult(RESULT_OK);finish();
}}
};
}
FoodoOrder.java
-
8/4/2019 Restarant Source Code
12/31
package is.hi.foodo;
import is.hi.foodo.net.FoodoServiceException;
import org.json.JSONArray;import org.json.JSONObject;
import android.app.Activity;import android.app.NotificationManager;import android.app.ProgressDialog;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.util.Log;import android.widget.TextView;
public class FoodoOrder extends Activity implements Runnable {
private static final String TAG = "FoodoOrder";
public static final String ORDER_ID = "ORDER_ID";
private Long order_id;private ProgressDialog pd;
private JSONObject order;
@Overrideprotected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);setContentView(R.layout.foodoorder);
order_id = (savedInstanceState != null ?savedInstanceState.getLong(ORDER_ID) : null);
if (order_id == null){
Bundle extras = getIntent().getExtras();order_id = extras != null ? extras.getLong(ORDER_ID) :
null;}
NotificationManager nManager =(NotificationManager)this.getSystemService(NOTIFICATION_SERVICE);
nManager.cancel(FoodoOrderService.FOODO_NOTIFICATION_ID);
pd = ProgressDialog.show(FoodoOrder.this, "Working..","Loading order");
Thread thread = new Thread(FoodoOrder.this);thread.run();
}
private void populateView() {if (order != null){
Log.d(TAG, "We haz order: " + order.toString());TextView orderline_view = (TextView)
this.findViewById(R.id.listOrder);
-
8/4/2019 Restarant Source Code
13/31
try {String orderline_str = "";JSONArray orderlines =
order.getJSONArray("orderlines");for (int i = 0; i < orderlines.length(); i++){
JSONObject line =orderlines.getJSONObject(i);
orderline_str =line.getString("menuitem") +line.getInt("count") + " x " +
line.getInt("price") +" = " + line.getInt("count") *
line.getInt("price") +"\n";
}orderline_str += "--------------------\n";orderline_str += "Total Price: " +
order.getInt("totalprice");
orderline_view.setText(orderline_str);}catch (Exception e){
Log.d(TAG, "Failure", e);}
}}
@Overridepublic void run() {
// TODO Auto-generated method stubtry {
FoodoApp app = (FoodoApp)this.getApplicationContext();order = app.getService().getOrder(order_id,
app.getUserManager().getApiKey());} catch (FoodoServiceException e) {
Log.d(TAG, "Exception", e);}handler.sendEmptyMessage(0);
}
private final Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {
pd.dismiss();populateView();
}};
FoodoOrderService.java
-
8/4/2019 Restarant Source Code
14/31
package is.hi.foodo;
import java.util.Timer;import java.util.TimerTask;
import org.json.JSONArray;import org.json.JSONObject;
import android.app.Notification;import android.app.NotificationManager;import android.app.PendingIntent;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;
public class FoodoOrderService extends Service {
public final static String TAG = "FoodoOrderService";
public final static int FOODO_NOTIFICATION_ID = 314159265;
private final Timer timer = new Timer();private final static int INTERVAL = 60000; //milliseconds
private NotificationManager mNotificationManager;private FoodoApp app;
@Overridepublic IBinder onBind(Intent arg0) {
return null;
}
@Overridepublic void onCreate() {
super.onCreate();Log.d(TAG, "Staring Service");mNotificationManager =
(NotificationManager)this.getSystemService(NOTIFICATION_SERVICE);timer.scheduleAtFixedRate(task, 0, INTERVAL);app = ((FoodoApp)this.getApplicationContext());
}
@Overridepublic void onDestroy() {
super.onDestroy();if (timer != null) {
timer.cancel();}
}
public void makeNotification(String restaurantName, long orderId) {Log.d(TAG, "Creating notification: " + restaurantName + ",
order: " + orderId);
-
8/4/2019 Restarant Source Code
15/31
Intent intent = new Intent(this, FoodoOrder.class);intent.putExtra(FoodoOrder.ORDER_ID, orderId);
Notification notification = new Notification(R.drawable.icon,"Your Foodo order!", System.currentTimeMillis());
notification.setLatestEventInfo(FoodoOrderService.this,"Foodo",restaurantName + " order confirmed!",
PendingIntent.getActivity(this.getBaseContext(), 0, intent,PendingIntent.FLAG_CANCEL_CURRENT)
);mNotificationManager.notify(FOODO_NOTIFICATION_ID,
notification);}
public void cancelNotification() {mNotificationManager.cancel(FOODO_NOTIFICATION_ID);
}
private final TimerTask task = new TimerTask() {@Overridepublic void run() {
String api_key = app.getUserManager().getApiKey();try {
JSONArray notifications =app.getService().getNotifications(api_key);
Log.d(TAG, notifications.toString());int n = notifications.length();if (n > 0){
for (int i = 0; i < n; i++){
JSONObject not =notifications.getJSONObject(i);
Log.d(TAG, not.toString());makeNotification(not.getString("restaurant"), not.getLong("order_id"));
}}
} catch (Exception e) {// TODO Auto-generated catch blockLog.d(TAG, "Exception in FoodoOrderService",
e);}
}
};}
FoodoService.java
package is.hi.foodo.net;
-
8/4/2019 Restarant Source Code
16/31
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* Service interface for communication with a Foodo web service.
* @author siggijons
*
*/
public interface FoodoService {
/**
* Get all available restaurants
* @throws FoodoServiceException
*/
public JSONArray getRestaurants() throws FoodoServiceException;
/**
*
* @param lat latitude
* @param lon longitude
* @param distance_km Distance in kilometers
* @return Array of restaurants within distance_km of lat, lon
* @throws FoodoServiceException
*/
public JSONArray getNearByRestaurants(double lat, double lon, int distance_km) throws
FoodoServiceException;
/**
* Get restaurant details
* @throws FoodoServiceException
*/
public JSONObject getRestaurantDetails(long restaurant_id) throws
FoodoServiceException;
/**
* Get restaurant reviews
* @throws FoodoServiceException
*/
public JSONArray getRestaurantReviews(long restaurant_id) throws
-
8/4/2019 Restarant Source Code
17/31
FoodoServiceException;
/**
* Get restaurant menu
* @throws FoodoServiceException
*/
public JSONArray getRestaurantMenu(long restaurant_id) throws FoodoServiceException;
/**
* Submit rating for a restaurant
* @throws FoodoServiceException
*/
public JSONObject submitRating(long restaurant_id, String apikey, int rating) throws
FoodoServiceException;
/*** Submit review for restaurant
*/
public JSONArray submitReview(long restaurant_id, String apikey, String review) throwsFoodoServiceException;
/**
* Register new user
* @throws FoodoServiceException
*/
public JSONObject registerUser(String email, String password, String firstName, StringlastName) throws FoodoServiceException;
/**
* Edits the name, email of an old user
* @throws FoodoServiceException
*/
public JSONObject editUser(String apikey, String password, String newEmail, String
newFirstName, String newLastName) throws FoodoServiceException;
/*** Edits the password of an old user
* @throws FoodoServiceException
*/
public JSONObject editPassword(String apikey, String currentPassword, String
newPassword) throws FoodoServiceException;
-
8/4/2019 Restarant Source Code
18/31
/**
* Login user
* @throws FoodoServiceException
*/
public JSONObject loginUser(String email, String password) throws
FoodoServiceException;
/**
* Returns all the users orders.
* @param apikey
* @return JSONArray
* @throws FoodoServiceException
*/
public JSONArray getUserOrders(String apikey) throws FoodoServiceException;
/*** Returns all the user information.
* @param apikey
* @return JSONObject
* @throws FoodoServiceException
*/
public JSONObject getUserInfo(String apikey) throws FoodoServiceException;
/**
* Get all available restaurant types
** @return List of types
* @throws FoodoServiceException
*/
public JSONArray getTypes() throws FoodoServiceException;
/**
* Submits an order
*
* @param restaurant_id
* @param api_key* @param items
* @return
* @throws FoodoServiceException
*/
public JSONObject submitOrder(long restaurant_id, String api_key,
List items) throws FoodoServiceException;
-
8/4/2019 Restarant Source Code
19/31
/**
* Get user reviews
* @throws FoodoServiceException
*/
public JSONArray getUserReviews(String apikey) throws FoodoServiceException;
/**
* Edit user reviews
* @throws FoodoServiceException
*/
public JSONArray editUserReview(long restaurantId, long reviewId, String apikey, String
review) throws FoodoServiceException;
/**
* Get user notifications* @return
*/
public JSONArray getNotifications(String apiKey) throws FoodoServiceException;
/**
* Deletes a user review
* @throws FoodoServiceException
*/
public JSONArray deleteUserReview(long reviewId, String apikey) throws
FoodoServiceException;
public JSONObject getOrder(Long orderId, String apikey) throws FoodoServiceException;
}
-
8/4/2019 Restarant Source Code
20/31
WebService.java
package is.hi.foodo.net;
import is.hi.foodo.FoodoMenu;
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.util.ArrayList;
import java.util.List;import java.util.Map;
import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;
import android.util.Log;
public class WebService implements FoodoService {
private static final String TAG = "WebService";private final String url;
public WebService(String url) {this.url = url;
}
private String streamToString(InputStream is) {BufferedReader reader = new BufferedReader( new
InputStreamReader(is));StringBuilder builder = new StringBuilder();String line;
try {while (( line = reader.readLine()) != null){
builder.append(line);
-
8/4/2019 Restarant Source Code
21/31
}return builder.toString();
}catch (IOException e) {
Log.d(TAG, "Error while converting input stream tostring");
e.printStackTrace();}finally {
try {is.close();
}catch (IOException e) {}
}//Log.d(TAG, builder.toString());return builder.toString();
}
private JSONObject post(String path, List data) throwsFoodoServiceException {
HttpClient httpclient = new DefaultHttpClient();HttpPost httppost = new HttpPost(this.url + path);
//Log.d(TAG, "Post request at: " + this.url + path);
try {//Add datahttppost.setEntity(new UrlEncodedFormEntity(data));
//Execute HTTP Post RequestHttpResponse response = httpclient.execute(httppost);HttpEntity entity = response.getEntity();
JSONObject result = newJSONObject(streamToString(entity.getContent()));
if (result.getInt("responseCode") == 200) {return result.getJSONObject("responseData");
}else {
throw newFoodoServiceException(result.getString("errorMessage"));
}}catch (JSONException e) {
Log.d(TAG, "There was a JSON exception", e);}catch (IOException e) {
Log.e(TAG, "There was an IO Stream related error",e);
}
return null;}
private JSONObject get(String path) throws FoodoServiceException {HttpClient httpclient = new DefaultHttpClient();HttpGet httpget = new HttpGet(this.url + path);
-
8/4/2019 Restarant Source Code
22/31
//Log.d(TAG, "Get request at: " + this.url + path);
try {//Execute HTTP Get RequestHttpResponse response = httpclient.execute(httpget);HttpEntity entity = response.getEntity();
JSONObject result = newJSONObject(streamToString(entity.getContent()));
if (result.getInt("responseCode") == 200) {return result.getJSONObject("responseData");
}else {
throw newFoodoServiceException(result.getString("errorMessage"));
}}catch (JSONException e) {
Log.d(TAG, "There was a JSON exception", e);}catch (IOException e) {
Log.e(TAG, "There was an IO Stream related error",e);
}
return null;}
@Overridepublic JSONArray getRestaurants() throws FoodoServiceException {
try {JSONObject o = this.get("/restaurants/");return o.getJSONArray("Restaurants");
} catch (FoodoServiceException e) {throw e;
} catch (Exception e) {Log.d(TAG, "Exception", e);throw new FoodoServiceException("Error while fetching
restaurants");}
}
@Overridepublic JSONArray getNearByRestaurants(double lat, double lon, int
distanceKm)throws FoodoServiceException {
try {Log.d(TAG, "Loading from: " + lat + ", " + lon + ",
km: " + distanceKm);JSONObject o = this.get("/restaurants/near/" + lat +
"/" + lon + "/" + distanceKm);return o.getJSONArray("Restaurants");
} catch (FoodoServiceException e) {throw e;
-
8/4/2019 Restarant Source Code
23/31
} catch (Exception e) {Log.d(TAG, "Exception", e);throw new FoodoServiceException("Error while fetching
restaurants");}
}
@Overridepublic JSONObject getRestaurantDetails(long restaurantId) throws
FoodoServiceException {try {
return this.get("/restaurants/" + restaurantId +"/").getJSONArray("Restaurants").getJSONObject(0);
} catch (FoodoServiceException e) {throw e;
} catch (Exception e) {Log.d(TAG, "Exception in details", e);throw new FoodoServiceException("Error while fetching
details");}
}
@Overridepublic JSONArray getRestaurantMenu(long restaurantId) throws
FoodoServiceException {try {
return this.get("/restaurants/" + restaurantId +"/menu/").getJSONArray("Menu");
} catch (FoodoServiceException e) {throw e;
} catch (Exception e) {Log.d(TAG, "Exception in menu", e);throw new FoodoServiceException("Error while fetching
menu");}
}
@Overridepublic JSONArray getRestaurantReviews(long restaurantId) throws
FoodoServiceException {try {
return this.get("/restaurants/" + restaurantId +"/reviews/").getJSONArray("Reviews");
} catch (FoodoServiceException e) {throw e;
} catch (Exception e) {Log.d(TAG, "Exception in reviews", e);
throw new FoodoServiceException("Error while fetchingreviews");
}}
@Overridepublic JSONObject loginUser(String email, String password) throws
FoodoServiceException {//Create list for request parametersList nameValuePairs = new
-
8/4/2019 Restarant Source Code
24/31
ArrayList(2);nameValuePairs.add(new BasicNameValuePair("email", email));nameValuePairs.add(new BasicNameValuePair("password",
password));
try {return this.post("/users/login/",
nameValuePairs).getJSONObject("User");} catch (FoodoServiceException e) {
throw e;} catch (Exception e) {
Log.d(TAG, "Exception in login", e);throw new FoodoServiceException("Error while logging
in");}
}
@Overridepublic JSONObject registerUser(String email, String password,
String firstName, String lastName) throws
FoodoServiceException {
List nameValuePairs = newArrayList(2);
nameValuePairs.add(new BasicNameValuePair("email", email));nameValuePairs.add(new BasicNameValuePair("password",
password));nameValuePairs.add(new BasicNameValuePair("firstname",
firstName));nameValuePairs.add(new BasicNameValuePair("lastname",
lastName));
try {return this.post("/users/signup/",
nameValuePairs).getJSONObject("User");} catch (FoodoServiceException e) {
throw e;} catch (Exception e) {
Log.d(TAG, "Exception in register", e);throw new FoodoServiceException("Error while
registering user");}
}
@Overridepublic JSONObject getUserInfo(String apikey) throws
FoodoServiceException {
//Create list for request parametersList nameValuePairs = new
ArrayList(2);nameValuePairs.add(new BasicNameValuePair("apikey", apikey));
try {return this.post("/users/info/",
nameValuePairs).getJSONObject("User");} catch (FoodoServiceException e) {
throw e;
-
8/4/2019 Restarant Source Code
25/31
} catch (Exception e) {Log.d(TAG, "Exception in login", e);throw new FoodoServiceException("Error while logging
in");}
}
@Overridepublic JSONObject editUser(String apikey, String password, String
newEmail,String newFirstName, String newLastName)
throws FoodoServiceException {Log.d(TAG, "In edtir user!");List nameValuePairs = new
ArrayList(2);nameValuePairs.add(new BasicNameValuePair("apikey", apikey));
nameValuePairs.add(new BasicNameValuePair("password",password));
nameValuePairs.add(new BasicNameValuePair("newemail",newEmail));
nameValuePairs.add(new BasicNameValuePair("newfirstname",newFirstName));
nameValuePairs.add(new BasicNameValuePair("newlastname",newLastName));
try {Log.d(TAG, "Still in editr user!, going to
post"); //Something fails here need to check itreturn this.post("/users/edit/userinfo/",
nameValuePairs).getJSONObject("User");} catch (FoodoServiceException e) {
throw e;} catch (Exception e) {
Log.d(TAG, "Exception in register", e);throw new FoodoServiceException("Error while
registering user");}
}
@Overridepublic JSONObject editPassword(String apikey, String currentPassword,
String newPassword) throws FoodoServiceException {List nameValuePairs = new
ArrayList(2);nameValuePairs.add(new BasicNameValuePair("apikey", apikey));
nameValuePairs.add(new BasicNameValuePair("password",currentPassword));
nameValuePairs.add(new BasicNameValuePair("newpassword",newPassword));
try {return this.post("/users/edit/password/",
nameValuePairs).getJSONObject("User");} catch (FoodoServiceException e) {
-
8/4/2019 Restarant Source Code
26/31
throw e;} catch (Exception e) {
Log.d(TAG, "Exception in register", e);throw new FoodoServiceException("Error while
registering user");}
}
@Overridepublic JSONArray getUserOrders(String apikey) throws
FoodoServiceException {try {
return this.get("/users/orders/" + apikey +"/").getJSONArray("Orders");
} catch (FoodoServiceException e) {throw e;
} catch (Exception e) {Log.d(TAG, "Exception in register", e);throw new FoodoServiceException("Error while
registering user");
}}
@Overridepublic JSONObject submitRating(long restaurantId, String apikey, int
rating) throws FoodoServiceException {try {
return this.get("/restaurants/" + restaurantId +"/rate/" + rating + "/" +apikey).getJSONArray("Restaurants").getJSONObject(0);
}catch (FoodoServiceException e) {
throw e;} catch (Exception e) {
Log.d(TAG, "Exception in submitRating", e);throw new FoodoServiceException("Unexcepted error
while submitting rating");}
}
@Overridepublic JSONArray submitReview(long restaurantId, String apikey,
String review) throws FoodoServiceException {List nameValuePairs = new
ArrayList(2);nameValuePairs.add(new BasicNameValuePair("review", review));
try {return this.post("/restaurants/" + restaurantId +
"/reviews/create/" + apikey + "/", nameValuePairs).getJSONArray("Reviews");} catch (FoodoServiceException e) {
throw e;} catch (Exception e) {
Log.d(TAG, "Exception in submitReview", e);throw new FoodoServiceException("Unexpected error
while submitting review");
-
8/4/2019 Restarant Source Code
27/31
}}
public JSONArray getTypes() throws FoodoServiceException {
try {return this.get("/types/").getJSONArray("Types");
}catch (FoodoServiceException e) {
throw e;}catch (Exception e) {
Log.d(TAG, "Exception in getTypes", e);throw new FoodoServiceException("Unexpected error
while fetching restaurant types");}
}
@Overridepublic JSONObject submitOrder(long restaurantId, String apiKey,
List items) throwsFoodoServiceException {
//Prepare JSON objectJSONArray order = new JSONArray();try {
for (int i = 0; i < items.size(); i++){
JSONObject item = new JSONObject();item.put("id",
items.get(i).get(FoodoMenu.ITEMID));item.put("amount",
items.get(i).get(FoodoMenu.AMOUNT));order.put(item);
}} catch (JSONException e) {
// TODO Auto-generated catch blocke.printStackTrace();
}Log.d(TAG, "Order is: " + order.toString());
//Prepare parameters for post requestList nameValuePairs = new
ArrayList(2);nameValuePairs.add(new BasicNameValuePair("order",
order.toString()));
nameValuePairs.add(new BasicNameValuePair("restaurant_id",String.valueOf(restaurantId)));
nameValuePairs.add(new BasicNameValuePair("apikey", apiKey));
try {return this.post("/order/",
nameValuePairs).getJSONObject("Order");} catch (FoodoServiceException e) {
throw e;} catch (Exception e) {
-
8/4/2019 Restarant Source Code
28/31
Log.d(TAG, "Exception in order", e);throw new FoodoServiceException("Error while sending
out order");}
}
public JSONArray getUserReviews(String apikey) throwsFoodoServiceException
{try {
return this.get("/users/reviews/" + apikey +"/").getJSONArray("Reviews");
} catch (FoodoServiceException e) {throw e;
} catch (Exception e) {Log.d(TAG, "Exception in reviews", e);throw new FoodoServiceException("Error while fetching
reviews");}
}
public JSONArray editUserReview(long restaurantId, long reviewId,String apikey, String review) throws FoodoServiceException
{List nameValuePairs = new
ArrayList(2);nameValuePairs.add(new BasicNameValuePair("editreview",
review));nameValuePairs.add(new BasicNameValuePair("apikey", apikey));
nameValuePairs.add(new BasicNameValuePair("restaurant_id",Long.toString(restaurantId)));
nameValuePairs.add(new BasicNameValuePair("review_id",Long.toString(reviewId)));
try {return this.post("/users/edit/review/",
nameValuePairs).getJSONArray("Reviews");
} catch (FoodoServiceException e) {throw e;
} catch (Exception e) {Log.d(TAG, "Exception in editing reviews", e);throw new FoodoServiceException("Error while editing
reviews");
}
}
@Overridepublic JSONArray getNotifications(String apikey) throws
FoodoServiceException {List nameValuePairs = new
ArrayList(2);nameValuePairs.add(new BasicNameValuePair("apikey", apikey));
-
8/4/2019 Restarant Source Code
29/31
try {
return this.post("/users/notifications/",nameValuePairs).getJSONArray("Notifications");
} catch (JSONException e) {throw new FoodoServiceException("Error getting
notifications");}
}
public JSONArray deleteUserReview(long reviewId, String apikey)throws FoodoServiceException{
List nameValuePairs = newArrayList(2);
nameValuePairs.add(new BasicNameValuePair("apikey", apikey));nameValuePairs.add(new BasicNameValuePair("review_id",
Long.toString(reviewId)));try {
return this.post("/users/delete/review/",nameValuePairs).getJSONArray("Reviews");
} catch (FoodoServiceException e) {throw e;
} catch (Exception e) {Log.d(TAG, "Exception in reviews", e);throw new FoodoServiceException("Error while deleting
review");}
}
@Overridepublic JSONObject getOrder(Long orderId, String apikey) throws
FoodoServiceException {List nameValuePairs = new
ArrayList(2);nameValuePairs.add(new BasicNameValuePair("apikey", apikey));
try {return this.post("/users/orderstatus/" + orderId +
"/", nameValuePairs).getJSONObject("Order");} catch (JSONException e) {
throw new FoodoServiceException("Error loadingorder");
}}
}
-
8/4/2019 Restarant Source Code
30/31
foodoorder.xml
-
8/4/2019 Restarant Source Code
31/31
android:padding="5px"
android:textSize="20dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Status:"
android:layout_alignParentBottom="true"/>