From ac20e1c5ed24193b8ec6b201a02648737b0f7a14 Mon Sep 17 00:00:00 2001 From: John Palmer Date: Tue, 14 Oct 2014 01:52:25 +0200 Subject: [PATCH] almost finished for beta testing --- SUDEAU/AndroidManifest.xml | 6 +- .../interactive_image_activity_heatmap.xml | 5 +- .../sudeau/ChooseItineraryActivity.java | 180 ---------------- .../sudeau/DetailItineraryActivity.java | 52 +++-- .../movelab/sudeau/EditHighLightActivity.java | 2 +- .../net/movelab/sudeau/EditRouteActivity.java | 6 +- .../InteractiveImageActivityHeatMap.java | 11 +- .../movelab/sudeau/MyItinerariesActivity.java | 16 +- .../net/movelab/sudeau/PropertyHolder.java | 21 +- .../src/net/movelab/sudeau/Switchboard.java | 192 +++++++++++++++--- SUDEAU/src/net/movelab/sudeau/Util.java | 31 +-- .../sudeau/database/DataBaseHelper.java | 2 +- .../sudeau/database/DataContainer.java | 21 +- .../src/net/movelab/sudeau/model/Route.java | 5 + 14 files changed, 274 insertions(+), 276 deletions(-) diff --git a/SUDEAU/AndroidManifest.xml b/SUDEAU/AndroidManifest.xml index 5e4ef51..fe614f9 100644 --- a/SUDEAU/AndroidManifest.xml +++ b/SUDEAU/AndroidManifest.xml @@ -1,9 +1,9 @@ + android:versionName="1.03" > + android:value="@string/maps_api_key_debugging" /> + android:layout_height="fill_parent"> + android:layout_height="wrap_content"> { - - @Override - protected void onPreExecute() { - super.onPreExecute(); - showDialog(DIALOG_DOWNLOAD_PROGRESS); - } - - @Override - protected String doInBackground(String... aurl) { - int count; - - try { - - URL url = new URL(aurl[0]); - Log.d("ANDRO_ASYNC", "uRL: " + url.toString()); - - HttpURLConnection conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("GET"); - conn.setDoOutput(true); - conn.connect(); - - int lenghtOfFile = conn.getContentLength(); - Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile); - - Log.d("ANDRO_ASYNC", "SD path: " + Environment.getExternalStorageDirectory().getPath()); - - File destinationFile = new File(Environment.getExternalStorageDirectory().getPath(), Util.baseFolder + "/route.zip"); - String destinationPath = destinationFile.getPath(); - Log.d("ANDRO_ASYNC", "Save path: " + destinationPath); - - InputStream input = new BufferedInputStream(url.openStream()); - OutputStream output = new FileOutputStream(destinationPath); - - byte data[] = new byte[1024]; - - long total = 0; - - while ((count = input.read(data)) != -1) { - total += count; - publishProgress(""+(int)((total*90)/lenghtOfFile)); - output.write(data, 0, count); - } - - output.flush(); - output.close(); - input.close(); - - - // NOW UNZIP IT - ZipFile thisZipfile = new ZipFile(destinationPath); - int nEntries = thisZipfile.size(); - int zipCounter = 0; - - String zipFilePath = destinationPath; - Log.d("ANDRO_ASYNC", "read path: " + destinationPath); -// TODO take out hard coded route 7 - File target_directory = new File(Environment.getExternalStorageDirectory().getPath(), Util.baseFolder + "/" + Util.routeMediaFolder + "/route_7"); - String destDirectory = target_directory.getPath(); - Log.d("ANDRO_ASYNC", "Save path: " + destDirectory); - - UnzipUtility unzipper = new UnzipUtility(); - try { -// unzipper.unzip(zipFilePath, destDirectory); -// publishProgress(""+100); - - final int BUFFER_SIZE = 4096; - - File destDir = new File(destDirectory); - if (!destDir.exists()) { - destDir.mkdirs(); - } - ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath)); - ZipEntry entry = zipIn.getNextEntry(); - // iterates over entries in the zip file - while (entry != null) { - String filePath = destDirectory + File.separator + entry.getName(); - if (!entry.isDirectory()) { - // if the entry is a file, extracts it -// extractFile(zipIn, filePath); - - File f = new File(filePath); - File dir = new File(f.getParent()); - dir.mkdirs(); - BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath)); - byte[] bytesIn = new byte[BUFFER_SIZE]; - int read = 0; - while ((read = zipIn.read(bytesIn)) != -1) { - bos.write(bytesIn, 0, read); - - } - bos.close(); - - - } else { - // if the entry is a directory, make the directory - File dir = new File(filePath); - dir.mkdirs(); - } - - publishProgress(""+(int)(90+ ((++zipCounter*10)/nEntries))); - - zipIn.closeEntry(); - entry = zipIn.getNextEntry(); - } - zipIn.close(); - - - - mPreferences.edit().putBoolean("r7d", true).apply(); - r7downloaded = true; - - } catch (Exception ex) { - // some errors occurred - ex.printStackTrace(); - } - - } catch (Exception e) {} - - - return null; - - } - protected void onProgressUpdate(String... progress) { - mProgressDialog.setProgress(Integer.parseInt(progress[0])); - } - - @Override - protected void onPostExecute(String unused) { - dismissDialog(DIALOG_DOWNLOAD_PROGRESS); - showItineraryOptions(); - } - } } diff --git a/SUDEAU/src/net/movelab/sudeau/DetailItineraryActivity.java b/SUDEAU/src/net/movelab/sudeau/DetailItineraryActivity.java index 62529c5..f3a955c 100644 --- a/SUDEAU/src/net/movelab/sudeau/DetailItineraryActivity.java +++ b/SUDEAU/src/net/movelab/sudeau/DetailItineraryActivity.java @@ -10,6 +10,7 @@ import org.json.JSONException; import org.json.JSONObject; +import net.movelab.sudeau.database.DataBaseHelper; import net.movelab.sudeau.database.DataContainer; import net.movelab.sudeau.model.FileManifest; import net.movelab.sudeau.model.HighLight; @@ -41,6 +42,7 @@ import android.provider.Settings; import android.util.DisplayMetrics; import android.util.Log; +import android.util.Property; import android.view.Display; import android.view.Gravity; import android.view.Menu; @@ -417,7 +419,7 @@ private void saveHighLight(HighLight h) { Log.d("saveHighLight", "Step id not found " + stepBeingEditedId); } else { DataContainer.addHighLightToStep(s, h, - DataContainer.getAndroidId(getContentResolver()), + PropertyHolder.getUserId(), app.getDataBaseHelper()); } } @@ -767,7 +769,7 @@ private void setUpRoutes() { .getId() : null; routeInProgress = DataContainer.createEmptyRoute(locale, app.getDataBaseHelper(), - DataContainer.getAndroidId(getContentResolver()), + PropertyHolder.getUserId(), idRouteBasedOn); } } @@ -892,6 +894,7 @@ public void onInfoWindowClick(Marker marker) { DetailHighLightActivity.class); i.putExtra("step_j", s_j_string); if(s!=null){ + DataBaseHelper. i.putExtra("route_id", s.getTrack().getRoute().getId()); } if(h!=null){ @@ -1554,39 +1557,32 @@ private void refreshDecorations(List steps) { } private MapBoxOfflineTileProvider initTileProvider() { - // File sdcard = Environment.getExternalStorageDirectory(); - File sdcard = new File(Environment.getExternalStorageDirectory(), - Util.baseFolder + "/" + Util.routeMapsFolder); - if (selectedRoute.getLocalCarto() != null) { - File f = new File(sdcard, selectedRoute.getLocalCarto()); + String mapPath = selectedRoute.getLocalCarto(); + if (mapPath != null && !mapPath.isEmpty()) { + File f = new File(mapPath); Log.e("CARTO", f.getPath()); - - // File f = new File(getCacheDir() + - // "/OSMPublicTransport_HiRes.mbtiles"); if (f.exists()) { Log.e("CARTO EXISTS", f.getPath()); - - // try { - // InputStream is = getAssets().open( - // "OSMPublicTransport_HiRes.mbtiles"); - // FileInputStream is = new FileInputStream(f); - // int size = is.available(); - // byte[] buffer = new byte[size]; - // is.read(buffer); - // is.close(); - // FileOutputStream fos = new FileOutputStream(f); - // fos.write(buffer); - // fos.close(); - // } catch (Exception e) { - // throw new RuntimeException(e); - // } - return new MapBoxOfflineTileProvider(f.getPath()); + return new MapBoxOfflineTileProvider(f.getPath()); } else { Log.d(TAG, "Fitxer cartografia no trobat " + f.getAbsolutePath()); } } - return null; + // If not returned by now, try the general map path instead + mapPath = PropertyHolder.getGeneralMapPath(); + if (mapPath != null && !mapPath.isEmpty()) { + File f = new File(mapPath); + Log.e("CARTO", f.getPath()); + if (f.exists()) { + Log.e("CARTO EXISTS", f.getPath()); + return new MapBoxOfflineTileProvider(f.getPath()); + } else { + Log.d(TAG, + "Fitxer cartografia no trobat " + f.getAbsolutePath()); + } + } + return null; } public class FixReceiver extends BroadcastReceiver { @@ -1768,7 +1764,7 @@ public void onReceive(Context context, Intent intent) { int order = stepsInProgress.size(); s.setOrder(order); DataContainer.addStepToTrack(s, routeInProgress.getTrack(), - DataContainer.getAndroidId(getContentResolver()), + PropertyHolder.getUserId(), app.getDataBaseHelper()); } Log.d("onReceive", "Received new location " + lat + " " + lng diff --git a/SUDEAU/src/net/movelab/sudeau/EditHighLightActivity.java b/SUDEAU/src/net/movelab/sudeau/EditHighLightActivity.java index c3763e1..99c9aa3 100644 --- a/SUDEAU/src/net/movelab/sudeau/EditHighLightActivity.java +++ b/SUDEAU/src/net/movelab/sudeau/EditHighLightActivity.java @@ -72,11 +72,11 @@ protected void onCreate(Bundle savedInstanceState) { app = (EruletApp) getApplicationContext(); } + // To stop keyboard from popping up immediately and blocking everything this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); setContentView(R.layout.highlight_activity); - setUpInterface(); Bundle extras = getIntent().getExtras(); if (extras != null) { diff --git a/SUDEAU/src/net/movelab/sudeau/EditRouteActivity.java b/SUDEAU/src/net/movelab/sudeau/EditRouteActivity.java index 2a49d5b..af7a179 100644 --- a/SUDEAU/src/net/movelab/sudeau/EditRouteActivity.java +++ b/SUDEAU/src/net/movelab/sudeau/EditRouteActivity.java @@ -83,7 +83,7 @@ public void onBackPressed() { @Override public void onClick(DialogInterface dialog, int which) { - save(DataContainer.getAndroidId(getContentResolver())); + save(PropertyHolder.getUserId()); Intent returnIntent = new Intent(); setResult(RESULT_OK, returnIntent); finish(); @@ -103,7 +103,7 @@ public void onClick(DialogInterface dialog, } } - private String save(String android_id) { + private String save(String userId) { editedRoute.setName(locale, routeName.getText().toString()); editedRoute.setDescription(locale, routeDescription.getText().toString()); DataContainer.editRoute(editedRoute, app.getDataBaseHelper()); @@ -209,7 +209,7 @@ public void afterTextChanged(Editable s) { btn_save.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (changed) { - save(DataContainer.getAndroidId(getContentResolver())); + save(PropertyHolder.getUserId()); Intent returnIntent = new Intent(); setResult(RESULT_OK, returnIntent); finish(); diff --git a/SUDEAU/src/net/movelab/sudeau/InteractiveImageActivityHeatMap.java b/SUDEAU/src/net/movelab/sudeau/InteractiveImageActivityHeatMap.java index e3de66b..d6914e7 100644 --- a/SUDEAU/src/net/movelab/sudeau/InteractiveImageActivityHeatMap.java +++ b/SUDEAU/src/net/movelab/sudeau/InteractiveImageActivityHeatMap.java @@ -63,9 +63,12 @@ protected void onCreate(Bundle savedInstanceState) { int[] screenSize = Util.getScreenSize(getBaseContext()); originalHeight = interactiveImage.getOriginalHeight(); originalWidth = interactiveImage.getOriginalWidth(); - scaledHeight = screenSize[1]; + int downloadedWidth = 2*Util.getLargestScreenDimension(getApplicationContext()); // this is by definition of what I have on server + int downloadedHeight = (int) (downloadedWidth * originalHeight)/originalWidth; + // to avoid images that are to large and cause memory problems, I am doing the following: Scaled height will be the minimum of the actual downloaded height and the phone's smallest screen dimension. So if landscape, image is usually full height. But in portrait it is not (since otherwise it becomes huge in portrait). + scaledHeight = Math.min(downloadedHeight, Math.min(screenSize[1], screenSize[0])); scaledWidth = Util.getScaledImageWidth(originalWidth, originalHeight, (float)scaledHeight); - image.setImageBitmap( Bitmap.createScaledBitmap(BitmapFactory.decodeFile(f.getAbsolutePath()), scaledWidth, scaledHeight, false) ); + image.setImageBitmap( Bitmap.createScaledBitmap(BitmapFactory.decodeFile(f.getAbsolutePath()), scaledWidth, scaledHeight, false) ); } } image.setOnTouchListener(this); @@ -102,6 +105,7 @@ public void showBubble(Box b){ dialog.setTitle( getString(R.string.info) ); dialog.setMessage( Html.fromHtml(b.getMessage()) ); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + dialog.setCanceledOnTouchOutside(true); WindowManager.LayoutParams wmlp = dialog.getWindow().getAttributes(); wmlp.gravity = Gravity.TOP | Gravity.LEFT; wmlp.x = 50; //x position @@ -109,7 +113,8 @@ public void showBubble(Box b){ dialog.show(); } - @Override + + @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub int x = (int) event.getX(); diff --git a/SUDEAU/src/net/movelab/sudeau/MyItinerariesActivity.java b/SUDEAU/src/net/movelab/sudeau/MyItinerariesActivity.java index 4669f8c..553187a 100644 --- a/SUDEAU/src/net/movelab/sudeau/MyItinerariesActivity.java +++ b/SUDEAU/src/net/movelab/sudeau/MyItinerariesActivity.java @@ -51,16 +51,16 @@ protected void onCreate(Bundle savedInstanceState) { locale = PropertyHolder.getLocale(); listView = (ListView) findViewById(R.id.lv_my_routes); - String android_id = DataContainer.getAndroidId(getBaseContext().getContentResolver()); - List myRoutes = loadRoutes(android_id); + String userId = PropertyHolder.getUserId(); + List myRoutes = loadRoutes(userId); routeArrayAdapter = new MyRouteArrayAdapter(this, locale, myRoutes,app); listView.setAdapter(routeArrayAdapter); } - private List loadRoutes(String android_id){ - List myRoutes = DataContainer.getUserRoutes(app.getDataBaseHelper(),android_id); + private List loadRoutes(String userId){ + List myRoutes = DataContainer.getUserRoutes(app.getDataBaseHelper(),userId); for(Route r : myRoutes){ DataContainer.refreshRoute(r, app.getDataBaseHelper()); if(r.getTrack()!=null) @@ -69,8 +69,8 @@ private List loadRoutes(String android_id){ return myRoutes; } - private void refreshListView(String android_id){ - List newRoutes = loadRoutes(android_id); + private void refreshListView(String userId){ + List newRoutes = loadRoutes(userId); routeArrayAdapter = new MyRouteArrayAdapter(this, locale, newRoutes,app); listView.setAdapter(routeArrayAdapter); } @@ -78,8 +78,8 @@ private void refreshListView(String android_id){ @Override protected void onResume() { super.onResume(); - String android_id = DataContainer.getAndroidId(getBaseContext().getContentResolver()); - refreshListView(android_id); + String userId = PropertyHolder.getUserId(); + refreshListView(userId); } } diff --git a/SUDEAU/src/net/movelab/sudeau/PropertyHolder.java b/SUDEAU/src/net/movelab/sudeau/PropertyHolder.java index 624d28a..ab2bd3d 100644 --- a/SUDEAU/src/net/movelab/sudeau/PropertyHolder.java +++ b/SUDEAU/src/net/movelab/sudeau/PropertyHolder.java @@ -21,6 +21,8 @@ public class PropertyHolder { public static final String SHARED_PREFERENCES_NAME = "PROPERTIES"; public static final String ALARM_INTERVAL = "ALARM_INTERVAL"; public static final String SERVICE_ON = "SERVICE_ON"; + public static final String IS_FIRST_TIME = "IS_FIRST_TIME"; + public static final String USER_KEY = "USER_KEY"; public static final String IS_REGISTERED = "IS_REGISTERED"; public static final String USER_ID = "USER_ID"; public static final String LAST_UPDATE_GENERAL_MAP = "LAST_UPDATE_GENERAL_MAP"; @@ -84,6 +86,15 @@ public static void setServiceOn(boolean _isOn) { editor.apply(); } + public static boolean isFirstTime() { + return sharedPreferences.getBoolean(IS_FIRST_TIME, true); + } + + public static void setFirstTime(boolean _isFirstTime) { + editor.putBoolean(IS_FIRST_TIME, _isFirstTime); + editor.apply(); + } + public static boolean isRegistered() { return sharedPreferences.getBoolean(IS_REGISTERED, false); } @@ -102,6 +113,15 @@ public static void setUserId(String _userId) { editor.apply(); } + public static String getUserKey() { + return sharedPreferences.getString(USER_KEY, null); + } + + public static void setUserKey(String _userKey) { + editor.putString(USER_KEY, _userKey); + editor.apply(); + } + public static String getGeneralMapPath() { return sharedPreferences.getString(GENERAL_MAP_PATH, null); @@ -153,7 +173,6 @@ public static void setLastUpdateGeneralReferencesNow(){ editor.apply(); } - public static String getLocale() { return sharedPreferences.getString(LOCALE, "oc"); } diff --git a/SUDEAU/src/net/movelab/sudeau/Switchboard.java b/SUDEAU/src/net/movelab/sudeau/Switchboard.java index 2c289f9..322453b 100644 --- a/SUDEAU/src/net/movelab/sudeau/Switchboard.java +++ b/SUDEAU/src/net/movelab/sudeau/Switchboard.java @@ -61,6 +61,7 @@ import java.net.URL; import java.util.ArrayList; import java.util.List; +import java.util.UUID; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; @@ -102,33 +103,25 @@ protected void onCreate(Bundle savedInstanceState) { } setContentView(R.layout.activity_switchboard); initButtons(); - //See if we need to display the user registration - mPreferences = getSharedPreferences("EruletPreferences", MODE_PRIVATE); - boolean firstTime = mPreferences.getBoolean("first_time", true); + if(!PropertyHolder.isInit()) + PropertyHolder.init(context); - //TODO take this out; for testing only - Util.forceNewDownloads(context, app); - // Util.forceNewMapDownloads(context, app); - - // TODO TEMP TESTING - mPreferences.edit().putBoolean("registered_user", false).apply(); - - startInitialSync(); - - // TODO Put this back in -- I have it out just for initial testing -// tryToRegister(); - - if (firstTime) { - //Show user manual, maybe? - //Toast.makeText(this, "First time!", Toast.LENGTH_SHORT).show(); - mPreferences.edit().putBoolean("first_time", false).apply(); + if (PropertyHolder.isFirstTime()) { + // TODO tryToRegister(); + String random_anon_id = UUID.randomUUID().toString(); + PropertyHolder.setUserId(random_anon_id); + showWelcomeDialog(); + PropertyHolder.setFirstTime(false); } } - private void tryToRegister() { + + // TODO take this out -- beta only + showNoRegistrationDialog(); + if(false){ boolean userIsRegistered = mPreferences.getBoolean("registered_user", false); if (!userIsRegistered) { if (Util.isOnline(getBaseContext())) { @@ -140,9 +133,26 @@ private void tryToRegister() { } else { Toast.makeText(this, getString(R.string.already_registered), Toast.LENGTH_SHORT).show(); } + } } + public void showNoRegistrationDialog(){ + AlertDialog.Builder b = new AlertDialog.Builder( + Switchboard.this); + b.setIcon(R.drawable.ic_launcher); + b.setTitle("Eth Holet Registration"); + b.setMessage("The final version of this app will let you create an account on the Eth Holet server so that ou can synchronized your data across devices and share highlights and ratings. For beta testing, however, no information is being sent to the server."); + b.setNeutralButton("OK", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + dialogInterface.dismiss(); + } + }); + b.show(); +} + + @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(group1, first_id, first_id, getString(R.string.preferences)); @@ -233,6 +243,29 @@ public void onClick(DialogInterface dialog, int which) { builderSingle.show(); } + private void showWelcomeDialog() { + AlertDialog.Builder b = new AlertDialog.Builder( + Switchboard.this); + b.setIcon(R.drawable.ic_launcher); + b.setTitle("Welcome to Eth Holet!"); + b.setMessage("Thanks for trying out the beta version of our app. You will see that the app communicates with you in a mixture of English and Catalan (regardless of the language setting you choose). This will change in the next few weeks once we have everything translated, so please bear with us for now.\n\nIn order to function offline in the mountains, Eth Holet needs to perform an initial sync with the server, which will take several minutes. If you have an internet connection and would like to do this now, please click 'OK'. Otherwise, you can always do it later by choosing the 'sync' option from the menu on this screen."); + b.setPositiveButton("OK", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + startInitialSync(); + } + }); + b.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + dialogInterface.dismiss(); + } + }); + b.show(); + } + + + private void startInitialSync() { @@ -325,9 +358,7 @@ protected Boolean doInBackground(Context... context) { } } - //Maps - - + //General Maps boolean mapSuccess = true; try { HttpResponse response = Util.getResponse(Util.getUrlGeneralMap(context[0]), 180000); @@ -433,6 +464,120 @@ protected Boolean doInBackground(Context... context) { PropertyHolder.setLastUpdateGeneralMapNow(); } + +//Route Maps +List routes = DataContainer.getAllOfficialRoutes(app.getDataBaseHelper()); + boolean routeMapSuccess; + for(Route route: routes){ + routeMapSuccess = true; + try { + HttpResponse response = Util.getResponse(Util.getUrlRouteMap(route), 180000); + int statusCode = response.getStatusLine().getStatusCode(); + Log.i("Route MAP Download", "Status code:" + statusCode); + if (statusCode == 200) { + if (response.containsHeader("Content-Length")) { + int fileSize = Integer.parseInt(response.getFirstHeader("Content-Length").getValue()); + HttpEntity entity = response.getEntity(); + File destinationFile = new File(Environment.getExternalStorageDirectory().getPath(), Util.baseFolder + "/route_map.zip"); + String destinationPath = destinationFile.getPath(); + Log.d("ANDRO_ASYNC", "Save path: " + destinationPath); + InputStream input = new BufferedInputStream(entity.getContent()); + OutputStream output = new FileOutputStream(destinationPath); + byte data[] = new byte[1024]; + int total = 0; + while ((count = input.read(data)) != -1) { + if (isCancelled()) { + mapSuccess = false; + break; + } else { + output.write(data, 0, count); + total += count; + myProgress = (int) ((total * 90) / fileSize); + publishProgress(myProgress); + } + } + output.flush(); + output.close(); + input.close(); + // NOW UNZIP IT + ZipFile thisZipfile = new ZipFile(destinationPath); + int nEntries = thisZipfile.size(); + int zipCounter = 0; + String zipFilePath = destinationPath; + Log.d("ANDRO_ASYNC", "read path: " + destinationPath); + File target_directory = new File(Environment.getExternalStorageDirectory().getPath(), Util.baseFolder + "/" + Util.routeMapsFolder); + String destDirectory = target_directory.getPath(); + Log.d("ANDRO_ASYNC", "Save path: " + destDirectory); + try { + final int BUFFER_SIZE = 4096; + File destDir = new File(destDirectory); + if (!destDir.exists()) { + destDir.mkdirs(); + } + ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath)); + ZipEntry entry = zipIn.getNextEntry(); + // iterates over entries in the zip file. THE server should put only one in it, and I will save only the last entry as the map destination in shared preferences. But I am keeping the iteration just in case that would change in future. + while (entry != null) { + if (isCancelled()) { + mapSuccess = false; + break; + } else { + String filePath = destDirectory + File.separator + entry.getName(); + PropertyHolder.setGeneralMapPath(filePath); + if (!entry.isDirectory()) { + // if the entry is a file, extracts it + File f = new File(filePath); + File dir = new File(f.getParent()); + dir.mkdirs(); + BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath)); + byte[] bytesIn = new byte[BUFFER_SIZE]; + int read = 0; + while ((read = zipIn.read(bytesIn)) != -1) { + bos.write(bytesIn, 0, read); + } + bos.close(); + + // add it to route + route.setLocalCarto(filePath); + route.setLocalCartoLastUpdatedNow(); + DataContainer.updateRoute(route, app.getDataBaseHelper()); + } else { + // if the entry is a directory, make the directory + File dir = new File(filePath); + dir.mkdirs(); + } + } + myProgress += (int) ((++zipCounter * 10) / nEntries); + publishProgress(myProgress); + zipIn.closeEntry(); + entry = zipIn.getNextEntry(); + } + zipIn.close(); + } catch (Exception ex) { + mapSuccess = false; + Log.e("MAP ERROR 1: ", ex.getStackTrace().toString()); + } + + } else { + Log.e("Maps", "entity: " + response.getEntity().getContent()); + } + } else { + Log.e("NEWTRY", "failed to get map"); + mapSuccess = false; + } + } catch (ClientProtocolException e) { + Log.e("NEWTRY", "error: " + e); + mapSuccess = false; + + } catch (IOException e) { + mapSuccess = false; + Log.e("NEWTRY", "error: " + e); + } + if (mapSuccess) { + PropertyHolder.setLastUpdateGeneralMapNow(); + } + + } // GENERAL REFS @@ -557,7 +702,6 @@ protected Boolean doInBackground(Context... context) { } // ROUTE MEDIA - List routes = DataContainer.getAllOfficialRoutes(app.getDataBaseHelper()); Log.e("ROUTES:", "size: " + routes.size()); for (Route route : routes) { boolean routeSuccess = true; diff --git a/SUDEAU/src/net/movelab/sudeau/Util.java b/SUDEAU/src/net/movelab/sudeau/Util.java index d29bec0..a8802fe 100644 --- a/SUDEAU/src/net/movelab/sudeau/Util.java +++ b/SUDEAU/src/net/movelab/sudeau/Util.java @@ -1111,13 +1111,25 @@ public static String getUrlGeneralMap(Context context) { return result; } + public static String getUrlRouteMap(Route route) { + long last_update = route.getLocalCartoLastUpdated(); + String result = UtilLocal.URL_ROUTE_MAP + route.getId() + "/" + last_update + "/"; + return result; + } + + public static int getLargestScreenDimension(Context context){ + DisplayMetrics metrics = new DisplayMetrics(); + WindowManager windowManager = (WindowManager) context + .getSystemService(Context.WINDOW_SERVICE); + windowManager.getDefaultDisplay().getMetrics(metrics); + // I am setting the width to whichever is the longer dimension (since we don't know the orientation). This way, images will always be fully sharp and full width in landcape mode, and they can be rescaled on phone for portrait. + return Math.max(metrics.widthPixels, metrics.heightPixels); + } + public static String getUrlGeneralReferences(Context context) { - DisplayMetrics metrics = new DisplayMetrics(); - WindowManager windowManager = (WindowManager) context - .getSystemService(Context.WINDOW_SERVICE); - windowManager.getDefaultDisplay().getMetrics(metrics); - int screenWidthPixels = metrics.widthPixels; + // I am setting the width to whichever is the longer dimension (since we don't know the orientation). This way, images will always be fully sharp and full width in landcape mode, and they can be rescaled on phone for portrait. + int screenWidthPixels = getLargestScreenDimension(context); if (!PropertyHolder.isInit()) PropertyHolder.init(context); long last_update = PropertyHolder.getLastUpdateGeneralReferences(); @@ -1126,18 +1138,13 @@ public static String getUrlGeneralReferences(Context context) { } public static String getUrlRouteContent(Context context, String routeId, long lastUpdate) { - DisplayMetrics metrics = new DisplayMetrics(); - WindowManager windowManager = (WindowManager) context - .getSystemService(Context.WINDOW_SERVICE); - windowManager.getDefaultDisplay().getMetrics(metrics); - int screenWidthPixels = metrics.widthPixels; + // I am setting the width to whichever is the longer dimension (since we don't know the orientation). This way, images will always be fully sharp and full width in landcape mode, and they can be rescaled on phone for portrait. + int screenWidthPixels = getLargestScreenDimension(context); String result = UtilLocal.URL_ROUTE_CONTENT + routeId + "/" + screenWidthPixels + "/" + Long.toString(lastUpdate) + "/"; return result; } - - public static boolean hasMinimumContents(Context context, EruletApp app) { if (!PropertyHolder.isInit()) PropertyHolder.init(context); diff --git a/SUDEAU/src/net/movelab/sudeau/database/DataBaseHelper.java b/SUDEAU/src/net/movelab/sudeau/database/DataBaseHelper.java index 118b020..370326d 100644 --- a/SUDEAU/src/net/movelab/sudeau/database/DataBaseHelper.java +++ b/SUDEAU/src/net/movelab/sudeau/database/DataBaseHelper.java @@ -24,7 +24,7 @@ public class DataBaseHelper extends OrmLiteSqliteOpenHelper { //Database Version - public static final int DATABASE_VERSION = 203; + public static final int DATABASE_VERSION = 206; // Database Name public static final String DATABASE_NAME = "appdata"; diff --git a/SUDEAU/src/net/movelab/sudeau/database/DataContainer.java b/SUDEAU/src/net/movelab/sudeau/database/DataContainer.java index 3a7cda6..d913f4b 100644 --- a/SUDEAU/src/net/movelab/sudeau/database/DataContainer.java +++ b/SUDEAU/src/net/movelab/sudeau/database/DataContainer.java @@ -187,6 +187,12 @@ public static HighLight refreshHighlightForFileManifest(HighLight hl, DataBaseHe return hl; } + public static Step refreshStepForHighlight(Step s, DataBaseHelper db) { + db.getHlDataDao().refresh(s.getHighlights()); + Log.i("REFRESH", hl.getId()); + return hl; + } + public static Reference refreshReference(Reference r, DataBaseHelper db) { db.getReferenceDataDao().refresh(r); @@ -355,11 +361,6 @@ private static List getStepIds(List steps) { return ids; } - public static String getAndroidId(ContentResolver cr) { - String android_id = Secure.getString(cr, Secure.ANDROID_ID); - return android_id; - } - public static void editRoute(Route editedRoute, DataBaseHelper db) { db.getRouteDataDao().update(editedRoute); } @@ -587,14 +588,14 @@ public static void updateInteractiveImage(InteractiveImage ii, DataBaseHelper da } public static void insertRoute(Route editedRoute, - DataBaseHelper dataBaseHelper, String android_id) { + DataBaseHelper dataBaseHelper, String userId) { // Save track // Track t = new Track(); if (editedRoute.getTrack() != null) { Track t = editedRoute.getTrack(); if (t.getId() == null || t.getId().equals("")) { t.setId( - DataContainer.getTrackId(dataBaseHelper, android_id)); + DataContainer.getTrackId(dataBaseHelper, userId)); } if (t.getName() == null || t.getName().equals("")) { //TODO change this once all track languages are in. Should be a line for each language. @@ -613,14 +614,14 @@ public static void insertRoute(Route editedRoute, for (int i = 0; i < currentSteps.size(); i++) { Step s = currentSteps.get(i); if (s.getId() == null) { - s.setId(DataContainer.getStepId(dataBaseHelper, android_id)); + s.setId(DataContainer.getStepId(dataBaseHelper, userId)); } s.setTrack(t); if (s.getHighlights() != null) { for (HighLight h : s.getHighlights()) { if (h.getId() == null) { - h.setId(DataContainer.getHighLightId(dataBaseHelper, android_id)); + h.setId(DataContainer.getHighLightId(dataBaseHelper, userId)); Log.e("HIGHLIGHT MISSING ID", h.getName()); } @@ -683,7 +684,7 @@ public static void insertRoute(Route editedRoute, } } if (editedRoute.getId() == null || editedRoute.getId().equals("")) { - editedRoute.setId(DataContainer.getRouteId(dataBaseHelper, android_id)); + editedRoute.setId(DataContainer.getRouteId(dataBaseHelper, userId)); } try { diff --git a/SUDEAU/src/net/movelab/sudeau/model/Route.java b/SUDEAU/src/net/movelab/sudeau/model/Route.java index e602f30..cdf2315 100644 --- a/SUDEAU/src/net/movelab/sudeau/model/Route.java +++ b/SUDEAU/src/net/movelab/sudeau/model/Route.java @@ -92,6 +92,11 @@ public void setLocalCartoLastUpdated(long localCartoLastUpdated) { this.localCartoLastUpdated = localCartoLastUpdated; } + public void setLocalCartoLastUpdatedNow() { + this.localCartoLastUpdated = System.currentTimeMillis()/1000; + } + + public long getRouteContentLastUpdated() { return routeContentLastUpdated; }