Skip to content

Instantly share code, notes, and snippets.

@ChrisRisner
Created August 31, 2012 05:55
Show Gist options
  • Save ChrisRisner/3549489 to your computer and use it in GitHub Desktop.
Save ChrisRisner/3549489 to your computer and use it in GitHub Desktop.
Android Todos Part 1
public class Constants {
public static final String kGetTodosUrl = "https://yoursubdomain.azure-mobile.net/tables/TodoItem?$filter=(complete%20eq%20false)";
public static final String kAddTodoUrl = "https://yoursubdomain.azure-mobile.net/tables/TodoItem";
public static final String kUpdateTodoUrl = "https://yoursubdomain.azure-mobile.net/tables/TodoItem/";
public static final String kMobileServiceAppId = "YourAppKey";
}
private void fetchTodos(Intent intent) {
boolean fetchFailed = false;
JSONObject[] todos = null;//
try {
URL url = new URL(Constants.kGetTodosUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection
.addRequestProperty("Content-Type", "application/json");
urlConnection.addRequestProperty("ACCEPT", "application/json");
urlConnection.addRequestProperty("X-ZUMO-APPLICATION",
Constants.kMobileServiceAppId);
try {
InputStream in = new BufferedInputStream(
urlConnection.getInputStream());
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(in));
StringBuilder stringBuilderResponse = new StringBuilder();
String line;
while ((line = bufferReader.readLine()) != null) {
stringBuilderResponse.append(line);
}
JSONArray jsonArray = new JSONArray(
stringBuilderResponse.toString());
todos = new JSONObject[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
todos[i] = jsonArray.getJSONObject(i);
}
} catch (Exception ex) {
Log.e("TodosFetchService", "Error getting JSON from Server: "+ ex.getMessage());
fetchFailed = true;
} finally {
urlConnection.disconnect();
}
} catch (Exception ex) {
Log.e("TodosFetchService", "Error opening HTTP Connection: " + ex.getMessage());
fetchFailed = true;
}
// Provided a result receiver was sent in, send a response back
if (mReceiver != null) {
if (fetchFailed) {
mReceiver.send(STATUS_ERROR, Bundle.EMPTY);
this.stopSelf();
mReceiver.send(STATUS_FINISHED, Bundle.EMPTY);
} else {
Bundle bundle = new Bundle();
bundle.putBoolean(SERVICE_WAS_SUCCESS_KEY, true);
bundle.putSerializable("todos", todos);
mReceiver.send(STATUS_SUCCESS, bundle);
this.stopSelf();
mReceiver.send(STATUS_FINISHED, Bundle.EMPTY);
}
} else {
this.stopSelf();
}
}
@Override
public void onReceiveResult(int resultCode, Bundle resultBundle) {
switch (resultCode) {
case TodosFetchService.STATUS_RUNNING:
// Don't do anything, the service is running
break;
case TodosFetchService.STATUS_SUCCESS:
boolean wasSuccess = resultBundle
.getBoolean(TodosFetchService.SERVICE_WAS_SUCCESS_KEY);
if (wasSuccess) {
// Success, update the ListView
mTodos = (JSONObject[]) resultBundle.getSerializable("todos");
showTodosInListView(mTodos);
} else {
// Failure, show error message
Toast.makeText(
getApplicationContext(),
"There was an error fetching the URL data. Please try again later.",
Toast.LENGTH_LONG).show();
}
break;
case TodosFetchService.STATUS_FINISHED:
break;
case TodosFetchService.STATUS_ERROR:
// Error returned from service, show and error message
Toast.makeText(
getApplicationContext(),
"There was an error fetching the Todo data."
+ "Please try again later.", Toast.LENGTH_LONG)
.show();
break;
}
}
public class ServiceResultReceiver extends ResultReceiver {
private Receiver mReceiver;
public ServiceResultReceiver(Handler handler) {
super(handler);
}
public void setReceiver(Receiver receiver) {
mReceiver = receiver;
}
public interface Receiver {
public void onReceiveResult(int resultCode, Bundle resultBundle);
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultBundle) {
if (mReceiver != null) {
mReceiver.onReceiveResult(resultCode, resultBundle);
}
}
}
private void showTodosInListView(JSONObject[] mTodos2) {
try {
TreeSet<String> treeSetKeys = new TreeSet<String>();
for (int i = 0; i < mTodos2.length; i++) {
treeSetKeys.add(mTodos[i].getString("text"));
}
String[] keys = (String[]) treeSetKeys
.toArray(new String[treeSetKeys.size()]);
ArrayAdapter adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, keys);
setListAdapter(adapter);
} catch (Exception ex) {
Log.e("TodoListActivity", ex.getMessage());
}
}
private void startTodoFetchService() {
final Intent serviceIntent = new Intent(Intent.ACTION_SYNC, null,
getApplicationContext(), TodosFetchService.class);
// put the specifics for the submission service commands
serviceIntent.putExtra(TodosFetchService.RECEIVER_KEY, mReceiver);
serviceIntent.putExtra(TodosFetchService.COMMAND_KEY,
TodosFetchService.PERFORM_SERVICE_ACTIVITY);
// Start the service
startService(serviceIntent);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mReceiver = new ServiceResultReceiver(new Handler());
mReceiver.setReceiver(this);
startTodoFetchService();
}
public class TodoListActivity extends ListActivity implements
ServiceResultReceiver.Receiver {
private ServiceResultReceiver mReceiver;
private JSONObject[] mTodos;
public class TodosFetchService extends IntentService {
// Status Constants
public static final int STATUS_RUNNING = 0x1;
public static final int STATUS_FINISHED = 0x2;
public static final int STATUS_SUCCESS = 0x3;
public static final int STATUS_ERROR = 0x4;
// Command Constants
public static final int PERFORM_SERVICE_ACTIVITY = 0x5;
public static final String COMMAND_KEY = "service_command";
public static final String RECEIVER_KEY = "serivce_receiver";
public static final String SERVICE_WAS_SUCCESS_KEY = "service_was_success";
private ResultReceiver mReceiver;
public TodosFetchService() {
super("TodosFetchService");
}
public TodosFetchService(String name) {
super(name);
}
@Override
protected void onHandleIntent(Intent intent) {
this.mReceiver = intent.getParcelableExtra(RECEIVER_KEY);
int command = intent.getIntExtra(COMMAND_KEY, PERFORM_SERVICE_ACTIVITY);
if (this.mReceiver != null)
this.mReceiver.send(STATUS_RUNNING, Bundle.EMPTY);
switch (command) {
case PERFORM_SERVICE_ACTIVITY:
fetchTodos(intent);
break;
default:
if (this.mReceiver != null)
mReceiver.send(STATUS_FINISHED, Bundle.EMPTY);
}
this.stopSelf();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment