Android 记事本NotePad

起初接触Android的时候用Eclipse写的小应用,后面手动移植到了Android Studio中,可以新建,查看,删除便签等,今天整理一下代码,完整的代码可以在我的GitHub上看到,链接在文末。


DbHelper:

package com.zms.notepad;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by AlexZhou on 2015/2/3.
 * 11:12
 */
public class NoteDbHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 2;
    private static final String DATABASE_NAME = "notes_db";

    private static final String NOTE_TABLE_NAME = "note";
    private static final String NOTE_COL_ID = "_id";
    private static final String NOTE_COL_TITLE = "title";
    private static final String NOTE_COL_CONTENT = "content";
    private static final String NOTE_COL_CREATED = "created";
    private static final String NOTE_COL_MODIFIED = "modified";

    private static final String[] NOTE_COL_PROJECTION = new String[] {
            NOTE_COL_ID,
            NOTE_COL_TITLE,
            NOTE_COL_CONTENT,
            NOTE_COL_CREATED,
            NOTE_COL_MODIFIED
    };

    public NoteDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Create table
    @Override
    public void onCreate(SQLiteDatabase db) {
        String createNoteTableSql = "CREATE TABLE " + NOTE_TABLE_NAME + " ("
                + NOTE_COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + NOTE_COL_TITLE
                + " TEXT," + NOTE_COL_CONTENT + " TEXT," + NOTE_COL_CREATED
                + " INTEGER," + NOTE_COL_MODIFIED + " INTEGER" + ");";
        db.execSQL(createNoteTableSql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + NOTE_TABLE_NAME);

        // Create tables again
        onCreate(db);
    }

    // Add new note
    public int addNote(Note note) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(NOTE_COL_TITLE, note.getTitle());
        values.put(NOTE_COL_CONTENT, note.getContent());
        values.put(NOTE_COL_CREATED, note.getCreated());
        values.put(NOTE_COL_MODIFIED, note.getModified());

        // Insert to database
        long rowId = db.insert(NOTE_TABLE_NAME, null, values);

        // Close the database
        db.close();

        return (int) rowId;
    }

    // Get one note
    public Note getNote(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(NOTE_TABLE_NAME, NOTE_COL_PROJECTION,
                NOTE_COL_ID + "=?", new String[] { String.valueOf(id) }, null,
                null, null, null);

        if (cursor != null)
            cursor.moveToFirst();

        Note note = new Note(cursor.getInt(0), cursor.getString(1),
                cursor.getString(2), cursor.getLong(3), cursor.getLong(4));

        return note;
    }

    // Get all notes
    public List getAllNotes() {
        List noteList = new ArrayList();
        String selectQuery = "SELECT * FROM " + NOTE_TABLE_NAME;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Note note = new Note(cursor.getInt(0), cursor.getString(1),
                        cursor.getString(2), cursor.getLong(3),
                        cursor.getLong(4));
                noteList.add(note);
            } while (cursor.moveToNext());
        }

        // return contact list
        return noteList;
    }

    public Cursor getAllNotesCursor() {
        String selectQuery = "SELECT * FROM " + NOTE_TABLE_NAME;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        return cursor;
    }

    public int updateNote(Note note) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(NOTE_COL_TITLE, note.getTitle());
        values.put(NOTE_COL_CONTENT, note.getContent());
        values.put(NOTE_COL_CREATED, note.getCreated());
        values.put(NOTE_COL_MODIFIED, note.getModified());

        return db.update(NOTE_TABLE_NAME, values,
                NOTE_COL_ID + "=?", new String[] { String.valueOf(note.getId()) });
    }

    public void deleteNote(int noteId) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(NOTE_TABLE_NAME, NOTE_COL_ID + "=?",new String[] { String.valueOf(noteId) } );
        db.close();
    }

    public void deleteAllNotes() {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(NOTE_TABLE_NAME, null, null);
        db.close();
    }
}

新建和修改便签:

package com.zms.notepad;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Created by AlexZhou on 2015/2/3.
 * 11:14
 */
public class NoteNew extends Activity {
    private EditText etTitle;        //便签标题
    private EditText etContent;    //便签内容
    private Button btnCancel;
    private Button btnSave;
    private int _noteId;        //便签ID
    private NoteDbHelper _db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.note_new);
        etTitle = (EditText) findViewById(R.id.etTitle);
        etContent = (EditText) findViewById(R.id.etContent);
        btnCancel = (Button) findViewById(R.id.btnCancel);
        btnSave = (Button) findViewById(R.id.btnSave);

        btnCancel.setOnClickListener(new OnClickListenerImp());
        btnSave.setOnClickListener(new OnClickListenerImp());
        _db = new NoteDbHelper(this);
        Intent intent = getIntent();
        _noteId = intent.getIntExtra(NoteList.EXTRA_NOTE_ID, -1);
        if (_noteId > 0) {
            Note note = _db.getNote(_noteId);
            etTitle.setText(note.getTitle());
            etContent.setText(note.getContent());
        }
    }

    private class OnClickListenerImp implements View.OnClickListener {
        @Override
        public void onClick(View v) {

            if (v == btnCancel) {
                Toast.makeText(NoteNew.this, "天启提示:放弃新建便签", Toast.LENGTH_SHORT).show();
                finish();
            } else if (v == btnSave) {
                String titleVoid = etTitle.getText().toString();
                String contentVoid = etContent.getText().toString();
                if (titleVoid.equals("") || contentVoid.equals("")) {
                    Toast.makeText(NoteNew.this, "天启提示:标题或内容为空", Toast.LENGTH_SHORT).show();
                } else {
                    ToDatabase();    //插入数据库
                    Toast.makeText(NoteNew.this, "天启提示:便签保存成功", Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.note_new_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_exit) {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            android.os.Process.killProcess(android.os.Process.myPid());
            return true;
        } else if (id == R.id.action_about) {
            Intent intent = new Intent(this, About.class);
            startActivity(intent);
            return true;
        }
        return super.onOptionsItemSelected(item);

    }

    public final int ToDatabase() {
        String title = etTitle.getText().toString();
        String content = etContent.getText().toString();
        int newNoteId = -1;
        if (_noteId > 0) {
            Note note = _db.getNote(_noteId);
            note.setTitle(title);
            note.setContent(content);
            note.setModified(Long.valueOf(System.currentTimeMillis()));
            _db.updateNote(note);
        } else {
            Note newNote = new Note(title, content);
            newNoteId = _db.addNote(newNote);
        }
        return newNoteId;
    }
}


查看便签:

package com.zms.notepad;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;


public class Main extends ActionBarActivity {

    private ImageView ivLogo;
    private Button btnView;
    private Button btnNew;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ivLogo = (ImageView) findViewById(R.id.ivLogo);
        btnView = (Button) findViewById(R.id.btnView);
        btnNew = (Button) findViewById(R.id.btnNew);

        btnView.setOnClickListener(new OnClickListenerImp());
        btnNew.setOnClickListener(new OnClickListenerImp());
        ivLogo.setAlpha(50);     //Alpha 0-255,设置主页Logo的透明度
    }

    private class OnClickListenerImp implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if (v == btnView) {
                Intent intent = new Intent(Main.this, NoteList.class);
                startActivity(intent);
            } else if (v == btnNew) {
                Intent intent = new Intent(Main.this, NoteNew.class);
                startActivity(intent);
            }
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();
        if (id == R.id.action_about) {
            //点击菜单兰“关于”按钮后触发
            Intent intent = new Intent(this, About.class);
            startActivity(intent);
            return true;
        } else if (id == R.id.action_exit) {
            //点击菜单兰“退出”按钮后触发
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            android.os.Process.killProcess(android.os.Process.myPid());
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}

转载请注明出处:周木水的CSDN博客 http://blog.csdn.net/zhoumushui


你可能感兴趣的:(Android)