技术开发 频道

android之notepad

  【IT168 技术文档】这个实例主要是对SDK中的Notepadv2Solution的修改和完善,因为本人在使用该sample发现一些错误和缺陷,主要是空指针异常。(1)Notepadv1.java:

package com.google.android.demo.notepad1;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.Menu.Item;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class Notepadv1 extends ListActivity {
 public static final int INSERT_ID = Menu.FIRST;
 private static final int EXIT_ID = 0;
 private static final int DELETE_ID = Menu.FIRST + 1;
 private static final int ACTIVITY_EDIT = 1;
 private static final int ACTIVITY_CREATE = 0;
 private NotesDbAdapter mDbHelper;
 private Cursor c;
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.notepad_list);
        mDbHelper = new NotesDbAdapter(this);
        mDbHelper.open();
        fillData();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
     boolean result = super.onCreateOptionsMenu(menu);
        menu.add(0, INSERT_ID, R.string.menu_insert);
        menu.add(0, EXIT_ID, R.string.exit_notes);
        menu.add(0, DELETE_ID, R.string.menu_delete);
        return result;
    }
    @Override
    public boolean onOptionsItemSelected(Item item) {
     switch (item.getId()) {
        case INSERT_ID:
            createNote();
            return true;
        case EXIT_ID:
         finish();
         return true;
        case DELETE_ID:
         mDbHelper.deleteNote(getListView().getSelectedItemId());
         fillData();
         return true;
        }
        return super.onOptionsItemSelected(item);
    }
   
    private void createNote() {
     Intent i = new Intent(this, NoteEdit.class);
        startSubActivity(i, ACTIVITY_CREATE);
    }
   
    private void fillData() {
        // Get all of the notes from the database and create the item list
        c = mDbHelper.fetchAllNotes();
        startManagingCursor(c);
        String[] from = new String[] { NotesDbAdapter.KEY_TITLE };
        int[] to = new int[] { R.id.text1 };
       
        // Now create an array adapter and set it to display using our row
        SimpleCursorAdapter notes =
            new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to);
        setListAdapter(notes);
    }
   
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
     super.onListItemClick(l, v, position, id);
       
        c.moveTo(position);
        Intent i = new Intent(this, NoteEdit.class);
        i.putExtra(NotesDbAdapter.KEY_ROWID, id);
        i.putExtra(NotesDbAdapter.KEY_TITLE, c.getString(
                c.getColumnIndex(NotesDbAdapter.KEY_TITLE)));
        i.putExtra(NotesDbAdapter.KEY_BODY, c.getString(
                c.getColumnIndex(NotesDbAdapter.KEY_BODY)));
        startSubActivity(i, ACTIVITY_EDIT);
    }
   
    @Override
    protected void onActivityResult(int requestCode, int resultCode, String data, Bundle extras) {
        super.onActivityResult(requestCode, resultCode, data, extras);
       
        switch(requestCode) {
        case ACTIVITY_CREATE:
         if(extras == null)
          break;
         
            String title = extras.getString(NotesDbAdapter.KEY_TITLE);
            String body = extras.getString(NotesDbAdapter.KEY_BODY);
           
            mDbHelper.createNote(title, body);
            fillData();
          
            break;
        case ACTIVITY_EDIT:
         if(extras == null)
          break;
            Long rowId = extras.getLong(NotesDbAdapter.KEY_ROWID);
            if (rowId != null) {
                String editTitle = extras.getString(NotesDbAdapter.KEY_TITLE);
                String editBody = extras.getString(NotesDbAdapter.KEY_BODY);
                mDbHelper.updateNote(rowId, editTitle, editBody);
            }
            fillData();
            break;
        }
    }
}

说明:
此activity主要是将为创建notepad做前期工作的,此外还做收尾工作,将从后台接受过来的数据显示出来。
图示:

(2)NoteEdit.java:

package com.google.android.demo.notepad1;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class NoteEdit extends Activity {
 private EditText mTitleText;
    private EditText mBodyText;
    private Long mRowId;
    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.note_edit);        mTitleText = (EditText) findViewById(R.id.title);
        mBodyText = (EditText) findViewById(R.id.body);
     
        Button confirmButton = (Button) findViewById(R.id.confirm);
      
        mRowId = null;
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            String title = extras.getString(NotesDbAdapter.KEY_TITLE);
            String body = extras.getString(NotesDbAdapter.KEY_BODY);
            mRowId = extras.getLong(NotesDbAdapter.KEY_ROWID);
         
            if (title != null) {
                mTitleText.setText(title);
            }
            if (body != null) {
                mBodyText.setText(body);
            }
        }        confirmButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Bundle bundle = new Bundle();
              
                bundle.putString(NotesDbAdapter.KEY_TITLE, mTitleText.getText().toString());
                bundle.putString(NotesDbAdapter.KEY_BODY, mBodyText.getText().toString());
                if (mRowId != null) {
                    bundle.putLong(NotesDbAdapter.KEY_ROWID, mRowId);
                }
               
                setResult(RESULT_OK, null, bundle);
                finish();
            }
        });
    }
}
 
说明:
接受前台的命令,开始创建notepad,并将数据传递到前台。注意if (extras != null) 可以可以防止输入数据为空时的空指针异常情况。
图示: 
(3)NotesDbAdapter.java:
 

package com.google.android.demo.notepad1;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import java.io.FileNotFoundException;

public class NotesDbAdapter {
    public static final String KEY_TITLE="title";
    public static final String KEY_BODY="body";
    public static final String KEY_ROWID="_id";
    
    
    private static final String DATABASE_CREATE =
        "create table notes (_id integer primary key autoincrement, "
            + "title text not null, body text not null);";
    private static final String DATABASE_NAME = "data";
    private static final String DATABASE_TABLE = "notes";
    private static final int DATABASE_VERSION = 2;
    private SQLiteDatabase mDb;
    private final Context mCtx;
    
    public NotesDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }
    
       public NotesDbAdapter open() throws SQLException {
        try {
            mDb = mCtx.openDatabase(DATABASE_NAME, null);
        } catch (FileNotFoundException e) {
            try {
                mDb =
                    mCtx.createDatabase(DATABASE_NAME, DATABASE_VERSION, 0,
                        null);
                mDb.execSQL(DATABASE_CREATE);
            } catch (FileNotFoundException e1) {
                throw new SQLException("Could not create database");
            }
        }
        return this;
    }
    public void close() {
        mDb.close();
    }
    
    public long createNote(String title, String body) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_TITLE, title);
        initialValues.put(KEY_BODY, body);
        return mDb.insert(DATABASE_TABLE, null, initialValues);
    }
    
    public boolean deleteNote(long rowId) {
        return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }
   
    public Cursor fetchAllNotes() {
        return mDb.query(DATABASE_TABLE, new String[] {
                KEY_ROWID, KEY_TITLE, KEY_BODY}, null, null, null, null, null);
    }
    
    public Cursor fetchNote(long rowId) throws SQLException {
        Cursor result = mDb.query(true, DATABASE_TABLE, new String[] {
                KEY_ROWID, KEY_TITLE, KEY_BODY}, KEY_ROWID + "=" + rowId, null, null,
                null, null);
        if ((result.count() == 0) || !result.first()) {
            throw new SQLException("No note matching ID: " + rowId);
        }
        return result;
    }
    
    public boolean updateNote(long rowId, String title, String body) {
        ContentValues args = new ContentValues();
        args.put(KEY_TITLE, title);
        args.put(KEY_BODY, body);
        return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
}

说明:
数据库和数据库操作在里面。
 
(4)notepad_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="@string/no_notes"/>
       
</LinearLayout>
 
(5)note_edi.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="horizontal"
 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" />
<EditText android:id="@+id/title"
 android:layout_width="wrap_content"
 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="wrap_content"
 android:layout_weight="1"
 android:scrollbars="vertical" />
 
<Button android:id="@+id/confirm"
 android:text="@string/confirm"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" />
</LinearLayout>
 
(6)notes_row.xml:
 
<?xml version="1.0" encoding="utf-8"?>
<TextView android:id="@+id/text1"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
 
(7)strings.xml:
 
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Notepad v1</string>
    <string name="no_notes">No Notes Yet</string>
    <string name="menu_insert">Add Item</string>
    <string name="exit_notes">Exit Notepad</string>
    <string name="menu_delete">Delete Item</string>
    <string name="title">Title</string>
    <string name="body">Body</string>
    <string name="confirm">Confirm</string>
    <string name="edit_note">Edit Note</string>
</resources>

(8)AndroidManifest.xml:
 
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.google.android.demo.notepad1">
    <application android:icon="@drawable/icon">
        <activity android:name=".Notepadv1" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".NoteEdit"></activity>
    </application>
</manifest>

 

0
相关文章