Skip to content

Instantly share code, notes, and snippets.

@ChrisRisner
Created August 31, 2012 06:47
Show Gist options
  • Save ChrisRisner/3549696 to your computer and use it in GitHub Desktop.
Save ChrisRisner/3549696 to your computer and use it in GitHub Desktop.
Todos Part two
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.msdpe.mymobileservice"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".TodoListActivity"
android:label="@string/title_activity_todo_list" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".TodosFetchService" />
</application>
</manifest>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/lblTodoText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="24dp"
android:text="ToDo Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/txtTodoText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/lblTodoText"
android:layout_marginTop="26dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="@+id/btnSaveTodo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/txtTodoText"
android:text="Save ToDo" />
<Button
android:id="@+id/btnMarkTodoComplete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/txtTodoText"
android:text="Mark ToDo Complete" />
</RelativeLayout>
@NotThreadSafe
public class HttpPatch extends HttpEntityEnclosingRequestBase {
public final static String METHOD_NAME = "PATCH";
public HttpPatch() {
super();
}
public HttpPatch(final URI uri) {
super();
setURI(uri);
}
public HttpPatch(final String uri) {
super();
setURI(URI.create(uri));
}
@Override
public String getMethod() {
return METHOD_NAME;
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case (R.id.menu_add_todo):
Intent todoDetailsIntent = new Intent(getApplicationContext(),
TodoDetailsActivity.class);
todoDetailsIntent.putExtra("AddingNewTodo", true);
startActivityForResult(todoDetailsIntent, 1);
return true;
case (R.id.menu_refresh):
startTodoFetchService();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
startTodoFetchService();
}
else
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mReceiver = new ServiceResultReceiver(new Handler());
mReceiver.setReceiver(this);
startTodoFetchService();
getListView().setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Convert the tapped view into a TextView
TextView tv = (TextView) view;
// Load the details intent for this specific slug
Intent todoDetailsIntent = new Intent(getApplicationContext(),
TodoDetailsActivity.class);
todoDetailsIntent.putExtra("TodoText", tv.getText().toString());
todoDetailsIntent.putExtra("AddingNewTodo", false);
try {
for (JSONObject todoItem : mTodos) {
if (todoItem.getString("text").equals(
tv.getText().toString())) {
todoDetailsIntent.putExtra("TodoId", todoItem.getInt("id"));
}
}
} catch (Exception ex) {
Log.e("TodoListActivity", ex.getMessage());
}
startActivityForResult(todoDetailsIntent, 1);
}
});
}
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_add_todo"
android:title="Add ToDo"
android:orderInCategory="100"
android:showAsAction="never" />
<item android:id="@+id/menu_refresh"
android:title="Refresh"
android:orderInCategory="100"
android:showAsAction="never" />
<item android:id="@+id/menu_settings"
android:title="@string/menu_settings"
android:orderInCategory="100"
android:showAsAction="never" />
</menu>
protected void saveTodo() {
new SaveTodoTask(this).execute(mTxtTodoText.getText().toString());
}
private class SaveTodoTask extends AsyncTask<String, Void, String> {
private Activity mContext;
public SaveTodoTask(Activity activity) {
mContext = activity;
}
@Override
protected String doInBackground(String... params) {
String todoText = params[0];
JSONObject jsonUrl = new JSONObject();
try {
jsonUrl.put("complete", "false");
jsonUrl.put("text", todoText);
} catch (JSONException e) {
Log.e("TodoDetailsActivity",
"Error creating JSON object: " + e.getMessage());
}
Log.i("TodoDetailsActivity", "JSON: " + jsonUrl.toString());
HttpURLConnection urlConnection = null;
try {
URL url = new URL(Constants.kAddTodoUrl);
urlConnection = (HttpURLConnection) url//
.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
urlConnection.addRequestProperty("Content-Type",
"application/json");
urlConnection.addRequestProperty("ACCEPT", "application/json");
urlConnection.addRequestProperty("X-ZUMO-APPLICATION",
Constants.kMobileServiceAppId);
// Write JSON to Server
DataOutputStream wr = new DataOutputStream(
urlConnection.getOutputStream());
wr.writeBytes(jsonUrl.toString());
wr.flush();
wr.close();
// Get response code
int response = urlConnection.getResponseCode();
// Read response
InputStream inputStream = new BufferedInputStream(
urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
StringBuilder stringBuilderResult = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilderResult.append(line);
}
if (response == 201)
return "SUCCESS";
return "FAIL";
} catch (IOException e) {
Log.e("TodoDetailsActivity", "IO Exeception: " + e.getMessage());
e.printStackTrace();
return "IOERROR";
} finally {
urlConnection.disconnect();
}
}
@Override
protected void onPostExecute(String status) {
// Do something with result
if (status.equals("SUCCESS")) {
Toast.makeText(getApplicationContext(),
"Todo Created Successfully", Toast.LENGTH_SHORT).show();
mContext.finishActivity(1);
finish();
} else {
Toast.makeText(getApplicationContext(),
"There was an error creating the Todo: " + status,
Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todo_details);
// Get references to controls on layout
mBtnSaveTodo = (Button) findViewById(R.id.btnSaveTodo);
mBtnMarkTodoComplete = (Button) findViewById(R.id.btnMarkTodoComplete);
mLblTodoText = (TextView) findViewById(R.id.lblTodoText);
mTxtTodoText = (EditText) findViewById(R.id.txtTodoText);
// Get extra data from intent
Intent intent = getIntent();
mIsAddingNewTodo = intent.getBooleanExtra("AddingNewTodo", false);
if (mIsAddingNewTodo) {
mBtnMarkTodoComplete.setVisibility(View.GONE);
} else {
mBtnSaveTodo.setVisibility(View.GONE);
mTodoText = intent.getStringExtra("TodoText");
mTodoId = intent.getIntExtra("TodoId", 0);
mTxtTodoText.setText(mTodoText);
mTxtTodoText.setFocusable(false);
}
mBtnMarkTodoComplete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
markTodoComplete();
}
});
mBtnSaveTodo.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
saveTodo();
}
});
}
private Button mBtnSaveTodo;
private Button mBtnMarkTodoComplete;
private TextView mLblTodoText;
private EditText mTxtTodoText;
private boolean mIsAddingNewTodo;
private String mTodoText;
private int mTodoId;
protected void markTodoComplete() {
new MarkTodoCompleteTask(this).execute(mTodoId, mTodoText);
}
private class MarkTodoCompleteTask extends AsyncTask<Object, Void, String> {
private Activity mContext;
public MarkTodoCompleteTask(Activity activity) {
mContext = activity;
}
@Override
protected String doInBackground(Object... params) {
int todoId = (Integer) params[0];
String todoText = (String) params[1];
try {
JSONObject jsonUrl = new JSONObject();
jsonUrl.put("complete", "true");
jsonUrl.put("text", todoText);
jsonUrl.put("id", todoId);
HttpClient httpClient = new DefaultHttpClient();
HttpPatch httpPatch = new HttpPatch(Constants.kUpdateTodoUrl + todoId);
httpPatch.addHeader("Content-Type", "application/json");
httpPatch.addHeader("ACCEPT", "application/json");
httpPatch.addHeader("X-ZUMO-APPLICATION", Constants.kMobileServiceAppId);
StringEntity body = new StringEntity(jsonUrl.toString());
body.setContentType("application/json");
httpPatch.setEntity(body);
org.apache.http.HttpResponse response = httpClient
.execute(httpPatch);
if (response.getStatusLine().getStatusCode() == 200)
return "SUCCESS";
else
return response.getStatusLine().getStatusCode() + "";
} catch (Exception ex) {
return ex.getMessage();
}
}
@Override
protected void onPostExecute(String status) {
if (status.equals("SUCCESS")) {
Toast.makeText(getApplicationContext(),
"Todo updated Successfully", Toast.LENGTH_SHORT).show();
mContext.finishActivity(1);
finish();
} else {
Toast.makeText(getApplicationContext(),
"There was an error updating the Todo: " + status,
Toast.LENGTH_SHORT).show();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment