Diary app : ListActivity « UI « Android






Diary app

   
/*
 * Copyright (C) 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.savedInstanceState
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.eoeAndroid.contentProvider;

import android.app.ListActivity;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import com.eoeAndroid.contentProvider.Diary.DiaryColumns;

public class ActivityMain extends ListActivity {

  // 
  public static final int MENU_ITEM_INSERT = Menu.FIRST;
  // 
  public static final int MENU_ITEM_EDIT = Menu.FIRST + 1;
  public static final int MENU_ITEM_DELETE = Menu.FIRST + 2;

  private static final String[] PROJECTION = new String[] { DiaryColumns._ID,
      DiaryColumns.TITLE, DiaryColumns.CREATED };

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.diary_list);
    Intent intent = getIntent();
    if (intent.getData() == null) {
      intent.setData(DiaryColumns.CONTENT_URI);
    }
    Cursor cursor = managedQuery(getIntent().getData(), PROJECTION, null,
        null, DiaryColumns.DEFAULT_SORT_ORDER);

    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
        R.layout.diary_row, cursor, new String[] { DiaryColumns.TITLE,
            DiaryColumns.CREATED }, new int[] { R.id.text1,
            R.id.created });
    setListAdapter(adapter);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    menu.add(0, MENU_ITEM_INSERT, 0, R.string.menu_insert);
    return true;
  }

  @Override
  /*
   * menumenu
   */
  public boolean onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);
    final boolean haveItems = getListAdapter().getCount() > 0;
    if (haveItems) {
      // Item
      if (getListView().getSelectedItemId() > 0) {
        menu.removeGroup(1);
        Uri uri = ContentUris.withAppendedId(getIntent().getData(),
            getSelectedItemId());
        Intent intent = new Intent(null, uri);
        menu.add(1, MENU_ITEM_EDIT, 1, "").setIntent(intent);
        menu.add(1, MENU_ITEM_DELETE, 1, "");
      }

    }else{
      menu.removeGroup(1);
    }
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    // 
    case MENU_ITEM_INSERT:
      Intent intent0 = new Intent(this, ActivityDiaryEditor.class);
      intent0.setAction(ActivityDiaryEditor.INSERT_DIARY_ACTION);
      intent0.setData(getIntent().getData());
      startActivity(intent0);
      return true;
      // 
    case MENU_ITEM_EDIT:
      Intent intent = new Intent(this, ActivityDiaryEditor.class);
      intent.setData(item.getIntent().getData());
      intent.setAction(ActivityDiaryEditor.EDIT_DIARY_ACTION);
      startActivity(intent);
      return true;
      // 
    case MENU_ITEM_DELETE:
      Uri uri = ContentUris.withAppendedId(getIntent().getData(),
          getListView().getSelectedItemId());
      getContentResolver().delete(uri, null, null);
      renderListView();

    }
    return super.onOptionsItemSelected(item);
  }

  @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
    Uri uri = ContentUris.withAppendedId(getIntent().getData(), id);
    startActivity(new Intent(ActivityDiaryEditor.EDIT_DIARY_ACTION, uri));

  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode,
      Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    //renderListView();
  }

  private void renderListView() {
    Cursor cursor = managedQuery(getIntent().getData(), PROJECTION, null,
        null, DiaryColumns.DEFAULT_SORT_ORDER);

    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
        R.layout.diary_row, cursor, new String[] { DiaryColumns.TITLE,
            DiaryColumns.CREATED }, new int[] { R.id.text1,
            R.id.created });
    setListAdapter(adapter);
  }
}
package com.eoeAndroid.contentProvider;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.eoeAndroid.contentProvider.Diary.DiaryColumns;

public class ActivityDiaryEditor extends Activity {
  private static final String TAG = "Diary";
  public static final String EDIT_DIARY_ACTION = "com.ex09_2_contentProvider.ActivityDiaryEditor.EDIT_DIARY";
  public static final String INSERT_DIARY_ACTION = "com.ex09_2_contentProvider.ActivityDiaryEditor.action.INSERT_DIARY";

  /**
   * cursor
   */
  private static final String[] PROJECTION = new String[] { DiaryColumns._ID, // 0
      DiaryColumns.TITLE, DiaryColumns.BODY, // 1
  };

  private static final int STATE_EDIT = 0;
  private static final int STATE_INSERT = 1;

  private int mState;

  private Uri mUri;
  private Cursor mCursor;

  private EditText mTitleText;
  private EditText mBodyText;
  private Button confirmButton;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTheme(android.R.style.Theme_Black);
    final Intent intent = getIntent();
    final String action = intent.getAction();
    setContentView(R.layout.diary_edit);
    
    mTitleText = (EditText) findViewById(R.id.title);
    mBodyText = (EditText) findViewById(R.id.body);
    confirmButton = (Button) findViewById(R.id.confirm);

    if (EDIT_DIARY_ACTION.equals(action)) {// 
      mState = STATE_EDIT;
      mUri = intent.getData();
      mCursor = managedQuery(mUri, PROJECTION, null, null, null);
      mCursor.moveToFirst();
      String title = mCursor.getString(1);
      mTitleText.setTextKeepState(title);
      String body = mCursor.getString(2);
      mBodyText.setTextKeepState(body);
      setResult(RESULT_OK, (new Intent()).setAction(mUri.toString()));
      setTitle("");
    } else if (INSERT_DIARY_ACTION.equals(action)) {// 
      mState = STATE_INSERT;
      setTitle("");
    } else {
      Log.e(TAG, "no such action error");
      finish();
      return;
    }

    confirmButton.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        if (mState == STATE_INSERT) {
          insertDiary();
        } else {
          updateDiary();
        }
        Intent mIntent = new Intent();
        setResult(RESULT_OK, mIntent);
        finish();
      }

    });

  }

  private void insertDiary() {
    String title = mTitleText.getText().toString();
    String body = mBodyText.getText().toString();
    ContentValues values = new ContentValues();
    values.put(Diary.DiaryColumns.CREATED, DiaryContentProvider
        .getFormateCreatedDate());
    values.put(Diary.DiaryColumns.TITLE, title);
    values.put(Diary.DiaryColumns.BODY, body);
    getContentResolver().insert(Diary.DiaryColumns.CONTENT_URI, values);

  }

  private void updateDiary() {
    String title = mTitleText.getText().toString();
    String body = mBodyText.getText().toString();
    ContentValues values = new ContentValues();
    values.put(Diary.DiaryColumns.CREATED, DiaryContentProvider
        .getFormateCreatedDate());
    values.put(Diary.DiaryColumns.TITLE, title);
    values.put(Diary.DiaryColumns.BODY, body);
    getContentResolver().update(mUri, values,
        null, null);

  }
}


package com.eoeAndroid.contentProvider;

import android.net.Uri;
import android.provider.BaseColumns;


public final class Diary {
  // AUTHORITY ManifestproviderAUTHORITY
    public static final String AUTHORITY = "com.ex09_2_contentprovider.diarycontentprovider";

    private Diary() {}
    
    /**
     * Notes table
     */
    public static final class DiaryColumns implements BaseColumns {
        // This class cannot be instantiated
        private DiaryColumns() {}

        public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/diaries");


        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.diary";


        public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.google.diary";


        public static final String DEFAULT_SORT_ORDER = "created DESC";

        public static final String TITLE = "title";

        public static final String BODY = "body";

        public static final String CREATED = "created";


     
    }
}
package com.eoeAndroid.contentProvider;

import java.util.Calendar;
import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import com.eoeAndroid.contentProvider.Diary.DiaryColumns;

public class DiaryContentProvider extends ContentProvider {

  private static final String DATABASE_NAME = "database";
  private static final int DATABASE_VERSION = 3;
  private static final String DIARY_TABLE_NAME = "diary";

  private static final int DIARIES = 1;
  private static final int DIARY_ID = 2;

  private static final UriMatcher sUriMatcher;

  private static class DatabaseHelper extends SQLiteOpenHelper {

    DatabaseHelper(Context context) {
      super(context, DATABASE_NAME, null, DATABASE_VERSION);
      Log.i("jinyan", "DATABASE_VERSION=" + DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
      Log.i("jinyan", "onCreate(SQLiteDatabase db)");
      String sql = "CREATE TABLE " + DIARY_TABLE_NAME + " ("
          + DiaryColumns._ID + " INTEGER PRIMARY KEY,"
          + DiaryColumns.TITLE + " TEXT," + DiaryColumns.BODY
          + " TEXT," + DiaryColumns.CREATED + " TEXT" + ");";
      //
      sql ="CREATE TABLE " + DIARY_TABLE_NAME + " ("
      + DiaryColumns._ID + " INTEGER PRIMARY KEY,"
      + DiaryColumns.TITLE + " varchar(255)," + DiaryColumns.BODY
      + " TEXT," + DiaryColumns.CREATED + " TEXT" + ");";
      //
      Log.i("jinyan", "sql="+sql);
      db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      Log.i("jinyan",
          " onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)="
              + newVersion);
      db.execSQL("DROP TABLE IF EXISTS diary");
      onCreate(db);
    }
  }

  private DatabaseHelper mOpenHelper;

  static {
    sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    sUriMatcher.addURI(Diary.AUTHORITY, "diaries", DIARIES);
    sUriMatcher.addURI(Diary.AUTHORITY, "diaries/#", DIARY_ID);

  }

  @Override
  public boolean onCreate() {
    mOpenHelper = new DatabaseHelper(getContext());
    return true;
  }

  @Override
  public Cursor query(Uri uri, String[] projection, String selection,
      String[] selectionArgs, String sortOrder) {
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    switch (sUriMatcher.match(uri)) {
    case DIARIES:
      qb.setTables(DIARY_TABLE_NAME);
      break;

    case DIARY_ID:
      qb.setTables(DIARY_TABLE_NAME);
      qb.appendWhere(DiaryColumns._ID + "="
          + uri.getPathSegments().get(1));
      break;

    default:
      throw new IllegalArgumentException("Unknown URI " + uri);
    }

    String orderBy;
    if (TextUtils.isEmpty(sortOrder)) {
      orderBy = Diary.DiaryColumns.DEFAULT_SORT_ORDER;
    } else {
      orderBy = sortOrder;
    }

    SQLiteDatabase db = mOpenHelper.getReadableDatabase();
    Cursor c = qb.query(db, projection, selection, selectionArgs, null,
        null, orderBy);
    return c;
  }

  @Override
  public String getType(Uri uri) {
    switch (sUriMatcher.match(uri)) {
    case DIARIES:
      return DiaryColumns.CONTENT_TYPE;

    case DIARY_ID:
      return DiaryColumns.CONTENT_ITEM_TYPE;

    default:
      throw new IllegalArgumentException("Unknown URI " + uri);
    }
  }

  @Override
  public Uri insert(Uri uri, ContentValues initialValues) {
    if (sUriMatcher.match(uri) != DIARIES) {
      throw new IllegalArgumentException("Unknown URI " + uri);
    }

    ContentValues values;
    if (initialValues != null) {
      values = new ContentValues(initialValues);
    } else {
      values = new ContentValues();
    }

    if (values.containsKey(Diary.DiaryColumns.CREATED) == false) {
      values.put(Diary.DiaryColumns.CREATED, getFormateCreatedDate());
    }

    if (values.containsKey(Diary.DiaryColumns.TITLE) == false) {
      Resources r = Resources.getSystem();
      values.put(Diary.DiaryColumns.TITLE, r
          .getString(android.R.string.untitled));
    }

    if (values.containsKey(Diary.DiaryColumns.BODY) == false) {
      values.put(Diary.DiaryColumns.BODY, "");
    }

    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    long rowId = db.insert(DIARY_TABLE_NAME, DiaryColumns.BODY, values);
    if (rowId > 0) {
      Uri diaryUri = ContentUris.withAppendedId(
          Diary.DiaryColumns.CONTENT_URI, rowId);
      return diaryUri;
    }

    throw new SQLException("Failed to insert row into " + uri);
  }

  @Override
  public int delete(Uri uri, String where, String[] whereArgs) {
    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    String rowId = uri.getPathSegments().get(1);
    return db
        .delete(DIARY_TABLE_NAME, DiaryColumns._ID + "=" + rowId, null);

  }

  @Override
  public int update(Uri uri, ContentValues values, String where,
      String[] whereArgs) {
    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    String rowId = uri.getPathSegments().get(1);
    return db.update(DIARY_TABLE_NAME, values, DiaryColumns._ID + "="
        + rowId, null);

  }

  public static String getFormateCreatedDate() {
    Calendar calendar = Calendar.getInstance();
    String created = calendar.get(Calendar.YEAR) + ""
        + calendar.get(Calendar.MONTH) + ""
        + calendar.get(Calendar.DAY_OF_MONTH) + ""
        + calendar.get(Calendar.HOUR_OF_DAY) + ""
        + calendar.get(Calendar.MINUTE) + "";
    return created;
  }
}
//diary_edit.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical" android:layout_width="fill_parent"
  android:layout_height="fill_parent">

  <LinearLayout android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <TextView android:layout_width="wrap_content"
      android:layout_height="wrap_content" android:text="@string/title"
      android:padding="2px" />
    <EditText android:id="@+id/title"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content" android:layout_weight="1" />
  </LinearLayout>

  <TextView android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:text="@string/body" />
  <EditText android:id="@+id/body" android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:layout_weight="1"
    android:scrollbars="vertical" android:gravity="top" />

  <Button android:id="@+id/confirm" android:text="@string/confirm"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

</LinearLayout>

//diary_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content">

  <ListView android:id="@+id/android:list"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
  <TextView android:id="@+id/android:empty"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:text="" />
</LinearLayout>
//diary_row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/row"
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

  <TextView android:id="@+id/text1"
    android:layout_width="wrap_content" android:layout_height="30px"
    android:maxWidth="200dip" 
    android:textSize="22sp"
    android:layout_marginTop="10dip"
    android:text="??????" />
  <TextView android:id="@+id/created" android:layout_width="wrap_content"
    android:layout_height="35px" android:layout_alignParentRight="true"
    android:layout_marginLeft="10dip" 
    android:layout_marginTop="10dip"
    android:text="1999?12?3?" />

</RelativeLayout>

   
    
    
  








Related examples in the same category

1.A list view example where the data for the list comes from an array of strings.
2.A list view example where the data comes from a cursor.
3.Using ListActivity
4.SimpleCursorAdapter and ListActivity
5.Get ListActivity selected index
6.Multi-column ListActivity
7.A list view example with separators.
8.List item click event
9.Dynamic List item
10.Self Wrapper for List
11.Static text for List view
12.List selection event
13.Simple List single choice
14.To do list app
15.Scale listener
16.Weather List Widget
17.Demonstrates expandable lists backed by Cursors
18.Demonstrates expandable lists backed by a Simple Map-based adapter
19.Demonstrates the using a list view in transcript mode
20.Demonstrates how a list can avoid expensive operations during scrolls or flings.
21.Demonstrates how to write an efficient list adapter.
22.A list view where the last item the user clicked is placed in the "activated" state, causing its background to highlight.
23.Calculate the minimum and maximum values out of a list of doubles.
24.Bounded Linked List
25.Adapter that simply returns row views from a list.