diff --git a/src/it/reyboz/bustorino/ActivityFavorites.java b/src/it/reyboz/bustorino/ActivityFavorites.java
index e901d9a..7288a29 100644
--- a/src/it/reyboz/bustorino/ActivityFavorites.java
+++ b/src/it/reyboz/bustorino/ActivityFavorites.java
@@ -1,210 +1,210 @@
/*
BusTO - Arrival times for Turin public transports.
Copyright (C) 2014 Valerio Bozzolan
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
*/
package it.reyboz.bustorino;
import it.reyboz.bustorino.backend.Stop;
-import it.reyboz.bustorino.lab.GTTSiteSucker.BusStop;
import it.reyboz.bustorino.middleware.StopAdapter;
import it.reyboz.bustorino.middleware.UserDB;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import java.util.List;
public class ActivityFavorites extends AppCompatActivity {
private ListView favoriteListView;
private EditText bus_stop_name;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorites);
ActionBar ab = getSupportActionBar();
assert ab != null;
ab.setIcon(R.drawable.ic_launcher);
ab.setDisplayHomeAsUpEnabled(true); // Back button
favoriteListView = (ListView) findViewById(R.id.favoriteListView);
createFavoriteList();
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId() == R.id.favoriteListView) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_favourites_entry, menu);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
- BusStop busStop = (BusStop) favoriteListView.getItemAtPosition(info.position);
+ Stop busStop = (Stop) favoriteListView.getItemAtPosition(info.position);
switch (item.getItemId()) {
case R.id.action_favourite_entry_delete:
// TODO: implement
//busStop.setIsFavorite(false);
//UserDB.DBBusStop.addBusStop(db, busStop);
createFavoriteList();
return true;
case R.id.action_rename_bus_stop_username:
showBusStopUsernameInputDialog(busStop);
return true;
default:
return super.onContextItemSelected(item);
}
}
void createFavoriteList() {
UserDB userDB = new UserDB(getApplicationContext());
SQLiteDatabase db = userDB.getReadableDatabase();
List busStops = UserDB.getFavorites(db);
// TODO: close connection
// If no data is found show a friendly message
if (busStops.size() == 0) {
favoriteListView.setVisibility(View.INVISIBLE);
TextView favoriteTipTextView = (TextView) findViewById(R.id.favoriteTipTextView);
assert favoriteTipTextView != null;
favoriteTipTextView.setVisibility(View.VISIBLE);
}
// Show results
favoriteListView.setAdapter(new StopAdapter(this, busStops));
favoriteListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView> parent, View view, int position, long id) {
/**
* Casting because of Javamerda
* @url http://stackoverflow.com/questions/30549485/androids-list-view-parameterized-type-in-adapterview-onitemclicklistener
*/
Stop busStop = (Stop) parent.getItemAtPosition(position);
Intent intent = new Intent(ActivityFavorites.this,
ActivityMain.class);
Bundle b = new Bundle();
b.putString("bus-stop-ID", busStop.ID);
intent.putExtras(b);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
});
registerForContextMenu(favoriteListView);
}
private class BusStopUsernameOnClickListener implements DialogInterface.OnClickListener {
- private BusStop busStop;
+ private Stop busStop;
- BusStopUsernameOnClickListener(BusStop busStop) {
+ BusStopUsernameOnClickListener(Stop busStop) {
this.busStop = busStop;
}
@Override
public void onClick(DialogInterface dialog, int which) {
}
}
- public void showBusStopUsernameInputDialog(BusStop busStop) {
+ public void showBusStopUsernameInputDialog(Stop busStop) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View renameDialogLayout = inflater.inflate(R.layout.rename_dialog, null);
bus_stop_name = (EditText) renameDialogLayout.findViewById(R.id.rename_dialog_bus_stop_name);
- bus_stop_name.setText(busStop.getBusStopUsername());
- bus_stop_name.setHint(busStop.getBusStopName());
+ bus_stop_name.setText(busStop.getStopName());
+ // TODO: default name as hint
+ //bus_stop_name.setHint(busStop.getBusStopName());
builder.setTitle(getString(R.string.dialog_rename_bus_stop_username_title));
builder.setView(renameDialogLayout);
builder.setPositiveButton(getString(android.R.string.ok), new BusStopUsernameOnClickListener(busStop) {
@Override
public void onClick(DialogInterface dialog, int which) {
String busStopUsername = bus_stop_name.getText().toString();
if (busStopUsername.length() == 0) {
busStopUsername = null;
}
- super.busStop.setBusStopUsername(busStopUsername);
+ //super.busStop.setBusStopUsername(busStopUsername);
// TODO: implement
//UserDB.DBBusStop.addBusStop(db, super.busStop, DBBusStop.FORCE_NULL_BUSSTOP_USERNAME);
createFavoriteList();
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setNeutralButton(R.string.dialog_rename_bus_stop_username_reset_button, new BusStopUsernameOnClickListener(busStop) {
@Override
public void onClick(DialogInterface dialog, int which) {
- super.busStop.setBusStopUsername(null);
+ //super.busStop.setBusStopUsername(null);
// TODO: implement
//UserDB.DBBusStop.addBusStop(db, super.busStop, DBBusStop.FORCE_NULL_BUSSTOP_USERNAME);
createFavoriteList();
}
});
builder.show();
}
}
diff --git a/src/it/reyboz/bustorino/backend/networkTools.java b/src/it/reyboz/bustorino/backend/networkTools.java
index 9600460..59fa3b6 100644
--- a/src/it/reyboz/bustorino/backend/networkTools.java
+++ b/src/it/reyboz/bustorino/backend/networkTools.java
@@ -1,123 +1,126 @@
/*
BusTO - Arrival times for Turin public transports.
Copyright (C) 2014 Valerio Bozzolan
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
*/
package it.reyboz.bustorino.backend;
import android.support.annotation.Nullable;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicReference;
public abstract class networkTools {
static String getDOM(final URL url, final AtomicReference res) {
//Log.d("asyncwget", "Catching URL in background: " + uri[0]);
HttpURLConnection urlConnection;
StringBuilder result = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch(IOException e) {
res.set(Fetcher.result.CLIENT_OFFLINE);
return null;
}
try {
InputStream in = new BufferedInputStream(
urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
//Log.e("asyncwget", e.getMessage());
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
if (result == null) {
res.set(Fetcher.result.PARSER_ERROR);
return null;
}
res.set(Fetcher.result.SERVER_ERROR); // will be set to "OK" later, this is a safety net in case StringBuilder returns null, the website returns an HTTP 204 or something like that.
return result.toString();
}
@Nullable
static String queryURL(URL url, AtomicReference res) {
HttpURLConnection urlConnection;
- InputStream in = null;
+ InputStream in;
String s;
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch(IOException e) {
res.set(Fetcher.result.SERVER_ERROR); // TODO: can we assume this is CLIENT_OFFLINE?
return null;
}
+ // TODO: make this configurable?
+ urlConnection.setConnectTimeout(5000);
+ urlConnection.setReadTimeout(10000);
res.set(Fetcher.result.PARSER_ERROR); // will be set to OK later
try {
in = urlConnection.getInputStream();
} catch (Exception e) {
return null;
}
s = streamToString(in);
try {
in.close();
} catch(Exception ignored) {}
try {
urlConnection.disconnect();
} catch(Exception ignored) {}
if(s.length() == 0) {
return null;
} else {
return s;
}
}
// https://stackoverflow.com/a/5445161
static String streamToString(InputStream is) {
Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
static int failsafeParseInt(String str) {
try {
return Integer.parseInt(str);
} catch(NumberFormatException e) {
return 0;
}
}
}
diff --git a/src/it/reyboz/bustorino/lab/GTTSiteSucker.java b/src/it/reyboz/bustorino/lab/GTTSiteSucker.java
deleted file mode 100644
index ad2179c..0000000
--- a/src/it/reyboz/bustorino/lab/GTTSiteSucker.java
+++ /dev/null
@@ -1,387 +0,0 @@
-/*
- BusTO - Arrival times for Turin public transports.
- Copyright (C) 2014 Valerio Bozzolan
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see .
- */
-package it.reyboz.bustorino.lab;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.StringReader;
-import java.io.UnsupportedEncodingException;
-import java.net.URLEncoder;
-import java.util.ArrayList;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.jsoup.Jsoup;
-import org.jsoup.nodes.Document;
-import org.jsoup.nodes.Element;
-import org.jsoup.select.Elements;
-
-import android.database.sqlite.SQLiteDatabase;
-import android.util.Log;
-
-/**
- * «BusTO, because sucking happens»
- *
- * @author Valerio Bozzolan
- */
-public class GTTSiteSucker {
-
- /**
- * Execute regexes.
- *
- * @param needle Regex
- * @param haystack Entire string
- * @return Matched string
- */
- public static String grep(String needle, String haystack) {
- String matched = null;
- Matcher matcher = Pattern.compile(
- needle).matcher(haystack);
- if (matcher.find()) {
- matched = matcher.group(1);
- }
- return matched;
- }
-
- /**
- * Javammerda! Lasciami null senza suicidarti!
- */
- public static Integer string2Integer(String str) {
- try {
- return Integer.parseInt(str);
- } catch(NumberFormatException e) {
- return null;
- }
- }
-
- /**
- * Helps comparing times
- */
- public static class Time {
- private int mm;
- private int hh;
-
- public Time(int hh, int mm) {
- this.hh = hh;
- this.mm = mm;
- }
-
- public boolean isMajorThan(Time time) {
- if (hh == time.getHH()) {
- return mm >= time.getMM();
- } else if (hh > time.getHH() || hh == 0 && time.getHH() == 23) {
- return true;
- }
- return false;
- }
-
- public int getHH() {
- return hh;
- }
-
- public int getMM() {
- return mm;
- }
- }
-
- /**
- * A time passage is a time with the answer of: Is this in real time?
- *
- * @author boz
- */
- public static class TimePassage {
- private String time;
- private boolean isInRealTime;
-
- public TimePassage(String time, boolean isInRealTime) {
- this.time = time;
- this.isInRealTime = isInRealTime;
- }
-
- public String getTime() {
- return time;
- }
-
- public boolean isInRealTime() {
- return isInRealTime;
- }
-
- /**
- * @return null if can't be converted into a time
- */
- public Time getComparableTime() {
- int hh, mm;
- String[] parts = time.split(":");
- if (parts.length != 2) {
- return null;
- }
- try {
- hh = Integer.valueOf(parts[0]);
- mm = Integer.valueOf(parts[1]);
- } catch (NumberFormatException e) {
- return null;
- }
- return new Time(hh, mm);
- }
-
- public String toString() {
- return time
- + (isInRealTime ? "*" : " ");
- }
- }
-
- /**
- * Passages (at a bus line) (like line numbers)
- *
- * @author boz
- */
- public static class BusLine {
-
- private Integer busLineID;
- private String busLineName;
- private String busLineUsername;
- private Integer busLineType;
-
- private ArrayList timesPassages = new ArrayList();
-
- public BusLine(Integer busLineID, String busLineName) {
- this.busLineID = busLineID;
- this.busLineName = busLineName;
- }
-
- public Integer getBusLineID() {
- return busLineID;
- }
-
- public void setBusLineID(Integer busLineID) {
- this.busLineID = busLineID;
- }
-
- public String getBusLineName() {
- return busLineName;
- }
-
- public void setBusLineName(String busLineName) {
- this.busLineName = busLineName;
- }
-
- public String getBusLineUsername() {
- return busLineUsername;
- }
-
- public void setBusLineUsername(String busLineUsername) {
- this.busLineUsername = busLineUsername;
- }
-
- public Integer getBusLineType() {
- return busLineType;
- }
-
- public void setBusLineType(Integer busLineType) {
- this.busLineType = busLineType;
- }
-
- public void addTimePassage(String time, boolean isInRealTime) {
- timesPassages.add(new TimePassage(time, isInRealTime));
- }
-
- public TimePassage[] getTimePassages() {
- return timesPassages.toArray(new TimePassage[timesPassages.size()]);
- }
-
- public String getTimePassagesString() {
- if (timesPassages.size() == 0) {
- return null;
- }
- String out = "";
- for (TimePassage timePassage : timesPassages) {
- if(! out.equals("")) {
- out += " ";
- }
- out += timePassage.toString();
- }
- return out;
- }
-
- public Time getFirstPassageComparableTime() {
- if(timesPassages == null || timesPassages.size() == 0) {
- return null;
- }
- return timesPassages.get(0).getComparableTime();
- }
-
- public String toString() {
- return busLineName + " (" + busLineID + ")";
- }
-
- /**
- * Help sorting
- *
- * @param busLineName
- * @return boolean -1/0/1 if this is minor/equal/major than busLineName arg (First 0-9, than A-Z)
- */
- public boolean isMajorThan(String busLineName) {
- final String regex = "^([0-9]+)";
- Integer nThis = string2Integer(grep(regex, this.busLineName));
- Integer nOther = string2Integer(grep(regex, busLineName));
- //Log.d("GTTSiteSucker", "\"" + this.busLineName + "\" (" + nThis + ") | \"" + busLineName + "\" (" + nOther + ")");
- if(nThis != null) {
- if(nOther != null) {
- int res = nThis.compareTo(nOther);
- if(res != 0) {
- return res > 0; // 0-9 <=> 0-9
- }
- }
- return false; // 0-9 < A-Z
- }
- if(nOther != null) {
- return true; // A-Z > 0-9
- }
- return this.busLineName.compareTo(busLineName) > 0; // A-Z <=> A-Z || 0-9 == 0-9
- }
- }
-
- /**
- * A BusStop has information on the bus stop (bus stop name) and of all the
- * buses that pass through it
- *
- * @author boz
- */
- public static class BusStop {
- private String busStopID; // Es: 1254 NOT always Integer!!! Sometimes there is something like "STCAR" D:
- private String busStopName; // Es: MARCONI
- private String busStopUsername;
- private String busStopLocality; // Es: Torino
- private String latitude;
- private String longitude;
- private BusLine[] busLines;
-
- private Boolean isFavorite = null;
-
- public BusStop(String busStopID) {
- this.busStopID = busStopID;
- }
-
- public BusStop(String busStopID, String busStopName) {
- this.busStopID = busStopID;
- this.busStopName = busStopName;
- }
-
- public BusStop(String busStopID, String busStopName, BusLine[] busLines) {
- this.busStopID = busStopID;
- this.busStopName = busStopName;
- this.busLines = busLines;
- }
-
- public String getBusStopName() {
- return busStopName;
- }
-
- public String getBusStopUsername() {
- return busStopUsername;
- }
-
- public void setBusStopUsername(String busStopUsername) {
- this.busStopUsername = busStopUsername;
- }
-
- public String getBusStopLocality() {
- return busStopLocality;
- }
-
- public String getBusStopID() {
- return busStopID;
- }
-
- public void setBusStopName(String busStopName) {
- this.busStopName = busStopName;
- }
-
- public BusLine[] getBusLines() {
- return busLines;
- }
-
- public void orderBusLinesByFirstArrival() {
- for (int i = 0; i < busLines.length - 1; i++) {
- for (int j = i + 1; j < busLines.length; j++) {
- BusLine a = busLines[i];
- BusLine b = busLines[j];
- Time aTime = a.getFirstPassageComparableTime();
- Time bTime = b.getFirstPassageComparableTime();
- if (aTime != null && bTime != null
- && aTime.isMajorThan(bTime)) {
- BusLine tmp = a;
- busLines[i] = b;
- busLines[j] = tmp;
- }
- }
- }
- }
-
- public void setBusStopLocality(String busStopLocality) {
- this.busStopLocality = busStopLocality;
- }
-
- public void setCoordinate(String latitude, String longitude) {
- this.latitude = latitude;
- this.longitude = longitude;
- }
-
- public String getLatitude() {
- return latitude;
- }
-
- public String getLongitude() {
- return longitude;
- }
-
- public Boolean getIsFavorite() {
- return isFavorite;
- }
-
- public void setIsFavorite(Boolean isFavorite) {
- this.isFavorite = isFavorite;
- }
-
- public void orderBusLinesByName() {
- for (int i = 0; i < busLines.length - 1; i++) {
- for (int j = i + 1; j < busLines.length; j++) {
- BusLine a = busLines[i];
- BusLine b = busLines[j];
- // Log.d("GTTSiteSucker", "Comparing " + a.getBusLineName() + (a.isMajorThan(b.getBusLineName()) ? " major than " : " minor or equal than ") + b.getBusLineName());
- if (a.isMajorThan(b.getBusLineName())) {
- BusLine tmp = a;
- busLines[i] = b;
- busLines[j] = tmp;
- }
- }
- }
- }
-
- /**
- * @return Bus line list
- */
- public String toString() {
- String toString = busStopID;
- if(busStopName != null) {
- toString += " (" + busStopName + ")";
- }
- return toString;
- }
- }
-}
diff --git a/src/it/reyboz/bustorino/lab/adapters/AdapterBusLines.java b/src/it/reyboz/bustorino/lab/adapters/AdapterBusLines.java
deleted file mode 100644
index 7e4e23e..0000000
--- a/src/it/reyboz/bustorino/lab/adapters/AdapterBusLines.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- BusTO - Arrival times for Turin public transports.
- Copyright (C) 2014 Valerio Bozzolan
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see .
- */
-package it.reyboz.bustorino.lab.adapters;
-
-import android.content.Context;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.ArrayAdapter;
-import android.widget.TextView;
-import it.reyboz.bustorino.R;
-import it.reyboz.bustorino.lab.GTTSiteSucker.BusLine;
-
-/**
- * ListView Adapter for BusLine[].
- *
- * Thanks to Framentos developers for the guide:
- * http://www.framentos.com/en/android-tutorial/2012/07/16/listview-in-android-using-custom-listadapter-and-viewcache/#
- *
- * @author Valerio Bozzolan
- */
-public class AdapterBusLines extends ArrayAdapter {
-
- private LayoutInflater layoutInflater;
- private Context context;
- private int resource;
-
- public AdapterBusLines(Context context, int resource, BusLine busLines[]) {
- super(context, resource, busLines);
- layoutInflater = LayoutInflater.from(context);
- this.context = context;
- this.resource = resource;
- }
-
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- // Create a new view of my layout and inflate it in the row
- convertView = layoutInflater.inflate(resource, null);
-
- // Extract the busLine object to show
- BusLine busLine = getItem( position );
-
- // Take the TextView from layout and set the busLine name
- TextView busLineIconTextView = (TextView) convertView.findViewById(R.id.routeID);
- busLineIconTextView.setText(busLine.getBusLineName());
-
- // Vehicle icon
- //TextView busLineVehicleIcon = (TextView) convertView.findViewById(R.id.vehicleIcon);
-
- // Take the TextView from layout and set the BusLine's passages
- TextView busLinePassagesTextView = (TextView) convertView.findViewById(R.id.routesThatStopHere);
- String timePassages = busLine.getTimePassagesString();
- if(timePassages != null) {
- busLinePassagesTextView.setText(timePassages);
- } else {
- busLinePassagesTextView.setText(R.string.no_passages);
- //busLineVehicleIcon.setVisibility(View.INVISIBLE);
- }
-
- return convertView;
- }
-}
diff --git a/src/it/reyboz/bustorino/lab/adapters/AdapterBusStops.java b/src/it/reyboz/bustorino/lab/adapters/AdapterBusStops.java
deleted file mode 100644
index 785dd48..0000000
--- a/src/it/reyboz/bustorino/lab/adapters/AdapterBusStops.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- BusTO - Arrival times for Turin public transports.
- Copyright (C) 2014 Valerio Bozzolan
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see .
- */
-package it.reyboz.bustorino.lab.adapters;
-
-import android.content.Context;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.ArrayAdapter;
-import android.widget.TextView;
-import it.reyboz.bustorino.R;
-import it.reyboz.bustorino.lab.GTTSiteSucker.BusLine;
-import it.reyboz.bustorino.lab.GTTSiteSucker.BusStop;
-
-/**
- * ListView Adapter for BusStop[].
- *
- * @author Valerio Bozzolan
- */
-public class AdapterBusStops extends ArrayAdapter {
-
- private LayoutInflater layoutInflater;
- private Context context;
- private int resource;
-
- public AdapterBusStops(Context context, int resource, BusStop busStops[]) {
- super(context, resource, busStops);
- layoutInflater = LayoutInflater.from(context);
- this.context = context;
- this.resource = resource;
- }
-
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- // Create a new view of my layout and inflate it in the row
- convertView = layoutInflater.inflate(resource, null);
-
- // Extract the busStop object to show
- BusStop busStop = getItem( position );
-
- // Take the TextView from layout and set the BusStop ID
- TextView busStopIDTextView = (TextView) convertView.findViewById(R.id.busStopID);
- busStopIDTextView.setText(busStop.getBusStopID());
-
- // Take the TextView from layout and set the busStop name
- TextView busStopNameTextView = (TextView) convertView.findViewById(R.id.busStopName);
- if(busStop.getBusStopUsername() != null) {
- busStopNameTextView.setText(busStop.getBusStopUsername());
- } else {
- busStopNameTextView.setText(busStop.getBusStopName());
- }
-
- // Vehicle icon
- //TextView busLineVehicleIcon = (TextView) convertView.findViewById(R.id.vehicleIcon);
-
- // Take the TextView from layout and set the busStop locality
- TextView busStopLinesTextView = (TextView) convertView.findViewById(R.id.routesThatStopHere);
- if(busStop.getBusLines() != null) {
- String busLines = "";
- for(BusLine busLine: busStop.getBusLines()) {
- if(busLines.length() > 0) {
- busLines += ", ";
- }
- busLines += busLine.getBusLineName();
- }
- busStopLinesTextView.setText(busLines);
- } else {
- busStopLinesTextView.setVisibility(View.GONE);
- //busLineVehicleIcon.setVisibility(View.INVISIBLE);
- }
-
- TextView busStopLocaLityTextView = (TextView) convertView.findViewById(R.id.busStopLocality);
- if (busStop.getBusStopLocality() != null) {
- busStopLocaLityTextView.setText(busStop.getBusStopLocality());
- } else {
- busStopLocaLityTextView.setVisibility(View.GONE);
- }
-
- return convertView;
- }
-}
diff --git a/src/it/reyboz/bustorino/lab/asyncwget/AsyncWget.java b/src/it/reyboz/bustorino/lab/asyncwget/AsyncWget.java
deleted file mode 100644
index bb5da6d..0000000
--- a/src/it/reyboz/bustorino/lab/asyncwget/AsyncWget.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- BusTO - Arrival times for Turin public transports.
- Copyright (C) 2014 Valerio Bozzolan
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see .
- */
-package it.reyboz.bustorino.lab.asyncwget;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedReader;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.net.HttpURLConnection;
-import java.net.URL;
-
-import android.os.AsyncTask;
-import android.util.Log;
-
-/**
- * Asynchronous DOM fetcher using HTTP.
- *
- * @author Valerio Bozzolan
- */
-public class AsyncWget extends AsyncTask {
- protected Exception exceptions;
-
- /**
- * Overload it!
- *
- * @param uri The URL
- * @return The response that go to the onPostExecute
- */
- protected String doInBackground(String... uri) {
- exceptions = null;
- Log.d("asyncwget", "Catching URL in background: " + uri[0]);
- HttpURLConnection urlConnection = null;
- StringBuilder result = null;
- try {
- URL url = new URL(uri[0]);
- urlConnection = (HttpURLConnection) url.openConnection();
- InputStream in = new BufferedInputStream(
- urlConnection.getInputStream());
- BufferedReader reader = new BufferedReader(
- new InputStreamReader(in));
- result = new StringBuilder();
- String line;
- while ((line = reader.readLine()) != null) {
- result.append(line);
- }
- } catch (Exception e) {
- // TODO Auto-generated catch block
- Log.e("asyncwget", e.getMessage());
- exceptions = e;
- } finally {
- urlConnection.disconnect();
- }
-
- if (result == null) {
- return null;
- }
- return result.toString();
- }
-
- protected void onProgressUpdate(Integer... progress) {
- }
-
- /**
- * Overload it!
- *
- * @param result The DOM result fetched in background.
- */
- protected void onPostExecute(String result) {
- super.onPostExecute(result);
- }
-
- protected void onCancelled() {
- this.cancel(true);
- }
-
- protected void onError() {
-
- }
-}
\ No newline at end of file
diff --git a/src/it/reyboz/bustorino/lab/asyncwget/AsyncWgetBusStopFromBusStopID.java b/src/it/reyboz/bustorino/lab/asyncwget/AsyncWgetBusStopFromBusStopID.java
deleted file mode 100644
index fd70058..0000000
--- a/src/it/reyboz/bustorino/lab/asyncwget/AsyncWgetBusStopFromBusStopID.java
+++ /dev/null
@@ -1,190 +0,0 @@
-/*
- BusTO - Arrival times for Turin public transports.
- Copyright (C) 2014 Valerio Bozzolan
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see .
- */
-package it.reyboz.bustorino.lab.asyncwget;
-
-import android.util.Log;
-
-import org.jsoup.Jsoup;
-import org.jsoup.nodes.Document;
-import org.jsoup.nodes.Element;
-import org.jsoup.select.Elements;
-
-import java.util.ArrayList;
-
-import it.reyboz.bustorino.lab.GTTSiteSucker;
-
-import static it.reyboz.bustorino.lab.GTTSiteSucker.grep;
-
-import it.reyboz.bustorino.lab.GTTSiteSucker.BusStop;
-
-/**
- * Asynchronous BusStop fetcher from a busStopID.
- *
- * @author Valerio Bozzolan
- */
-public class AsyncWgetBusStopFromBusStopID extends AsyncWget {
- public final static int ERROR_NONE = 0;
- public final static int ERROR_EMPTY_DOM = 1;
- public final static int ERROR_DOM = 2;
- public final static int ERROR_NO_PASSAGES_OR_NO_BUS_STOP = 3;
-
- /**
- * Like Ajax
- *
- * @param busStopID
- */
- public AsyncWgetBusStopFromBusStopID(String busStopID) {
- super.execute(getURL(busStopID));
- ;
- }
-
- protected final String getURL(String busStopID) {
- return "http://www.5t.torino.it/5t/trasporto/arrival-times-byline.jsp?action=getTransitsByLine&shortName=" + getFilteredBusStopID(busStopID);
- }
-
- protected final String getEmergencyURL(String busStopID) {
- return "http://www.gtt.to.it/cms/percorari/arrivi?palina=" + getFilteredBusStopID(busStopID);
- }
-
- /**
- * I've sent many emails to the public email info@5t.torino.it to write down something like:
- * «YOUR SITE EXPLODE IF I USE **YOUR** BUS LINE IDs STARTING WITH ZERO!!!!!»
- * So, waiting for a response, I must purge the busStopID from "0"s .__.
- * IN YOUR FACE 5T/GTT. IN YOUR FACE.
- *
- * @param busStopID
- * @return parseInt(busStopID)
- * @antifeatured yep
- * @notabug yep
- * @wontfix yep
- */
- protected final String getFilteredBusStopID(String busStopID) {
- /*
- * OK leds me ezplain why 'm dong this shot of shittt. OK zo swhy?
- * Bhumm thads because the GTT/5T site-"developer" ids obviusli drunk.
- */
- String enableGTTDeveloperSimulator = "on"; // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK
- final char ZZZZZZZEEEEROOOOOO = '0'; // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK
- char[] cinquettiBarraGtt = busStopID.toCharArray(); // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK
- int merda = 0; // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK
- while (merda < cinquettiBarraGtt.length && cinquettiBarraGtt[merda] == ZZZZZZZEEEEROOOOOO) {
- // COMPLETELELELLELEEELY DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK
- Log.i("AsyncWgetBusStop", "scimmie ubriache assunte per tirar su il sito 5T/GTT"); // DR
- merda++; // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK
- } // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK
- String trenoDiMerda = ""; // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK
- for (; merda < cinquettiBarraGtt.length; merda++) { // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK
- trenoDiMerda += cinquettiBarraGtt[merda]; // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK
- } // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK
- enableGTTDeveloperSimulator = "off"; // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK
-
- return trenoDiMerda;
- }
-
- protected void onPostExecute(String responseInDOMFormatBecause5THaveAbsolutelyNoIdeaWhatJSONWas) {
- if (responseInDOMFormatBecause5THaveAbsolutelyNoIdeaWhatJSONWas == null) {
- onReceivedBusStop(null, ERROR_EMPTY_DOM);
- return;
- }
-
- Document doc = Jsoup.parse(responseInDOMFormatBecause5THaveAbsolutelyNoIdeaWhatJSONWas);
- Element error = doc.select("p.errore").first();
- if (error != null) {
- onReceivedBusStop(null, ERROR_NO_PASSAGES_OR_NO_BUS_STOP);
- return;
- }
-
- Element span = doc.select("span").first();
- String busStopID = grep("^(.+) ", span.html());
- if (busStopID == null) {
- Log.e("BusStop", "Empty busStopID from " + span.html());
- onReceivedBusStop(null, ERROR_DOM);
- return;
- }
-
- String busStopName = grep("^.+ (.+)", span.html()); // The first "dot" is the single strange space character in the middle of "39{HERE→} {←HERE}PORTA NUOVA"
- if (busStopName == null) {
- Log.e("BusStop", "Empty busStopName from " + span.html());
- onReceivedBusStop(null, ERROR_DOM);
- return;
- }
- busStopName.trim();
-
- ArrayList busLines = new ArrayList();
-
- // Every table row is a busLine
- Elements trs = doc.select("table tr");
- for (Element tr : trs) {
- Element line = tr.select("td.line a").first();
- if (!line.hasText()) {
- onReceivedBusStop(null, ERROR_DOM);
- return;
- }
-
- String busLineName = line.text();
- Integer busLineID = Integer.parseInt(
- grep(
- "([0-9]+)$",
- line.attr("href")
- )
- );
- if (busLineName == null || busLineID == null) {
- onReceivedBusStop(null, ERROR_DOM);
- return;
- }
-
- GTTSiteSucker.BusLine busLine = new GTTSiteSucker.BusLine(busLineID, busLineName);
-
- // Every busLine have passages
- Elements tds = tr.select("td:not(.line)");
- for (Element td : tds) {
- boolean isInRealTime = td.select("i").size() > 0;
-
- td.select("i").remove(); // Stripping "*"
- String time = td.text().trim();
- if (time.equals("")) {
- // Yes... Sometimes there is an EMPTY td ._.
- continue;
- }
- busLine.addTimePassage(time, isInRealTime);
- }
-
- busLines.add(busLine);
- }
- onReceivedBusStop(
- new BusStop(
- busStopID,
- busStopName,
- busLines.toArray(
- new GTTSiteSucker.BusLine[busLines.size()]
- )
- ),
- ERROR_NONE
- );
- }
-
- /**
- * Overload this!
- *
- * @param busStop The busStop
- * @param status Error status if any
- */
- public void onReceivedBusStop(GTTSiteSucker.BusStop busStop, int status) {
- // Do something here
- }
-}
diff --git a/src/it/reyboz/bustorino/lab/asyncwget/AsyncWgetBusStopSuggestions.java b/src/it/reyboz/bustorino/lab/asyncwget/AsyncWgetBusStopSuggestions.java
deleted file mode 100644
index 959d226..0000000
--- a/src/it/reyboz/bustorino/lab/asyncwget/AsyncWgetBusStopSuggestions.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- BusTO - Arrival times for Turin public transports.
- Copyright (C) 2014 Valerio Bozzolan
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see .
- */
-package it.reyboz.bustorino.lab.asyncwget;
-
-import android.util.Log;
-
-import org.jsoup.Jsoup;
-import org.jsoup.nodes.Document;
-import org.jsoup.nodes.Element;
-import org.jsoup.select.Elements;
-
-import java.io.UnsupportedEncodingException;
-import java.net.URLEncoder;
-import java.util.ArrayList;
-import it.reyboz.bustorino.lab.GTTSiteSucker.BusStop;
-
-/**
- * Asynchronous BusStop[] fetcher from a query.
- *
- * @author Valerio Bozzolan
- */
-public class AsyncWgetBusStopSuggestions extends AsyncWget {
- public final static int ERROR_NONE = 0;
- public final static int ERROR_EMPTY_DOM = 1;
- public final static int ERROR_DOM = 2;
-
- /**
- * Like Ajax
- *
- * @param query Part of the busStopName
- * @throws UnsupportedEncodingException
- */
- public AsyncWgetBusStopSuggestions(String query) throws UnsupportedEncodingException {
- super.execute(getURL(query));
- }
-
- protected final String getURL(String busStopName) throws UnsupportedEncodingException {
- return "http://www.5t.torino.it/5t/trasporto/stop-lookup.jsp?action=search&stopShortName=" + URLEncoder.encode(busStopName, "utf-8");
- }
-
- /**
- * See http://www.5t.torino.it/5t/trasporto/stop-lookup.jsp?action=search&stopShortName=carducci
- *
- * @param responseInDOMFormatBecause5THaveAbsolutelyNoIdeaWhatJSONWas
- * @Override
- */
- protected void onPostExecute(String responseInDOMFormatBecause5THaveAbsolutelyNoIdeaWhatJSONWas) {
- ArrayList busStops = new ArrayList();
-
- if (responseInDOMFormatBecause5THaveAbsolutelyNoIdeaWhatJSONWas == null) {
- onReceivedBusStopNames(null, ERROR_EMPTY_DOM);
- return;
- }
-
- Document doc = Jsoup.parse(responseInDOMFormatBecause5THaveAbsolutelyNoIdeaWhatJSONWas);
-
- // Find bus stops
- Elements lis = doc.getElementsByTag("li");
- for(Element li : lis) {
- Elements spans = li.getElementsByTag("span");
-
- BusStop busStop;
-
- // busStopID
- try {
- busStop = new BusStop(spans.eq(0).text());
- } catch(Exception e) {
- Log.e("Suggestions", "Empty busStopID");
- onReceivedBusStopNames(null, ERROR_DOM);
- return;
- }
-
- // busStopName
- try {
- busStop.setBusStopName(spans.eq(1).text());
- } catch(Exception e) {
- Log.e("Suggestions", "Empty busStopName");
- onReceivedBusStopNames(null, ERROR_DOM);
- return;
- }
-
- // busStopLocation
- try {
- busStop.setBusStopLocality(spans.eq(2).text());
- } catch(Exception e) {
- Log.e("Suggestions", "Empty busStopLocation");
- onReceivedBusStopNames(null, ERROR_DOM);
- return;
- }
-
- busStops.add( busStop );
- }
-
- onReceivedBusStopNames(
- busStops.toArray(new BusStop[busStops.size()]),
- ERROR_NONE
- );
- }
-
- /**
- * Overload this!
- *
- * @param busStops Suggestions
- * @param status Error status if any
- */
- public void onReceivedBusStopNames(BusStop[] busStops, int status) {
- // Do something here
- }
-}
\ No newline at end of file
diff --git a/src/it/reyboz/bustorino/middleware/UserDB.java b/src/it/reyboz/bustorino/middleware/UserDB.java
index fa1b385..12a49b5 100644
--- a/src/it/reyboz/bustorino/middleware/UserDB.java
+++ b/src/it/reyboz/bustorino/middleware/UserDB.java
@@ -1,200 +1,217 @@
/*
BusTO ("backend" components)
Copyright (C) 2016 Ludovico Pavesi
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
*/
package it.reyboz.bustorino.middleware;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import it.reyboz.bustorino.backend.Stop;
public class UserDB extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "user.db";
private final Context c; // needed during upgrade
private static String[] usernameColumnNameAsArray = {"username"};
+ private static String[] getFavoritesColumnNamesAsArray = {"ID", "standardname", "username"};
public UserDB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.c = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
// exception intentionally left unhandled
db.execSQL("CREATE TABLE favorites (ID TEXT PRIMARY KEY NOT NULL, standardname TEXT, username TEXT)");
if(OldDB.doesItExist(this.c)) {
upgradeFromOldDatabase();
}
}
private void upgradeFromOldDatabase() {
OldDB old;
try {
old = new OldDB(this.c);
} catch(IllegalStateException e) {
// can't create database => it doesn't really exist, no matter what doesItExist() says
return;
}
int ver = old.getOldVersion();
/* version 8 was the previous version, OldDB "upgrades" itself to 1337 but unless the app
* has crashed midway through the upgrade and the user is retrying, that should never show
* up here. And if it does, try to recover favorites anyway.
* Versions < 8 already got dropped during the update process, so let's do the same.
*/
if(ver >= 8) {
ArrayList ID = new ArrayList<>();
ArrayList name = new ArrayList<>();
ArrayList username = new ArrayList<>();
int len;
int len2;
try {
Cursor c = old.getReadableDatabase().rawQuery("SELECT busstop_ID, busstop_name, busstop_username FROM busstop WHERE busstop_isfavorite = 1 ORDER BY busstop_name ASC", new String[] {});
int zero = c.getColumnIndex("busstop_ID");
int one = c.getColumnIndex("busstop_name");
int two = c.getColumnIndex("busstop_username");
while(c.moveToNext()) {
ID.add(c.getString(zero));
if(c.getString(one).length() <= 0) {
name.add(null);
} else {
name.add(c.getString(one));
}
if(c.getString(two).length() <= 0) {
username.add(null);
} else {
username.add(c.getString(two));
}
}
c.close();
old.close();
} catch(Exception ignored) {
// there's no hope, go ahead and nuke old database.
}
len = ID.size();
len2 = name.size();
if(len2 < len) {
len = len2;
}
len2 = username.size();
if(len2 < len) {
len = len2;
}
if (len > 0) {
SQLiteDatabase newdb = this.getWritableDatabase();
newdb.beginTransaction();
try {
for (int i = 0; i < len; i++) {
newdb.rawQuery("INSERT INTO favorites(ID, standardname, username) VALUES (?, ?, ?)", new String[]{ID.get(i), name.get(i), username.get(i)});
}
newdb.setTransactionSuccessful();
} finally {
newdb.endTransaction();
}
newdb.close();
}
}
if(!OldDB.destroy(this.c)) {
// TODO: notify user somehow?
Log.e("UserDB", "Failed to delete old database, you should really uninstall and reinstall the app. Unfortunately I have no way to tell the user.");
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// nothing to do yet
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// nothing to do yet
}
/**
* Gets stop name set by the user.
*
* @param db readable database
* @param stopID stop ID
* @return name set by user, or null if not set\not found
*/
public static String getStopUserName(SQLiteDatabase db, String stopID) {
String username = null;
try {
Cursor c = db.query("favorites", usernameColumnNameAsArray, "ID = ?", new String[] {stopID}, null, null, null, null);
if(c.moveToNext()) {
username = c.getString(c.getColumnIndex("username"));
}
c.close();
} catch(SQLiteException ignored) {}
return username;
}
public static List getFavorites(SQLiteDatabase db) {
List l = new ArrayList<>();
- // TODO: implement
- l.add(new Stop("TEST asd", "123", null, null, null));
- l.add(new Stop("TEST lel", "456", null, null, null));
- l.add(new Stop("asdasdasd asdsaad", "67", null, null, null));
+ try {
+ Cursor c = db.query("favorites", getFavoritesColumnNamesAsArray, null, null, null, null, null, null);
+ int colID = c.getColumnIndex("ID");
+ int colStandard = c.getColumnIndex("standardname");
+ int colUser = c.getColumnIndex("username");
+
+ if(c.moveToNext()) {
+ String name = c.getString(colUser);
+ if(name == null || name.length() <= 0) {
+ l.add(new Stop(c.getString(colStandard), c.getString(colID), null, null, null));
+ } else {
+ l.add(new Stop(name, c.getString(colID), null, null, null));
+ }
+ }
+
+ c.close();
+ } catch(SQLiteException ignored) {}
return l;
}
public boolean addOrUpdate(Stop s, SQLiteDatabase db) {
- Cursor c;
String username;
username = getStopUserName(db, s.ID);
- String[] arr = {s.ID, s.getStopName(), username};
- // UPSERT.
try {
- db.rawQuery("INSERT OR IGNORE INTO favorites(ID, standardname, username) VALUES (?, ?, ?)", arr).close();
- db.rawQuery("UPDATE favorites SET standardname = ? WHERE ID = ?", new String[]{arr[1], arr[0]}).close();
+ if(username == null) {
+ db.rawQuery("INSERT INTO favorites(ID, standardname, username) VALUES (?, ?, null)", new String[] {s.ID, s.getStopName()}).close();
+ } else {
+ db.rawQuery("INSERT INTO favorites(ID, standardname, username) VALUES (?, ?, ?)", new String[] {s.ID, s.getStopName(), username}).close();
+ }
+ // UPSERT.
+ // standardname is the only field that could have changed...
+ db.rawQuery("UPDATE favorites SET standardname = ? WHERE ID = ?", new String[]{s.getStopName(), s.ID}).close();
} catch(SQLiteException e) {
return false;
}
return true;
}
}