简单笔记本应用实现

来源:互联网 发布:梦里花落知多少书包网 编辑:程序博客网 时间:2024/05/17 23:04

   笔记本应用简介,用户通过密码登陆该应用,用户可以修改密码,登陆后可以创建一个笔记,笔记由标题和内容组成,用户的密码和笔记将会保存到数据库中,笔记标题采用ListView来展示,并可修改,工程由4个类实现,一个帮助类,3个activity,Login(登陆),NoteList(主题),Edit(编辑记事).

 首先创建一个帮助类,增删改查

package com.pms.db;

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

public class DbHelper extends SQLiteOpenHelper {

 private final static String DATABASE_NAME = "note_db";  //数据库名
 private final static int DATABASE_VERSION = 1;   //版本号   
 
 private final static String TABLE_NAME = "notepad";
 public final static String NOTE_ID = "_id";
 public final static String NOTE_TITLE = "title";
 public final static String NOTE_CONTENT = "content";
 
 public final static String LOGIN_TABLE_NAME = "login";
 public final static String LOGIN_USER = "admin";
 public final static String LOGIN_PWD = "password";
 
 /*构造函数*/
 public DbHelper(Context context) {
  super(context, DATABASE_NAME, null, DATABASE_VERSION);
 }
 
 /*创建数据库*/
 @Override
 public void onCreate(SQLiteDatabase db) {
  String sql = "create table "+TABLE_NAME+" ("
  +NOTE_ID+" integer primary key autoincrement, "
  +NOTE_TITLE+" text, "
  +NOTE_CONTENT+" text )";
  db.execSQL(sql);
  
  sql = "create table "+LOGIN_TABLE_NAME+" ("
  +LOGIN_USER+" text, "
  +LOGIN_PWD+" text )";
  db.execSQL(sql);
 }

 /*更新数据库*/
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  String sql = "drop table if exists "+TABLE_NAME;
  db.execSQL(sql); 
  
  sql = "drop table if exists "+LOGIN_TABLE_NAME;
  db.execSQL(sql);
  onCreate(db);
 }
 /**插入密码
  * @param password
  * 要插入的密码
  * */
 public long insertPwd(String password){
  SQLiteDatabase db = this.getWritableDatabase();    //取得可写的数据库对象
  ContentValues cv = new ContentValues();
  cv.put(LOGIN_USER, LOGIN_USER);
  cv.put(LOGIN_PWD, password);
  return db.insert(LOGIN_TABLE_NAME, null, cv);
 }
 
 /**更新密码
  * @param password
  * 新密码
  * */
 public int updatePwd(String password){
  SQLiteDatabase db = this.getWritableDatabase();
  String where = LOGIN_USER+"=?";
  String[] whereValues = {LOGIN_USER};
  ContentValues cv = new ContentValues();
  cv.put(LOGIN_PWD, password);
  return db.update(LOGIN_TABLE_NAME, cv, where, whereValues);
 }
 
 /**取得密码
  * @return 返回密码,没有则返回""
  * */
 public String getPwd(){
  SQLiteDatabase db = this.getReadableDatabase();
  String where = LOGIN_USER+"=?";
  String[] whereValues = {LOGIN_USER};
  Cursor cursor = db.query(LOGIN_TABLE_NAME, null, where, whereValues, null, null, null);
  if(cursor.moveToFirst()){
   return cursor.getString(cursor.getColumnIndex(LOGIN_PWD));
  }else{
   return "";
  }
 }
 /**查询记事本表中的内容 
   */
 public Cursor selectNotes(){
  SQLiteDatabase db = this.getReadableDatabase();
  Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null);
  return cursor;
 }
 
 /**插入记事
  * */
 public long insertNote(String title, String content){
  SQLiteDatabase db = this.getWritableDatabase();
  ContentValues cv = new ContentValues();
  cv.put(NOTE_TITLE, title);
  cv.put(NOTE_CONTENT, content);
  return db.insert(TABLE_NAME, null, cv);
 }
 
 /**删除记事
  * @param id
  * _id字段
  * */
 public void deleteNote(String id){
  SQLiteDatabase db = this.getWritableDatabase();
  String where = NOTE_ID+"=?";
  String[] whereValues = {id};
  db.delete(TABLE_NAME, where, whereValues);
 }
 
 /**更新记事
  * */
 public int updateNote(String id,String title, String content){
  SQLiteDatabase db = this.getWritableDatabase();
  String where = NOTE_ID+"=?";
  String[] whereValues = {id};
  ContentValues cv = new ContentValues();
  cv.put(NOTE_TITLE, title);
  cv.put(NOTE_CONTENT, content);
  return db.update(TABLE_NAME, cv, where, whereValues);
 }
 
}

 

package com.pms.note;

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

import com.pms.db.DbHelper;

public class Edit extends Activity{
 
 private EditText et_title, et_content;  //输入框对象
 private Button   bt;     //按钮对象
 private DbHelper db;     //数据库对象
 private String   id;     //从NoteList传过来的id
 private String   listTitle, listContent;//从NoteList传过来的标题和内容

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.edit);
  
  /*取得对象*/
  et_title = (EditText) findViewById(R.id.et_title);
  et_content = (EditText) findViewById(R.id.et_content);
  bt = (Button) findViewById(R.id.bt);
  db = new DbHelper(this);
  
  Intent intent = getIntent();     //得到Intent对象
  /*取出从NoteList传来的值*/
  id = intent.getStringExtra(DbHelper.NOTE_ID);
  listTitle = intent.getStringExtra(DbHelper.NOTE_TITLE);
  listContent = intent.getStringExtra(DbHelper.NOTE_CONTENT);
  
  if(listTitle!= null){            //标题内容不为空
   et_title.setText(listTitle); //显示该标题
  
   
  }
  if(listContent!=null){    //正文内容不为空
   et_content.setText(listContent);//显示该正文
  }
  
  /*绑定按钮点击事件*/
  bt.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
    
    /*取得用户的输入内容*/
    String title = et_title.getText().toString();
    String content = et_content.getText().toString();
    
    //判断是否为空
    if(title.equals("")){
     Toast.makeText(Edit.this, "标题不能为空!", Toast.LENGTH_SHORT).show();
    }
    else if(id!=null){                 //判断是否存在该id的记事
     if(db.updateNote(id, title, content)>0){//存在则更新,返回值大于0,更新成功
      Toast.makeText(Edit.this, "编辑成功!", Toast.LENGTH_SHORT).show();
     }
     else{
      Toast.makeText(Edit.this, "编辑失败", Toast.LENGTH_SHORT).show();
     }
    }
    else if(db.insertNote(title, content)!= -1)//不存在则插入,返回值不等于-1,插入成功
     {
      Toast.makeText(Edit.this, "添加成功!", Toast.LENGTH_SHORT).show();
     }
     else
     {
      Toast.makeText(Edit.this, "添加失败!", Toast.LENGTH_SHORT).show();
     }
    /*设置需要返回到NoteList的内容*/
    Intent intent = new Intent();
    setResult(RESULT_OK,intent);
    finish();    //关闭这个Activity
   }
  
  });
  
  }
 
 

}
Login类

package com.pms.note;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.pms.db.DbHelper;

public class Login extends Activity {
 
 /*得到各个控件对象*/
 private EditText et;
 private Button   bt_login, bt_update;
 
 private DbHelper db;     //数据库对象
 private String   pwd;    //密码
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        /*取得各个控件*/
        et = (EditText) findViewById(R.id.password_edit);
        bt_login = (Button) findViewById(R.id.login_button);
        bt_update = (Button) findViewById(R.id.update_button);
       
        db = new DbHelper(this); //得到DbHelper对象
       
        pwd = db.getPwd();       //从数据库中取得密码
       
        if(pwd.equals(""))       //为空
        {
         Toast.makeText(Login.this, "这是你第一次登录,请初始化密码!", Toast.LENGTH_LONG)
         .show();//弹出Toast消息
         bt_login.setText("注册");    //将Button显示的文字变为注册
        }
        else       //不为空
        {
         Toast.makeText(Login.this, "欢迎回来,请输入密码登录!", Toast.LENGTH_LONG).show();
        }
       
        /*为注册或者登陆绑定监听事件*/
        bt_login.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
    String password = et.getText().toString();  //取得输入的密码
    if(pwd.equals(""))     //为空
    {
     changePwd();       //调用该方法
      
    }
    else if(password.equals("")){                //如果输入为空
     //弹出Toast消息
     Toast.makeText(Login.this, "不能为空!", Toast.LENGTH_LONG).show();
    }
    else if(password.equals(pwd)){               //如果输入匹配
     Toast.makeText(Login.this, "登录成功!", Toast.LENGTH_LONG).show();
     Intent intent = new Intent(Login.this, NoteList.class);
     startActivity(intent);                   //跳转到记事列表
    }
    else{
     //不匹配弹出消息提示密码错误
     Toast.makeText(Login.this, "密码错误!", Toast.LENGTH_LONG).show();
    }
   }
  });
       
        /*为修改密码按钮绑定监听事件*/
        bt_update.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
    String password = et.getText().toString();  //取得输入框的内容
    if(password.equals(pwd)){                   //匹配
     changePwd();                            //调用该方法
    }
    else{
     //不匹配弹出消息
     Toast.makeText(Login.this, "初始密码错误", Toast.LENGTH_LONG).show();
    }
   }
  });
       
    }
   
    /**修改密码
     * */
    public void changePwd(){
     /*装载对话框布局*/
     LinearLayout newPwd = (LinearLayout) getLayoutInflater()
  .inflate(R.layout.login_dialog, null);
  
     //取得对话框中的输入框对象
  final EditText et_dia_new = (EditText) newPwd.findViewById(R.id.etnew);
  final EditText et_dia_con = (EditText) newPwd.findViewById(R.id.etconfirm);
  
  /*新建一个对话框*/
  new AlertDialog.Builder(Login.this)
   .setTitle("输入密码")              //设置标题
   .setView(newPwd)      //设置对话框绑定的视图
   .setPositiveButton("确定", new DialogInterface.OnClickListener() {
    
    @Override
    public void onClick(DialogInterface dialog, int which) {
     //取得输入框的内容
     String dia_new = et_dia_new.getText().toString();
     String dia_con = et_dia_con.getText().toString();
     
     if(dia_new.equals("")||dia_con.equals("")){   //判断是否有空值
      Toast.makeText(Login.this, "不能为空!", Toast.LENGTH_LONG).show();
     }
     else if(dia_new.equals(dia_con)){             //如果两个输入一致
      if(db.getPwd()!=null){
       db.updatePwd(dia_new);                //如果已经设置过密码,更新
      }
      else{
       db.insertPwd(dia_new);                //插入密码
      }
      pwd = dia_new;                            //新的密码
      bt_login.setText("登录");                 //把Button的文字显示为登录
      //弹出Toast消息
      Toast.makeText(Login.this, "你可以使用该密码登录了!", Toast.LENGTH_LONG)
       .show();

     }
     
    }
   })
   //设置一个取消按钮
   .setNegativeButton("取消", new DialogInterface.OnClickListener() {
    
    @Override
    public void onClick(DialogInterface dialog, int which) {
     
    }
   })
   .show();
    }
}

NoteList

package com.pms.note;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.pms.db.DbHelper;


public class NoteList extends Activity{
 
 /*变量声明*/
 private ListView lv;
 private TextView tv;
 private DbHelper db;
 private Cursor   cursor;
 private static final int ADD = Menu.FIRST;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.notelist);
  
  /*取得控件对象*/
  lv = (ListView) findViewById(R.id.lv);
  tv = (TextView) findViewById(R.id.tv);
  
  registerForContextMenu(lv);         //注册一个上下文菜单
  db = new DbHelper(this);            //获得数据库对象
  cursor = db.selectNotes();    //取得数据库中的记事
  refreshListView();
 
  
  /*绑定点击事件*/
  lv.setOnItemClickListener(new OnItemClickListener() {

   @Override
   public void onItemClick(AdapterView<?> parent, View view,
     int position, long id) {
    cursor.moveToPosition(position);                        //将cursor指向position
    Intent intent = new Intent(NoteList.this, Edit.class);  //创建一个Intent对象,跳转到Edit
    /*传递记事的id,标题,内容,这些内容从数据库中相应的字段中取得*/
    intent.putExtra(DbHelper.NOTE_ID, String.valueOf(id));
    intent.putExtra(DbHelper.NOTE_TITLE, cursor.getString(cursor.getColumnIndexOrThrow(DbHelper.NOTE_TITLE)));
    intent.putExtra(DbHelper.NOTE_CONTENT, cursor.getString(cursor.getColumnIndexOrThrow(DbHelper.NOTE_CONTENT)));
    startActivityForResult(intent, 0);      //跳转                    
   }
   
  });
  
  
  
 }

 /**刷新ListView
   */
 public void refreshListView() {
  cursor = db.selectNotes();
  if(cursor.moveToFirst()){
   startManagingCursor(cursor);   //让Activity来管理cursor
   String[] from = {DbHelper.NOTE_TITLE}; //数据库中的列名
   int[] to = {R.id.itemtv};    //数据库中列的内容绑定的视图
   //SimpleCursorAdapter将数据库中的值绑定到listview
   //参数分别为上下文,listview的布局,游标,数据库中列的值,值所要绑定的视图
   SimpleCursorAdapter adapter = new SimpleCursorAdapter(NoteList.this,
    R.layout.listitem,cursor, from, to);
   lv.setAdapter(adapter);                 //listview绑定适配器
   tv.setVisibility(View.GONE);
   lv.setVisibility(View.VISIBLE);
  }
  else{
   tv.setVisibility(View.VISIBLE); //设置为可见
   //设置显示的文本
   tv.setText("还没有你的私人笔记,点击menu添加");
   lv.setVisibility(View.GONE);
  }
   
  }
 
 
 /*创建上下文菜单*/
 @Override
 public void onCreateContextMenu(ContextMenu menu, View v,
   ContextMenuInfo menuInfo) {
  super.onCreateContextMenu(menu, v, menuInfo);
  menu.add(0, 1, 1, "删除");
  
 }

 /*创建菜单*/
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  
  menu.add(0, ADD, 1, "添加笔记")
   .setIcon(R.drawable.menu_add);
  return super.onCreateOptionsMenu(menu);
  
 }
 
 /*设置上下文菜单点击事件*/
 @Override
 public boolean onContextItemSelected(final MenuItem item) {
  final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
  if(item.getItemId()==1){
   new AlertDialog.Builder(this)                  //新建对话框
    .setTitle("警告") 
    .setMessage("确定要删除么?")
    .setIcon(R.drawable.plugin_notice)     //设置图标
    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
     
     @Override
     public void onClick(DialogInterface dialog, int which) {
      db.deleteNote(String.valueOf(info.id)); //删除数据库中该项内容
      refreshListView();            //刷新listview
     }
    })
    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
     
     @Override
     public void onClick(DialogInterface dialog, int which) {
      
     }
    })
    .show();
  }
  return super.onContextItemSelected(item);
 }

 /*设置menu选择事件*/
 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
  if(item.getItemId()==ADD)
  {
   Intent intent = new Intent(NoteList.this, Edit.class);
   startActivityForResult(intent, 1);//跳转到Edit
  }
  return super.onOptionsItemSelected(item);
 }
 
 /*从Edit这个Activity返回是调用*/
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  refreshListView();          //刷新listview  
 }

}

 

清单文件
<?xml version="1.0" encoding="UTF-8"?>
-<manifest android:versionName="1.0" android:versionCode="1" package="com.pms.note" xmlns:android="http://schemas.android.com/apk/res/android"> -<application android:label="@string/app_name" android:icon="@drawable/icon"> -<activity android:label="@string/app_name" android:name="Login"> -<intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <activity android:name=".Edit"/> <activity android:name=".NoteList"/> </application> </manifest>

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

<LinearLayoutandroid:layout_height="fill_parent"android:layout_width="fill_parent"android:orientation="vertical"xmlns:android="http://schemas.android.com/apk/res/android"><RelativeLayoutandroid:layout_height="wrap_content"android:layout_width="fill_parent"android:paddingBottom="5dip"android:paddingTop="10dip"android:background="@drawable/login_bg"android:id="@+id/login_main"><TextViewandroid:layout_height="35dip"android:layout_width="fill_parent"android:id="@+id/password_text"android:layout_alignParentLeft="true"android:text="密码:"android:layout_marginTop="45dip"android:layout_marginRight="10dip"android:layout_marginLeft="12dip"android:textColor="#000000"android:gravity="bottom"android:textSize="18sp"/><EditTextandroid:layout_height="40dip"android:layout_width="fill_parent"android:id="@+id/password_edit"android:layout_marginRight="10dip"android:layout_marginLeft="12dip"android:inputType="textPassword"android:layout_below="@id/password_text"android:maxLength="200"android:singleLine="true"android:password="true"android:scrollHorizontally="true"android:focusable="true"/></RelativeLayout><RelativeLayoutandroid:layout_height="fill_parent"android:layout_width="fill_parent"android:paddingTop="10dip"android:background="@drawable/login_bg2"></RelativeLayout></LinearLayout>

notelist.xml
<?xml version="1.0" encoding="UTF-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:background="@drawable/login_bg" android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="vertical"> <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:visibility="gone" android:textColor="#FF7A00FF" android:textSize="20sp" android:id="@+id/tv"/> <ListView android:layout_height="fill_parent" android:layout_width="fill_parent" android:id="@+id/lv" android:cacheColorHint="#00000000" android:divider="@drawable/divider"/> </LinearLayout>

edit.xml

<?xml version="1.0" encoding="UTF-8"?>
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:background="@drawable/login_bg" android:layout_height="fill_parent" android:layout_width="fill_parent"> <EditText android:layout_height="wrap_content" android:layout_width="fill_parent" android:singleLine="true" android:id="@+id/et_title"/> <EditText android:layout_height="330dp" android:layout_width="fill_parent" android:id="@+id/et_content" android:layout_below="@id/et_title"/> <Button android:background="@drawable/reg_button" android:layout_height="wrap_content" android:layout_width="120dp" android:id="@+id/bt" android:text="确定" android:layout_margin="3dp" android:layout_alignParentRight="true" android:layout_alignParentBottom="true"/> </RelativeLayout>

 

listItem.xml

<?xml version="1.0" encoding="UTF-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="horizontal"> <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:padding="15dp" android:textColor="#FF7A00FF" android:textSize="27sp" android:id="@+id/itemtv"/> </LinearLayout>

login_dialog.xm

<?xml version="1.0"?>

<LinearLayoutandroid:orientation="vertical"android:layout_height="wrap_content"android:layout_width="fill_parent"xmlns:android="http://schemas.android.com/apk/res/android"><TextViewandroid:layout_height="wrap_content"android:layout_width="wrap_content"android:gravity="left"android:text="新密码:"android:layout_marginRight="20dip"android:layout_marginLeft="20dip"android:id="@+id/tvnew"/><EditTextandroid:layout_height="wrap_content"android:layout_width="fill_parent"android:gravity="fill_horizontal"android:layout_marginRight="20dip"android:layout_marginLeft="20dip"android:id="@+id/etnew"/><TextViewandroid:layout_height="wrap_content"android:layout_width="wrap_content"android:gravity="left"android:text="确认密码:"android:layout_marginRight="20dip"android:layout_marginLeft="20dip"android:id="@+id/tvconfirm"/><EditTextandroid:layout_height="wrap_content"android:layout_width="fill_parent"android:gravity="fill_horizontal"android:layout_marginRight="20dip"android:layout_marginLeft="20dip"android:id="@+id/etconfirm"/></LinearLayout>