android 记事本程序源码

应用实现密码登陆,记事本内容可增删改除等操作,用listview显示每次保存的记事内容,实现了记事本的基本功能。代码都有详细注解。

1、代码的目录

密码登陆使用的是sharedpreferences记录输入的密码,sharedPreferences简单介绍

做软件开发应该都知道,很多软件会有配置文件,里面存放这程序运行当中的各个属性值,由于其配置信息并不多,如果采用数据库来存放并不划算,因为数据库连接跟操作等耗时大大影响了程序的效率,因此我们使用键值这种一一对应的关系来存放这些配置信息。SharedPreferences正是Android中用于实现这中存储方式的技术。

SharedPreferences的使用非常简单,能够轻松的存放数据和读取数据。SharedPreferences只能保存简单类型的数据,例如,String、int等。一般会将复杂类型的数据转换成Base64编码,然后将转换后的数据以字符串的形式保存在XML文件中,再用SharedPreferences保存。

使用SharedPreferences保存key-value对的步骤如下:

  (1)使用Activity类的getSharedPreferences方法获得SharedPreferences对象,其中存储key-value的文件的名称由getSharedPreferences方法的第一个参数指定。

  (2)使用SharedPreferences接口的edit获得SharedPreferences.Editor对象。

  (3)通过SharedPreferences.Editor接口的putXxx方法保存key-value对。其中Xxx表示不同的数据类型。例如:字符串类型的value需要用putString方法。

  (4)通过SharedPreferences.Editor接口的commit方法保存key-value对。commit方法相当于数据库事务中的提交(commit)操作。

//对密码进行判断如果任意一个为空就继续执行
			 if((num.equals(""))||(num.equals(""))||(num.equals(""))||(num.equals(""))||(num.equals(""))){
		         SharedPreferences preferences=getSharedPreferences("softinfo",Context.MODE_WORLD_READABLE);
		         Editor edit=preferences.edit();
				 Button btn1 = (Button) v;
		         String input1 = btn1.getText().toString();
		         editNum[number1].setText(input1);
		        // Toast.makeText(getApplication(),editNum[number1].getText().toString(), Toast.LENGTH_SHORT).show();
		        // display.setText(input);
		         number1++;
		         if(number1>4){
					 number1 = 0;
					 for(int i=0;i<10;i++){
						 btnNum[i].setEnabled(false);
					 }

				 }
		        // edit.clear().commit();
		          //第一次输入数据保存到sharedpreference
		         edit.putString("editNum[0]", editNum[0].getText().toString());
		         edit.putString("editNum[1]", editNum[1].getText().toString());
		         edit.putString("editNum[2]", editNum[2].getText().toString());
		         edit.putString("editNum[3]", editNum[3].getText().toString());
		         edit.putString("editNum[4]", editNum[4].getText().toString());
		         edit.commit();
		        // read();
		         if(number1 ==3){
		        	 Toast.makeText(getApplication(), "输完后请再输入一次密码", Toast.LENGTH_SHORT).show();
		         }
			 }

完整登陆代码:

package com.example.diary;

import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 首页
 * @author xing
 *
 */
public class Login extends Activity implements OnClickListener {
	 Boolean flag;

	@SuppressWarnings("unused")
	private TextView display;
	 private Button c,clear,cancel,helplogin;
	 private Button[] btnNum = new Button[10];// 数值按钮
	 private EditText[] editNum = new EditText[5];// 数值按钮
	 int number = 0;
	 int number1 = 0;
	 int editnumber = 0;
	 String num="",num1="",num2="",num3="",num4="";//定义5个输入密码
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login); 

        initUI();

	}
	/**
	 * 初始化UI
	 */
	private void initUI() {

		helplogin = (Button)findViewById(R.id.helplogin);
		helplogin.setOnClickListener(new helploginListener());

		c = (Button)findViewById(R.id.c);
		c.setOnClickListener(new cListener());

		clear = (Button)findViewById(R.id.clear);
		clear.setOnClickListener(new clearListener());

		cancel = (Button)findViewById(R.id.cancel);
		cancel.setOnClickListener(new cancelListener());

		display = (TextView)findViewById(R.id.display);

		editNum[0] = (EditText)findViewById(R.id.editone);
		editNum[1] = (EditText)findViewById(R.id.edittwo);
		editNum[2] = (EditText)findViewById(R.id.editthree);
		editNum[3] = (EditText)findViewById(R.id.editfour);
		editNum[4] = (EditText)findViewById(R.id.editfive);		

		// TODO Auto-generated method stub
		btnNum[0] = (Button)findViewById(R.id.one);
        btnNum[1] = (Button)findViewById(R.id.two);
        btnNum[2] = (Button)findViewById(R.id.three);
        btnNum[3] = (Button)findViewById(R.id.four);
        btnNum[4] = (Button)findViewById(R.id.five);
        btnNum[5] = (Button)findViewById(R.id.six);
        btnNum[6] = (Button)findViewById(R.id.seven);
        btnNum[7] = (Button)findViewById(R.id.eight);
        btnNum[8] = (Button)findViewById(R.id.nine);
        btnNum[9] = (Button)findViewById(R.id.zero);
        read();
        //给全部按钮添加监听器
        for(int i=0;i<10;i++){
        	btnNum[i].setOnClickListener(this);
        }
//        handler.removeCallbacks(runnable);
//		handler.postDelayed(runnable,200);
	}
	//刷新线程,没用,输入一个密码就会不能再输入
	private Handler handler = new Handler();
	private Runnable runnable = new Runnable() {
         public void run () {
        	 read();
         handler.postDelayed(this,1000);
      }
    };
	/**
	 * 所有数字控件的监听器
	 */

	@SuppressWarnings("deprecation")
	public void onClick(View v) {
	    //对密码进行判断如果任意一个为空就继续执行
			 if((num.equals(""))||(num.equals(""))||(num.equals(""))||(num.equals(""))||(num.equals(""))){
		         SharedPreferences preferences=getSharedPreferences("softinfo",Context.MODE_WORLD_READABLE);
		         Editor edit=preferences.edit();
				 Button btn1 = (Button) v;
		         String input1 = btn1.getText().toString();
		         editNum[number1].setText(input1);
		        // Toast.makeText(getApplication(),editNum[number1].getText().toString(), Toast.LENGTH_SHORT).show();
		        // display.setText(input);
		         number1++;
		         if(number1>4){
					 number1 = 0;
					 for(int i=0;i<10;i++){
						 btnNum[i].setEnabled(false);
					 }

				 }
		        // edit.clear().commit();
		          //第一次输入数据保存到sharedpreference
		         edit.putString("editNum[0]", editNum[0].getText().toString());
		         edit.putString("editNum[1]", editNum[1].getText().toString());
		         edit.putString("editNum[2]", editNum[2].getText().toString());
		         edit.putString("editNum[3]", editNum[3].getText().toString());
		         edit.putString("editNum[4]", editNum[4].getText().toString());
		         edit.commit();
		        // read();
		         if(number1 ==3){
		        	 Toast.makeText(getApplication(), "输完后请再输入一次密码", Toast.LENGTH_SHORT).show();
		         }
			 }

			 //判断输入的密码是否被记录了,如果都有了就执行匹配,匹配对了就跳转到firstpage页面
		if(isNumeric(num)&&isNumeric(num1)&&isNumeric(num2)&&isNumeric(num3)&&isNumeric(num4)){
			 Button btn = (Button) v;
	         String input = btn.getText().toString();
	         editNum[number].setText(input);
	       //判断如果输入密码与首次输入密码相同则跳转到firstFage
	        // display.setText(input);
	         if((num.equals(editNum[0].getText().toString()))&&(num1.equals(editNum[1].getText().toString()))&&(num2.equals(editNum[2].getText().toString()))
	        		&&(num3.equals(editNum[3].getText().toString()))&&(num4.equals(editNum[4].getText().toString()))){

	        	 	Intent intent = new Intent(Login.this,Firstpage.class);
		        	startActivity(intent);
		     }
	        // display.setText(editNum[number].getText().toString());
	         editnumber++;
	        // Toast.makeText(getApplication(), editnumber, Toast.LENGTH_SHORT).show();
	         if(editnumber>4){
					editnumber=4;

				}
	         number++;
	         if(number>4){
				 number = 0;
				 //输完密码后设置控件为不可操作状态
				 for(int i=0;i<10;i++){
					 btnNum[i].setEnabled(false);
				 }

			 }	

	         //Toast.makeText(getApplication(),editNum[4].getText().toString()+":"+editNum[3].getText().toString()+":"+ editNum[2].getText().toString(), Toast.LENGTH_SHORT).show();

		 }

	 }
	/**
	 * 判断是否是0-9数字
	 * @param str
	 * @return pattern.matcher(str).matches()
	 */
	public static boolean isNumeric(String str){
	    Pattern pattern = Pattern.compile("[0-9]*");
	    return pattern.matcher(str).matches();
	} 

	/**
	 * 帮助
	 * @author xing
	 *
	 */
	public class helploginListener implements OnClickListener{

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			dialog();
		}

	}
	/**
	 * 帮助对话框
	 */
	protected void dialog() {
		  AlertDialog.Builder builder = new Builder(this);
		  builder.setMessage(R.string.helpcontent);
		  builder.setIcon(R.drawable.ic_launcher);
		  builder.setTitle("温馨提示");
		  builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
			  public void onClick(DialogInterface dialog, int which) {

		   }
		  });
		  builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			  public void onClick(DialogInterface dialog, int which) {

		   }
		  });
		  builder.create().show();
		}

	 public class cListener implements OnClickListener{

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
//			SharedPreferences sp = getSharedPreferences("loginUser", Context.MODE_PRIVATE);
//			Editor editor = sp.edit();
//			editor.clear();
//			editor.commit();
//			display.setText("");
			read();
//			for(int i=0;i<5;i++){
//				editNum[i].setText("");
//			}
			btnsetEnabled();

			number--;
			if(number<0){
				number=0;
			}
			editNum[editnumber].setText("");
			//display.setText(editnumber+":"+number);
			editnumber--;
			if(editnumber<0){
				editnumber=0;
			}

		}

	 }
	 /**
	  * 清空数据监听器
	  * @author aeon
	  *
	  */
	 public class clearListener implements OnClickListener{

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			for(int i=0;i<5;i++){
				editNum[i].setText("");
			}
			btnsetEnabled();
			read(); 

		}

	 }
	 /**
	  * 退出监听器
	  * @author aeon
	  *
	  */
	 public class cancelListener implements OnClickListener{

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}

		 }
	 /**
	  * 读取sharedpreference数据
	  */
	 public void read(){
		  SharedPreferences ferences=getSharedPreferences("softinfo",0);
          num=ferences.getString("editNum[0]", "");
          num1=ferences.getString("editNum[1]", "");
          num2=ferences.getString("editNum[2]", "");
          num3=ferences.getString("editNum[3]", "");
          num4=ferences.getString("editNum[4]", "");
        //  display.setText(num+num1+num2+num3+num4);
//          if((num.equals(""))||(num.equals(""))||(num.equals(""))||(num.equals(""))||(num.equals(""))){
//        	  flag = true;
//        	  Toast.makeText(getApplication(), "输完后请再输入一次密码", Toast.LENGTH_SHORT).show();
//          }else{
//        	  flag = false;
//          }
	 }
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		for(int i=0;i<10;i++){
			 btnNum[i].setEnabled(true);
		 }
		handler.removeCallbacks(runnable);//停止定时器
		super.onDestroy();

	}
	/**
	 * 设置控件可操作
	 */
	public void btnsetEnabled(){
		for(int i=0;i<10;i++){
			 btnNum[i].setEnabled(true);
		 }
	}
	/**
	 * onRestart时控件变为可操作状态,并清空密码显示
	 */
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		btnsetEnabled();//设置控件可操作
		//清空密码
		for(int i=0;i<5;i++){
			editNum[i].setText("");
		}
	}

}

布局实现代码:主要使用了线性布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black"
    android:orientation="vertical" >
    <LinearLayout
        android:layout_marginTop="20dip"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

    <TextView
        android:layout_marginLeft="10dip"
        android:text="@string/chengxu"
        android:layout_width="wrap_content"
        android:textSize="20sp"
        android:layout_height="wrap_content"/>
    <Button
        android:id="@+id/helplogin"
        android:layout_marginLeft="180dip"
        android:textColor="@color/white"
        android:background="#00000000"
        android:text="@string/helplogin"
        android:layout_width="wrap_content"
        android:textSize="20sp"
        android:layout_height="wrap_content"/>
    </LinearLayout>
	<LinearLayout
	    android:layout_marginTop="50dip"
	    android:layout_marginLeft="35dip"
	    android:layout_width="fill_parent"
	    android:layout_height="50dip"
	    android:orientation="horizontal">

	    <EditText

	        android:background="@color/white"
	       android:padding="10sp"
	        android:inputType="textPassword"
	        android:id="@+id/editone"
	        android:maxLength="1"
	        android:layout_width="50dip"
	        android:layout_height="50dip"
	        android:layout_marginLeft="5dip"
	        />
	    <EditText
	        android:background="@color/white"
	        android:inputType="textPassword"
	        android:id="@+id/edittwo"
	        android:maxLength="1"
	        android:layout_width="50dip"
	        android:layout_height="50dip"
	        android:layout_marginLeft="5dip"
	        />
	    <EditText
	        android:background="@color/white"
	        android:inputType="textPassword"
	        android:id="@+id/editthree"
	        android:maxLength="1"
	        android:layout_width="50dip"
	        android:layout_height="50dip"
	        android:layout_marginLeft="5dip"
	        />
	    <EditText
	        android:background="@color/white"
	        android:inputType="textPassword"
	        android:id="@+id/editfour"
	        android:maxLength="1"
	        android:layout_width="50dip"
	        android:layout_height="50dip"
	        android:layout_marginLeft="5dip"
	        />
	    <EditText
	        android:background="@color/white"
	        android:inputType="textPassword"
	        android:id="@+id/editfive"
	        android:maxLength="1"
	        android:layout_width="50dip"
	        android:layout_height="50dip"
	        android:layout_marginLeft="5dip"
	        />
    </LinearLayout>
    <LinearLayout
        android:layout_marginTop="100dip"
        android:layout_marginLeft="20dip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
	    <Button
	        android:id="@+id/one"
	        android:text="@string/one"
	        android:layout_width="105dip"
	        android:layout_height="wrap_content"/>
	    <Button
	        android:id="@+id/two"
	        android:text="@string/two"
	        android:layout_width="105dip"
	        android:layout_height="wrap_content"/>
	    <Button
	        android:id="@+id/three"
	        android:text="@string/three"
	        android:layout_width="105dip"
	        android:layout_height="wrap_content"/>
	</LinearLayout>
	<LinearLayout
	    android:layout_marginLeft="20dip"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
	    <Button
	        android:id="@+id/four"
	        android:text="@string/four"
	        android:layout_width="105dip"
	        android:layout_height="wrap_content"/>
	    <Button
	        android:id="@+id/five"
	        android:text="@string/five"
	        android:layout_width="105dip"
	        android:layout_height="wrap_content"/>
	    <Button
	        android:id="@+id/six"
	        android:text="@string/six"
	        android:layout_width="105dip"
	        android:layout_height="wrap_content"/>
	</LinearLayout>
	<LinearLayout
	    android:layout_marginLeft="20dip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
	    <Button
	        android:id="@+id/seven"
	        android:text="@string/seven"
	        android:layout_width="105dip"
	        android:layout_height="wrap_content"/>
	    <Button
	        android:id="@+id/eight"
	        android:text="@string/eight"
	        android:layout_width="105dip"
	        android:layout_height="wrap_content"/>
	    <Button
	        android:id="@+id/nine"
	        android:text="@string/nine"
	        android:layout_width="105dip"
	        android:layout_height="wrap_content"/>
	</LinearLayout>
	<LinearLayout
	    android:layout_marginLeft="20dip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
	    <Button
	        android:id="@+id/c"
	        android:text="@string/c"
	        android:layout_width="105dip"
	        android:layout_height="wrap_content"/>
	    <Button
	        android:id="@+id/zero"
	        android:text="@string/zero"
	        android:layout_width="105dip"
	        android:layout_height="wrap_content"/>
	    <Button
	        android:id="@+id/clear"
	        android:text="@string/clear"
	        android:layout_width="105dip"
	        android:layout_height="wrap_content"/>
	</LinearLayout>
    <Button
        android:layout_marginLeft="20dip"
        android:layout_marginRight="10dip"
        android:id="@+id/cancel"
        android:text="@string/cancel"
        android:layout_width="315dip"
        android:layout_height="wrap_content"/>
        <TextView
            android:id="@+id/display"
        android:layout_marginTop="20dip"
        android:layout_width="fill_parent"
        android:textSize="20sp"
        android:layout_height="wrap_content"/>
</LinearLayout>

2、在写记事本中记录数据使用了sqlite数据库,因为现在的主流移动设备像Android、iPhone等都使用SQLite作为复杂数据的存储引擎,在我们为移动设备开发应用程序时,也许就要使用到SQLite来存储我们大量的数据,所以我们就需要掌握移动设备上的SQLite开发技巧。对于Android平台来说,系统内置了丰富的API来供开发人员操作SQLite,我们可以轻松的完成对数据的存取。

	/**
	 * 保存数据监听器
	 * @author aeon
	 *
	 */
	public class saveListener implements OnClickListener{

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
				SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd");
		        data   =   sDateFormat.format(new  java.util.Date());
				//if(diary!=null)
	           // {
	                //return;
		            People people = new People();
		            people.Time = data;
		            people.Diary = diarycontent.getText().toString();//获取输入日志内容
		            //people.Height = 1;
		            long colunm = dbAdapter.insert(people);
		            if(colunm == -1)
		            {
		                Toast.makeText(getApplication(), "添加错误", Toast.LENGTH_SHORT).show();
		            }
		            else
		            {
		            	Toast.makeText(getApplication(), "成功添加数据 ", Toast.LENGTH_SHORT).show();
		               // Toast.makeText(getApplication(), "成功添加数据 , ID: "+String.valueOf(colunm), Toast.LENGTH_SHORT).show();
		            }
		          //  Firstpage.displaydiary1();//当点击保存后更新listview列表数据
		            finish();//写完日记后结束该activity以免多次保存
		}

	}

关于记事本用到的数据库的一些操作,更新日记

/**
	 * 修改内容监听器
	 * @author xing
	 *
	 */
	public class changeListener implements OnClickListener{

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub			

			People people = new People();
            people.Diary = diarycontent.getText().toString();
            people.Time  = data;
            //people.Height = Float.parseFloat(heightEdit.getText().toString());
            Intent intent=getIntent();
            timeid=intent.getStringExtra("timeid");
            if(timeid!=null){

            	  int  id = Integer.parseInt(timeid);
                 // Toast.makeText(getApplication(),timeid, Toast.LENGTH_SHORT).show();
                  long count = dbAdapter.updateOneData(id, people);      

                   if(count == -1 )
                   {
                   	Toast.makeText(getApplication(), "更新错误", Toast.LENGTH_SHORT).show();
                       //display.setText("");
                   }
                   else
                   {
                   	//Toast.makeText(getApplication(), "更新成功"+"更新数据第"+String.valueOf(id)+"条", Toast.LENGTH_SHORT).show();
                   	Toast.makeText(getApplication(), "更新成功", Toast.LENGTH_SHORT).show();
                   }

                   finish();
            }else{
            	Toast.makeText(getApplication(), "请点击保存", Toast.LENGTH_SHORT).show();
            }
			//hintKb();
		}

	}

删除记事本代码

/**
	 * 删除所有记事对话框
	 */
	public void showdeleteDialog(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		LayoutInflater inflater = getLayoutInflater();
	    View layout = inflater.inflate(R.layout.dialog, null);
	    builder.setView(layout);
	    builder.setIcon(R.drawable.ic_launcher);
		builder.setTitle(R.string.firstdialogtitle);
		builder.setMessage("请问您是否要删除所有记事?");
		builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				dbAdapter.deleteAllData();
				Diaryadapter.clear(); //删除数据后清空listview显示
	            Toast.makeText(getApplication(), "日志已删除", Toast.LENGTH_SHORT).show();
			}
		});
		builder.setNegativeButton("cancel",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				});
		final AlertDialog dlg = builder.create();
		dlg.show();
	}

编辑记事本功能

/**
		 * 编辑该天事件监听器
		 */
		Button editordialog  = (Button)layout.findViewById(R.id.editordialog);
		editordialog.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(Firstpage.this,WriteDiaryActivity.class);
				String spStr[] = itemdata1.split("日记内容:");//匹配字符串
				String spStr1[] = itemdata1.split(",时间");//匹配字符串
				intent.putExtra("diary", spStr[1]);  //获取内容
				intent.putExtra("timeid", spStr1[0]);//获取id
				//intent.putExtra("", "");
//				Bundle bundle=new Bundle();
//	            bundle.putString("result", "第一个activity的内容");
//	            bundle.putString("content",content);
//	            intent.putExtras(bundle);
				startActivity(intent);
				//finish();//跳转后结束dialog
			}
		});

3、完整的写记事本跟现实代码:

package com.example.diary;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import tree.love.Adapter.DBAdapter;
import tree.love.Bean.People;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class WriteDiaryActivity extends Activity {  

	private TextView time;
	private Button takephoto;
	private Button finish;
	private Button delete;
	private Button change;
	private EditText diarycontent;
	private Button scanphoto;
	private Button save;
	private Button autocam;
	private ImageView imageview4,imageview1,imageview2,imageview3;
	private SoundPool sp;//声明一个SoundPool
	private int music;//定义一个整型用load();来设置suondID    

	private DBAdapter dbAdapter;

	int count = 0;
	String diary;
	String data;
	String aa;
	String timeid;
   // Firstpage Firstpage = new Firstpage();
    int num=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
      //去除标题
       // requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.writediarycome);
        //初始化UI
        initUI();
        //获得实例
        dbAdapter = new DBAdapter(this);
        //打开数据库
        dbAdapter.open();

    }

//    /**
//     * 判断输入内容是否为空
//     * @return
//     */
//    boolean isRight()
//    {
//        if(diary.length() == 0)
//        {
//            Toast.makeText(getApplication(), "请输入符合场常理的数据", Toast.LENGTH_SHORT).show();
//            return false;
//        }else
//        {
//            return true;
//        }
//    }

    /**
     * 初始化UI控件
     */
	private void initUI() {
		// TODO Auto-generated method stub
		 //获取声音文件
        sp= new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);//第一个参数为同时播放数据流的最大个数,第二数据流类型,第三为声音质量
        music = sp.load(this, R.raw.jie, 1); //把你的声音素材放到res/raw里,第2个参数即为资源文件,第3个为音乐的优先级
		autocam = (Button)findViewById(R.id.autocam);
		autocam.setOnClickListener(new autocamListener());
		imageview3 = (ImageView)findViewById(R.id.imageview3);
		imageview3.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				getCurrentScreen();
				sp.play(music, 1, 1, 0, 0, 1);   //拍照声音
			}
		});		

		save = (Button)findViewById(R.id.save);
		save.setOnClickListener(new saveListener());

		change = (Button)findViewById(R.id.change);
		change.setOnClickListener(new changeListener());

		diarycontent = (EditText)findViewById(R.id.diarycontent);
		diary = diarycontent.getText().toString();

		delete = (Button)findViewById(R.id.delete);
		delete.setOnClickListener(new deleteListener());

		finish = (Button)findViewById(R.id.finish);
		finish.setOnClickListener(new finishListener());
		imageview4 = (ImageView)findViewById(R.id.imageview4);
		imageview4.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});

		takephoto = (Button)findViewById(R.id.takephoto);
		takephoto.setOnClickListener(new takephotoListener());
		imageview1 = (ImageView)findViewById(R.id.imageview1);
		imageview1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
	            startActivityForResult(intent, 1);
			}
		});

		scanphoto = (Button)findViewById(R.id.sanphoto);
		scanphoto.setOnClickListener(new scanphotoListener());
		imageview2 = (ImageView)findViewById(R.id.imageview2);
		imageview2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(WriteDiaryActivity.this,Scanphoto.class);
				startActivity(intent);
			}
		});
		time = (TextView)findViewById(R.id.time);

		time();//获取手机当前时间
		time1();//获取手机日期,年月日
		receiveaadata();
	}
	/**
	 * 接收显示编辑diary
	 */
	public void receiveaadata(){
		Intent intent=getIntent();
		aa=intent.getStringExtra("diary");
		diarycontent.setText(aa);
		if(aa!=null){
			save.setEnabled(false);//设置保存按钮为不可操作状态
		}
	}

	/**
	 * 保存数据监听器
	 * @author aeon
	 *
	 */
	public class saveListener implements OnClickListener{

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
				SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd");
		        data   =   sDateFormat.format(new  java.util.Date());
				//if(diary!=null)
	           // {
	                //return;
		            People people = new People();
		            people.Time = data;
		            people.Diary = diarycontent.getText().toString();//获取输入日志内容
		            //people.Height = 1;
		            long colunm = dbAdapter.insert(people);
		            if(colunm == -1)
		            {
		                Toast.makeText(getApplication(), "添加错误", Toast.LENGTH_SHORT).show();
		            }
		            else
		            {
		            	Toast.makeText(getApplication(), "成功添加数据 ", Toast.LENGTH_SHORT).show();
		               // Toast.makeText(getApplication(), "成功添加数据 , ID: "+String.valueOf(colunm), Toast.LENGTH_SHORT).show();
		            }
		          //  Firstpage.displaydiary1();//当点击保存后更新listview列表数据
		            finish();//写完日记后结束该activity以免多次保存
		}

	}

	/**
	 * 修改内容监听器
	 * @author xing
	 *
	 */
	public class changeListener implements OnClickListener{

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub			

			People people = new People();
            people.Diary = diarycontent.getText().toString();
            people.Time  = data;
            //people.Height = Float.parseFloat(heightEdit.getText().toString());
            Intent intent=getIntent();
            timeid=intent.getStringExtra("timeid");
            if(timeid!=null){

            	  int  id = Integer.parseInt(timeid);
                 // Toast.makeText(getApplication(),timeid, Toast.LENGTH_SHORT).show();
                  long count = dbAdapter.updateOneData(id, people);      

                   if(count == -1 )
                   {
                   	Toast.makeText(getApplication(), "更新错误", Toast.LENGTH_SHORT).show();
                       //display.setText("");
                   }
                   else
                   {
                   	//Toast.makeText(getApplication(), "更新成功"+"更新数据第"+String.valueOf(id)+"条", Toast.LENGTH_SHORT).show();
                   	Toast.makeText(getApplication(), "更新成功", Toast.LENGTH_SHORT).show();
                   }

                   finish();
            }else{
            	Toast.makeText(getApplication(), "请点击保存", Toast.LENGTH_SHORT).show();
            }
			//hintKb();
		}

	}
	/**
	 * 打开与关闭软件键盘
	 */
	 @SuppressWarnings("unused")
	private void hintKb() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		   // 得到InputMethodManager的实例
		   if (imm.isActive()) {
		    // 如果开启
			   imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
		       InputMethodManager.HIDE_NOT_ALWAYS);
		    // 关闭软键盘,开启方法相同,这个方法是切换开启与关闭状态的
		   }
	    }

	/**
	 * 删除监听器
	 * @author aeon
	 *
	 */
	public class deleteListener implements OnClickListener{

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			showDialog();
		}

	}

	/**
	 * delete自定义对话框
	 * @author ning
	 *
	 */
	public void showDialog(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		LayoutInflater inflater = getLayoutInflater();
	    View layout = inflater.inflate(R.layout.dialog, null);
	    builder.setView(layout);
	    builder.setIcon(R.drawable.ic_launcher);
		builder.setTitle(R.string.dialogtitle);
		builder.setMessage("请问您是否要删除该天记事?");
		builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub

				diarycontent.setText("");
				Toast.makeText(getBaseContext(), "删除成功", Toast.LENGTH_SHORT).show();
			}
		});
		builder.setNegativeButton("cancel",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						//finish();
					}
				});
		final AlertDialog dlg = builder.create();
		dlg.show();
	}

	/**
	 * 退出监听器
	 * @author aeon
	 *
	 */
	public class finishListener implements OnClickListener{

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			//结束本页面与logoActivity,返回到登录页面
//			Intent intent = new Intent();
//			intent.setClass(WriteDiaryActivity.this, MainActivity.class);
//			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //注意本行的FLAG设置
//			startActivity(intent);
			finish();
		}
	}
	/**
	 * takephoto监听器
	 *
	 * */
	public class takephotoListener implements OnClickListener{

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, 1);
		}

	}

	/*
	 * 获取时间
	 * return null
	 * */
	public void time(){

		SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd hh:mm");
        String   date   =   sDateFormat.format(new  java.util.Date());
        time.setText(date);
	}
	/**
	 * 获取手机当前年月日
	 */
	public void time1(){
		SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd");
        data   =   sDateFormat.format(new  java.util.Date());
	}
	/**
	 * 浏览拍好的图片
	 * @author aeon
	 *
	 */
	public class scanphotoListener implements OnClickListener{

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			//scanphotodialog();
			Intent intent = new Intent(WriteDiaryActivity.this,Scanphoto.class);
			startActivity(intent);
		}

	}

	/**执行拍照
	 * (non-Javadoc)
	 * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
	 * @param requestCode \resultCode \data
	 * Exception 当不加权限的时候会报空指针
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub

		if(resultCode == Activity.RESULT_OK ){
			count++;
			String sdStatus = Environment.getExternalStorageState();
            if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
                Log.i("TestFile",
                        "SD card is not avaiable/writeable right now.");
                return;
            }
            //String name = new DateFormat().format("yyyyMMdd_hhmmss",Calendar.getInstance(Locale.CHINA)) + ".jpg"; 

            //Toast.makeText(this, name, Toast.LENGTH_LONG).show();
            Bundle bundle = data.getExtras();
            Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据,并转换为Bitmap图片格式  

            FileOutputStream b = null;
            File file = new File("/sdcard/data/");
            file.mkdirs();// 创建文件夹
           // String fileName = "/sdcard/data/"+name;
            String s = String.valueOf(count)+".jpg";

            String fileName = "/sdcard/data/"+s;

            try {
                b = new FileOutputStream(fileName);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    b.flush();
                    b.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
           // ((ImageView) findViewById(R.id.imageview)).setImageBitmap(bitmap);// 将图片显示在ImageView里
        }
		super.onActivityResult(requestCode, resultCode, data);
	}
	/**
	 * autocam监听器
	 * @author aeon
	 *
	 */
	public class autocamListener implements OnClickListener{

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			getCurrentScreen();
		}

	}

	/**
	 * 截屏
	 */
	@SuppressWarnings("deprecation")
	public void getCurrentScreen() {
		num++;
        // 1.构建Bitmap
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        int w = display.getWidth();//w=480
        int h = display.getHeight();//h=800
        Bitmap imageBitmap = Bitmap.createBitmap(w, h, Config.ARGB_8888);//最后一个参数叫位图结构
        //ARGB--Alpha,Red,Green,Blue.
        //ARGB为一种色彩模式,也就是RGB色彩模式附加上Alpha(透明度)通道,常见于32位位图的存储结构。  

        // 2.获取屏幕
        View decorview = this.getWindow().getDecorView();//decor意思是装饰布置
        decorview.setDrawingCacheEnabled(true);
        imageBitmap = decorview.getDrawingCache();                

      //  String SaveImageFilePath = getSDCardPath() + "/gameCounter";//保存图片的文件夹路径
        String SaveImageFilePath = getSDCardPath() + "/data";//保存图片的文件夹路径  data为新建文件夹

        // 3.保存Bitmap
        try {
            File path = new File(SaveImageFilePath);
           // String imagepath = SaveImageFilePath + "/data" + ".png";//保存图片的路径
            String imagepath = SaveImageFilePath + "/data"+num + ".png";//保存图片的路径
            File file = new File(imagepath);
            if (!path.exists()) {
                path.mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }  

            FileOutputStream fos = null;
            fos = new FileOutputStream(file);
            if (null != fos) {
                //imageBitmap.compress(format, quality, stream);
                //把位图的压缩信息写入到一个指定的输出流中
                //第一个参数format为压缩的格式
                //第二个参数quality为图像压缩比的值,0-100.0 意味着小尺寸压缩,100意味着高质量压缩
                //第三个参数stream为输出流
                imageBitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
                fos.flush();
                fos.close();
                Toast.makeText(this,"图片已经已保存在手机卡data文件目录下",Toast.LENGTH_LONG).show();
                //text.setText("图片已经已保存至"+SaveImageFilePath);
            }  

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取SDCard的目录路径功能
     */
    private String getSDCardPath() {
        String SDCardPath = null;
        // 判断SDCard是否存在
        boolean IsSDcardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
        if (IsSDcardExist) {
            SDCardPath = Environment.getExternalStorageDirectory().toString();//SD卡的路径为: /mnt/sdcard
        }
        return SDCardPath;
    }
    /**
     * 结束时关闭数据库
     */
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		dbAdapter.close();//关闭数据库
	}  

}

布局代码:

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

    android:layout_gravity="center"
    android:orientation="vertical" >
  <LinearLayout
      android:background="#FFCCFF"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:orientation="horizontal">
      <TextView
        android:id="@+id/time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
		/>
	  <Button
	      android:layout_marginLeft="15dip"
	      android:background="#00000000"
	      android:id="@+id/change"
	      android:layout_width="wrap_content"
	      android:layout_height="wrap_content"
	      android:text="@string/change"/>
	  <Button
	      android:layout_marginLeft="15dip"
	      android:background="#00000000"
	      android:id="@+id/delete"
	      android:layout_width="wrap_content"
	      android:layout_height="wrap_content"
	      android:text="@string/delete"/>
	  <Button
	      android:layout_marginLeft="15dip"
	      android:background="#00000000"
	      android:id="@+id/save"
	      android:layout_width="wrap_content"
	      android:layout_height="wrap_content"
	      android:text="@string/save"/>
	</LinearLayout>
	<EditText
	  	android:gravity="top"
	  	android:inputType="none"
	    android:id="@+id/diarycontent"
	    android:layout_width="fill_parent"
	    android:background="@drawable/writediary1"
	    android:layout_height="450dip"/>

  <LinearLayout
      android:background="#FFCCFF"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:orientation="horizontal">
	  <LinearLayout
	      android:layout_width="wrap_content"
	       android:layout_marginLeft="5dip"
	      android:layout_height="wrap_content"
	      android:orientation="vertical">
	      <ImageView
	          android:id="@+id/imageview1"
	          android:layout_marginTop="5dip"
	          android:layout_marginLeft="15dip"
	          android:contentDescription="@string/desc"
	          android:layout_width="40dip"
	          android:layout_height="30dip"
	          android:background="@drawable/takephoto"/>
	      <Button
	        android:layout_marginLeft="5dip"
		    android:background="#00000000"
	        android:id="@+id/takephoto"
	        android:textSize="13sp"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:text="@string/takephoto"
			/>
      </LinearLayout>
      <!--  -->
       <LinearLayout
	      android:layout_width="wrap_content"
	      android:layout_height="wrap_content"
	       android:layout_marginLeft="5dip"
	      android:orientation="vertical">
	      <ImageView
	          android:id="@+id/imageview2"
	          android:layout_marginTop="5dip"
	          android:layout_marginLeft="30dip"
	          android:contentDescription="@string/desc"
	          android:layout_width="40dip"
	          android:layout_height="30dip"
	          android:background="@drawable/picture"/>
			<Button
	        android:layout_marginLeft="20dip"
		    android:background="#00000000"
	        android:id="@+id/sanphoto"
	         android:textSize="13sp"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:text="@string/scanphoto"
		/>
		</LinearLayout>
		<!--  -->
		 <LinearLayout
	      android:layout_width="wrap_content"
	       android:layout_marginLeft="5dip"
	      android:layout_height="wrap_content"
	      android:orientation="vertical">
			<ImageView

			    android:id="@+id/imageview3"
	          android:layout_marginTop="5dip"
	          android:layout_marginLeft="30dip"
	          android:contentDescription="@string/desc"
	          android:layout_width="40dip"
	          android:layout_height="30dip"
	          android:background="@drawable/jieping"/>
		  <Button
		      android:layout_marginLeft="20dip"
		      android:background="#00000000"
		      android:id="@+id/autocam"
		       android:textSize="13sp"
		      android:layout_width="wrap_content"
		      android:layout_height="wrap_content"
		      android:text="@string/autocam"/>
	  </LinearLayout>
	  <!--  -->
	   <LinearLayout
	      android:layout_width="wrap_content"
	      android:layout_height="wrap_content"
	      android:layout_marginLeft="5dip"
	      android:orientation="vertical">
		  <ImageView
		      android:id="@+id/imageview4"
	          android:layout_marginTop="5dip"
	          android:layout_marginLeft="30dip"
	          android:contentDescription="@string/desc"
	          android:layout_width="40dip"
	          android:layout_height="30dip"
	          android:background="@drawable/finish"/>
		  <Button
		      android:layout_marginLeft="20dip"
		      android:background="#00000000"
		      android:id="@+id/finish"
		      android:textSize="13sp"
		      android:layout_width="wrap_content"
		      android:layout_height="wrap_content"
		      android:text="@string/finish"/>
	  </LinearLayout>

	</LinearLayout>
	<!--
	<ImageView
	    android:id="@+id/imageview"
	    android:layout_width="fill_parent"
	    android:layout_height="1dip"/>
	    	 -->
</LinearLayout>

实现记事本内容代码:

package com.example.diary;

import tree.love.Adapter.DBAdapter;
import tree.love.Bean.People;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;

public class Firstpage extends Activity {
	private Button writediary;
	private Button set;
	private Button deletediary;
	private Button scandiary;
	private Button firstfinish;
	private ListView diarylistview;

	private PopupWindow popupwindow;
	private DBAdapter dbAdapter;

	 String result = "";
	 String itemdata,itemdata1;
	// String iddiary;
	 private ArrayAdapter<String> Diaryadapter;
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
      //去除标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.firstpage);
      //获得实例
        dbAdapter = new DBAdapter(this);
        //打开数据库
        dbAdapter.open();
        initUI();

    }
	/**
	 * 初始化UI
	 */
	private void initUI() {
		// TODO Auto-generated method stub
		 // 初使化设备存储数组
		Diaryadapter = new ArrayAdapter<String>(this, R.layout.listview_format);
		diarylistview = (ListView)findViewById(R.id.diaryshow);
		diarylistview.setOnItemClickListener(new diarylistviewItemListener());
		//Diaryadapter.clear();
		diarylistview.setAdapter(Diaryadapter);

		firstfinish = (Button)findViewById(R.id.firstfinish);
		firstfinish.setOnClickListener(new firstfinishListener());	

		set = (Button)findViewById(R.id.set);
		set.setOnClickListener(new setListener());		

		writediary = (Button)findViewById(R.id.writediary);
		writediary.setOnClickListener(new writeListener());

		deletediary = (Button)findViewById(R.id.deletediary);
		deletediary.setOnClickListener(new deletediaryListener());

		scandiary = (Button)findViewById(R.id.scandiary);
		scandiary.setOnClickListener(new scandiaryListener());
		displaydiary();//登录进去后显示所有日记
		photodialog();
//		handler.removeCallbacks(runnable);
//		handler.postDelayed(runnable,1000);
	}
	/**
	 * 由于更新完数据和写完日记后listview不能自动更新,如果在writeDiaryActivity调用display()
	 * 方法会出现空指针,因此添加一个定时器定时刷新listview
	 */
	private Handler handler = new Handler();
	private Runnable runnable = new Runnable() {
         public void run () {
        	 displaydiary();
         handler.postDelayed(this,1000);
      }
    };

    /**
     * 退出
     * @author aeon
     *
     */
    public class firstfinishListener implements OnClickListener{

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			finish();
		}

    }

	/**
	 * listview item事件监听器,并根据listview id获取到数据库数据,再赋值给itemdata1
	 * @author aeon
	 *
	 */
	public class diarylistviewItemListener implements OnItemClickListener{

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			for(int i=0;i<1000;i++){
				if(arg2 ==i){
					itemdata = Diaryadapter.getItem(arg2);
					Diaryadapter.clear();
					String result1 = "";
					String c = String.valueOf(arg3);
					int cc = Integer.parseInt(c);
					 People[] peoples = dbAdapter.queryAllData();
			         for (int j = 0; j < peoples.length; j++)

			         {
			             result1 =peoples[cc].toString()+"\n";
			         }
					 itemdata1 = result1;
					showItemDialog();	//点击listviewitem后弹出item对话框
				}
			}
		}
	}

	/**
	 * deletediary 监听器
	 * @author aeon
	 *
	 */
	public class deletediaryListener implements OnClickListener{

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub

			showdeleteDialog();		//弹出是否删除全部数据对话框
//			dbAdapter.deleteAllData();
//			Diaryadapter.clear(); //删除数据后清空listview显示
//          Toast.makeText(getApplication(), "日志已删除", Toast.LENGTH_SHORT).show();
		}

	}
	/**
	 * scandiary 监听器
	 * @author aeon
	 *
	 */
	public class scandiaryListener implements OnClickListener{

		@Override
		public void onClick(View arg0) {
			displaydiary();
			// TODO Auto-generated method stub
//			 People[] peoples = dbAdapter.queryAllData();
//             if(peoples == null)
//             {
//                 Toast.makeText(getApplication(), "数据库里面没有数据", Toast.LENGTH_SHORT).show();
//                 return;
//             }
//           //  Toast.makeText(getApplication(), "数据库:", Toast.LENGTH_SHORT).show();
//             //String result = "";
//             //该方式会使所有数据都添加到一个item里面去
//             for (int i = 0; i < peoples.length; i++)
//             {
//            	 result += peoples[i].toString()+"\n";
//                // result = peoples[i].toString()+"\n";
//
//             }
//             //Diaryadapter.clear();
//             Diaryadapter.add(result);
//             result = "";         //添加完后将result清空,防止下次点击会累加
           //  scandiary.setEnabled(false);
            // display.setText(result);
		}

	}
	/**
	 * 更新listview数据并拆分数据得到id和时间后面的数据
	 */
	public void displaydiary(){
		Diaryadapter.clear();
		 People[] peoples = dbAdapter.queryAllData();
         if(peoples == null)
         {
           //  Toast.makeText(getApplication(), "数据库里面没有数据", Toast.LENGTH_SHORT).show();
             return;
         }

         for (int i = 0; i < peoples.length; i++)
         {
             result = peoples[i].toString()+"\n";
             String spStrone[] = result.split(",时间:");//匹配字符串
             Diaryadapter.add(spStrone[1]);
         }
         result = "";         //添加完后将result清空,防止下次点击会累加
	}

	/**
	 * 打开列表监听器
	 * @author aeon
	 *
	 */
	public class setListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.set:
				set.setText("设置");
				if (popupwindow != null&&popupwindow.isShowing()) {
					popupwindow.dismiss();
					return;
				} else {
					set.setText("关闭");
					initmPopupWindowView();
					popupwindow.showAsDropDown(v, 0, 5);
				}
				break;
			default:
				break;
			}
		}

	}
	/**
	 * 弹出列表method
	 */
	public void initmPopupWindowView() {

		// // 获取自定义布局文件pop.xml的视图
		View customView = getLayoutInflater().inflate(R.layout.view_item,
				null, false);
		// 创建PopupWindow实例,200,150分别是宽度和高度
		popupwindow = new PopupWindow(customView, 300, 300);
		// 设置动画效果 [R.style.AnimationFade 是自己事先定义好的]
		popupwindow.setAnimationStyle(R.style.AnimationFade);
		// 自定义view添加触摸事件
		customView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (popupwindow != null && popupwindow.isShowing()) {
					popupwindow.dismiss();
					popupwindow = null;
				}

				return false;
			}
		});
		//初始化view_item UI
		Button grid = (Button) customView.findViewById(R.id.grid);
		Button list = (Button) customView.findViewById(R.id.more);
		final CheckBox gridCB = (CheckBox)customView.findViewById(R.id.gridCB);
		final CheckBox listCB = (CheckBox)customView.findViewById(R.id.listCB);
		//宫格显示监听
		gridCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){  

            public void onCheckedChanged(android.widget.CompoundButton compoundButton, boolean b){
            	//popupwindow.dismiss();
            	gridCB.setChecked(true);
                Toast.makeText(getApplication(),"gridCB",Toast.LENGTH_LONG).show();
            }
        });
		//列表显示监听
		listCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){  

            public void onCheckedChanged(android.widget.CompoundButton compoundButton, boolean b){
            	//popupwindow.dismiss();
            	listCB.setChecked(true);
                Toast.makeText(getApplication(),"listCB",Toast.LENGTH_LONG).show();
            }
        }); 

		//设置
		grid.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(Firstpage.this,Setting.class);
				startActivity(intent);
				set.setText("设置");
				popupwindow.dismiss();
			}
		});

		//list按钮监听器
		list.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				//Intent intent = new Intent(Firstpage.this,Image.class);
				//startActivity(intent);
				Toast.makeText(getApplicationContext(), "没有更多选项了", Toast.LENGTH_SHORT).show();
				set.setText("设置");
				popupwindow.dismiss();
			}
		});

	}

	/**
	 * 写笔记监听器
	 * @author aeon
	 *
	 */
	public class writeListener implements OnClickListener{

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			Intent intent = new Intent(Firstpage.this,WriteDiaryActivity.class);
			startActivity(intent);
		}

	}

	/**
	 * 删除所有记事对话框
	 */
	public void showdeleteDialog(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		LayoutInflater inflater = getLayoutInflater();
	    View layout = inflater.inflate(R.layout.dialog, null);
	    builder.setView(layout);
	    builder.setIcon(R.drawable.ic_launcher);
		builder.setTitle(R.string.firstdialogtitle);
		builder.setMessage("请问您是否要删除所有记事?");
		builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				dbAdapter.deleteAllData();
				Diaryadapter.clear(); //删除数据后清空listview显示
	            Toast.makeText(getApplication(), "日志已删除", Toast.LENGTH_SHORT).show();
			}
		});
		builder.setNegativeButton("cancel",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				});
		final AlertDialog dlg = builder.create();
		dlg.show();
	}

	/**
	 * 弹出item事件处理对话框
	 */
	public void showItemDialog(){
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		LayoutInflater inflater = getLayoutInflater();
		final View layout = inflater.inflate(R.layout.item_dialog, null);
	    builder.setView(layout);
	    builder.setIcon(R.drawable.ic_launcher);
		builder.setTitle(R.string.itemdialogtitle);
		//builder.setMessage("");
		Button deleteitem  = (Button)layout.findViewById(R.id.deleteitem);
		/**
		 * 删除该天记事监听器
		 */

		deleteitem.setOnClickListener(new OnClickListener() {

			@SuppressWarnings("static-access")
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				 String spStr1[] = itemdata1.split(",时间");//匹配字符串
				 int  id = Integer.parseInt(spStr1[0]);
	             long result = dbAdapter.deleteOneData(id);
                 Log.i(dbAdapter.DB_ACTION, "delete long :"+result);
                // String msg = "删除ID为"+id+"的数据" + (result>0?"成功":"失败");
                 String msg = "数据删除" + (result>0?"成功":"失败");
			   	 Toast.makeText(getApplication(), msg, Toast.LENGTH_SHORT).show();
			   	//dlg.dismiss();
			     displaydiary();
			}
		});

		/**
		 * 编辑该天事件监听器
		 */
		Button editordialog  = (Button)layout.findViewById(R.id.editordialog);
		editordialog.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(Firstpage.this,WriteDiaryActivity.class);
				String spStr[] = itemdata1.split("日记内容:");//匹配字符串
				String spStr1[] = itemdata1.split(",时间");//匹配字符串
				intent.putExtra("diary", spStr[1]);  //获取内容
				intent.putExtra("timeid", spStr1[0]);//获取id
				//intent.putExtra("", "");
//				Bundle bundle=new Bundle();
//	            bundle.putString("result", "第一个activity的内容");
//	            bundle.putString("content",content);
//	            intent.putExtras(bundle);
				startActivity(intent);
				//finish();//跳转后结束dialog
			}
		});
		/**
		 * cancel
		 */
		builder.setNegativeButton("cancel",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						//finish();
					}
				});
		final AlertDialog dlg = builder.create();
		dlg.show();

	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		dbAdapter.close();
		handler.removeCallbacks(runnable);//关闭定时器
	}
	//暂停时停止定时器
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		handler.removeCallbacks(runnable);//停止定时器
	}
	//重启时启动定时器,定时器一直放在初始化中一直执行太耗内存,但会出现少许延迟
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		handler.removeCallbacks(runnable);
		handler.postDelayed(runnable,200);
	}
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		handler.removeCallbacks(runnable);//停止定时器
	}
	/**
	 * 图片对话框
	 */
	protected void photodialog() {
		  AlertDialog.Builder builder = new Builder(this);

		  builder.setIcon(R.drawable.welcome);
		  builder.setTitle("welcome");
		  //builder.setMessage("welcome");
		  builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
			  public void onClick(DialogInterface dialog, int which) {

		   }
		  });
		  builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			  public void onClick(DialogInterface dialog, int which) {

		   }
		  });
		  builder.create().show();
		}
}

布局代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:textColor="@color/white"
            android:background="#00000000"
            android:layout_marginLeft="20dip"
            android:id="@+id/set"
            android:text="@string/set"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <TextView
            android:layout_marginLeft="65dip"
            android:gravity="center_horizontal"
            android:textSize="30sp"
            android:textColor="@color/pink"
            android:text="@string/diary"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <Button
            android:textColor="@color/white"
            android:background="#00000000"
            android:text="@string/writedrary"
            android:layout_marginLeft="65dip"
            android:id="@+id/writediary"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

    </LinearLayout>
    <!-- android:listSelector="@drawable/listview_item_line" -->

    <!-- android:background="@drawable/view_yuan_morelist"  -->
    <ListView

        android:id="@+id/diaryshow"
        android:scrollbars="vertical"
        android:background="@drawable/writediary1"
        android:layout_width="fill_parent"
        android:divider="#FFF"
        android:dividerHeight="2dip"
        android:listSelector="@color/lightpink"
        android:cacheColorHint="@android:color/transparent"
        android:layout_height="520dip"/>

    <LinearLayout

        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <Button
            android:textColor="@color/white"
            android:background="#00000000"
            android:layout_marginLeft="25dip"
        	android:text="@string/deletediary"
            android:id="@+id/deletediary"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <Button
            android:textColor="@color/white"
            android:background="#00000000"
            android:layout_marginLeft="60dip"
       		android:text="@string/scandiary"
            android:id="@+id/scandiary"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
        <Button
            android:textColor="@color/white"
            android:background="#00000000"
            android:layout_marginLeft="60dip"
       		android:text="@string/firstfinish"
            android:id="@+id/firstfinish"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

    </LinearLayout>

</LinearLayout>

数据库各种操作方法实现类代码:

package tree.love.Adapter;

import tree.love.Bean.People;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;

/**
 * @author
 *
 */
public class DBAdapter
{
    public static final String DB_ACTION="db_action";//LogCat

    private static final String DB_NAME="people.db";//数据库名
    private static final String DB_TABLE="peopleinfo";//数据库表名
    private static final int    DB_VERSION=1;//数据库版本号

    public static final String KEY_ID = "_id";  //表属性ID
    public static final String KEY_NAME = "name";//表属性name
    public static final String KEY_AGE  = "age";//表属性age
    public static final String KEY_HEIGHT = "height";//表属性height

    private SQLiteDatabase db ;
    private Context xContext ;
    private DBOpenHelper dbOpenHelper ;
    public DBAdapter(Context context)
    {
        xContext = context ;
    }

    /**
     * 空间不够存储的时候设为只读
     * @throws SQLiteException
     */
    public void open() throws SQLiteException
    {
        dbOpenHelper = new DBOpenHelper(xContext, DB_NAME, null,DB_VERSION);
        try
        {
            db = dbOpenHelper.getWritableDatabase();
        }
        catch (SQLiteException e)
        {
            db = dbOpenHelper.getReadableDatabase();
        }
    }

    public void close()
    {
        if(db != null)
        {
            db.close();
            db = null;
        }
    }
    /**
     * 向表中添加一条数据
     * @param people
     * @return
     */
    public long insert(People people)
    {
        ContentValues newValues = new ContentValues();

        newValues.put(KEY_NAME, people.Diary);
        newValues.put(KEY_AGE, people.Time);
       // newValues.put(KEY_HEIGHT, people.Height);

        return db.insert(DB_TABLE, null, newValues);
    }

    /**
     * 删除一条数据
     * @param id
     * @return
     */
    public long deleteOneData(long id)
    {
        return db.delete(DB_TABLE, KEY_ID+"="+id, null );
    }
    /**
     * 删除所有数据
     * @return
     */
    public long deleteAllData()
    {
        return db.delete(DB_TABLE, null, null);
    }
    /**
     * 根据id查询数据的代码
     * @param id
     * @return
     */
    public People[] queryOneData(long id)
    {
        Cursor result = db.query(DB_TABLE, new String[] {KEY_ID,KEY_NAME,KEY_AGE,KEY_HEIGHT},
                KEY_ID+"="+id, null, null, null, null);
        return ConvertToPeople(result) ;
    }
    /**
     * 查询全部数据的代码
     * @return
     */
    public People[] queryAllData()
    {
        Cursor result = db.query(DB_TABLE, new String[] {KEY_ID,KEY_NAME,KEY_AGE,KEY_HEIGHT},
                null, null, null, null, null);
        return ConvertToPeople(result);
    }
    /**
     * 更新数据
     * @param id
     * @param people
     * @return
     */
    public long updateOneData(long id ,People people)
    {
        ContentValues newValues = new ContentValues();

        newValues.put(KEY_NAME, people.Diary);
        newValues.put(KEY_AGE, people.Time);
       // newValues.put(KEY_HEIGHT, people.Height);

        return db.update(DB_TABLE, newValues, KEY_ID+"="+id, null);
    }

    private People[] ConvertToPeople(Cursor cursor)
    {
        int resultCounts = cursor.getCount();
        if(resultCounts == 0 || !cursor.moveToFirst())
        {
            return null ;
        }
        People[] peoples = new People[resultCounts];
        Log.i(DB_ACTION, "PeoPle len:"+peoples.length);
        for (int i = 0; i < resultCounts; i++)
        {
            peoples[i] = new People();
            peoples[i].ID = cursor.getInt(0);
            peoples[i].Diary = cursor.getString(cursor.getColumnIndex(KEY_NAME));
            peoples[i].Time  = cursor.getString(cursor.getColumnIndex(KEY_AGE));
           // peoples[i].Height = cursor.getFloat(cursor.getColumnIndex(KEY_HEIGHT));
            Log.i(DB_ACTION, "people "+i+"info :"+peoples[i].toString());
            cursor.moveToNext();
        }
        return peoples;
    }

    /**
     * 静态Helper类,用于建立、更新和打开数据库
     */
    private static class DBOpenHelper extends SQLiteOpenHelper
    {
        /*
         * 手动建库代码
        CREATE TABLE peopleinfo
        (_id integer primary key autoincrement,
        name text not null,
        age integer,
        height float);*/
        private static final String DB_CREATE=
        "CREATE TABLE "+DB_TABLE
        +" ("+KEY_ID+" integer primary key autoincrement, "
        +KEY_NAME+" text not null, "
        +KEY_AGE+" integer,"+
        KEY_HEIGHT+" float);";
        public DBOpenHelper(Context context, String name,
                CursorFactory factory, int version)
        {
            super(context, name, factory, version);
        }

        @Override
        public void onCreate(SQLiteDatabase db)
        {
            db.execSQL(DB_CREATE);
            Log.i(DB_ACTION, "onCreate");
        }

        @Override
        public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion)
        {
            //函数在数据库需要升级时被调用,
            //一般用来删除旧的数据库表,
            //并将数据转移到新版本的数据库表中
            _db.execSQL("DROP TABLE IF EXISTS "+DB_TABLE);
            onCreate(_db);
            Log.i(DB_ACTION, "Upgrade");
        }

    }
}

数据格式定义代码

package tree.love.Bean;

public class People {
	public int ID = -1;
	public String Diary;
	public String Time;
	@Override
    public String toString()
    {
        String result =this.ID+","+
        		"时间:"+this.Time+","
        		+"日记内容:"+this.Diary;
        return result;
    }
}

实现效果图

详细可看下载代码看:点击打开链接

时间: 2024-08-01 20:50:18

android 记事本程序源码的相关文章

Android 开发的QQ程序源码

Android 开发的QQ程序源码 网上下载的一款Android 开发的QQ程序源码,其中有大量的注释.项目中有错误不能直接运行,有兴趣的朋友可以下载看下. 下载地址:http://www.devstore.cn/code/info/841.html  运行截图:

微信小程序源码下载(200多个)

微信小程序源码下载汇总,点击标题进入对应的微信小程序下载页面. 最新 demo源码(点击标题进入帖子下载) 描述 1 微信小程序 会议室预定小程序 微信小程序 会议室预定小程序**** 本内容被作者隐藏 **** 2 微信小程序-双人五子棋小游戏 微信小程序-双人五子棋小游戏**** 本内容被作者隐藏 **** 3 打卡签到小程序 用微信小程序实现的一个简单的打卡签到的小程序拒绝 4 微信小程序---左滑删除 微信小程序---左滑删除**** 本内容被作者隐藏 **** 5 一个借钱的记事本的微

[Android 编译(一)] Ubuntu 16.04 LTS 成功编译 Android 6.0 源码教程

本文转载自:[Android 编译(一)] Ubuntu 16.04 LTS 成功编译 Android 6.0 源码教程 1 前言 经过3天奋战,终于在Ubuntu 16.04上把Android 6.0的源码编译出来了,各种配置,各种error,各种爬坑,特写此博客记录爬坑经历.先上图,Ubuntu上编译完后成功运行模拟器,如图: 2 编译环境 UbuntuKylin 16.04 LTS Android 6.0_r1 Open JDK 7 3 准备工作 (1) 下载android 6.0源码.

微信小程序_微信小程序开发,小程序源码、案例、教程

原文地址:http://whosmall.com/?post=448 本文标签: 微信小程序 小程序源码案例 小程序项目 小程序源码 微信小程序教程 什么是微信小程序? 微信小程序是微信基于微信平台的一个应用发布平台,微信小程序app开发属于原生app组件提供js接口的开发方式,比混合是app的用户体验更好,仅次于原生应用. 不过微信小程序定位于小,要符合轻量易用无需下载,所以从体积上也是有限制,整个小程序应用体积不能超过1M. 微信小程序的应用场景? 微信小程序的应用场景适用于轻量应用,非强交

【小程序源码案例】微信小程序项目开发案例分享

作者:web小二本文标签: 微信小程序 小程序源码案例 小程序项目小程序的开发,并不是适合所有公司,我今天跟大家分享小程序方面的教程,主要是供大家学习使用.学习这种东西,有时候则是单纯的喜欢,没有任何目的,很单纯的为了好玩,记得很早之前学flash,没有想法,就是觉得好玩,纯娱乐爱好而已.到后来玩视频剪辑也是出于同样的原因,不图钱财名利,只是图自己个人爱好娱乐. 但是,学习,有时候则是需要有明确目的,特别是关系到自己吃饭问题的时候,你就需要非常有目的去学习,并且还需要制定好学习的计划与目标,希望

Android -- 消息处理机制源码分析(Looper,Handler,Message)

android的消息处理有三个核心类:Looper,Handler和Message.其实还有一个Message Queue(消息队列),但是MQ被封装到Looper里面了,我们不会直接与MQ打交道,因此我没将其作为核心类.下面一一介绍: Looper Looper的字面意思是“循环者”,它被设计用来使一个普通线程变成Looper线程.所谓Looper线程就是循环工作的线程.在程序开发中(尤其是GUI开发中),我们经常会需要一个线程不断循环,一旦有新任务则执行,执行完继续等待下一个任务,这就是Lo

Ubuntu 16.04 LTS 成功编译 Android 6.0 源码教程 (转)

1 前言 经过3天奋战,终于在Ubuntu 16.04上把Android 6.0的源码编译出来了,各种配置,各种error,各种爬坑,特写此博客记录爬坑经历.先上图,Ubuntu上编译完后成功运行模拟器,如图: 2 编译环境 UbuntuKylin 16.04 LTS Android 6.0_r1 Open JDK 7 3 准备工作 (1) 下载Android 6.0源码. Androdi 6.0源码下载地址: http://pan.baidu.com/s/1o6N86a2 感谢下面这位博主上传

Android 开源项目源码解析(第二期)

Android 开源项目源码解析(第二期) 阅读目录 android-Ultra-Pull-To-Refresh 源码解析 DynamicLoadApk 源码解析 NineOldAnimations 源码解析 SlidingMenu 源码解析 Cling 源码解析 BaseAdapterHelper 源码分析 Side Menu.Android 源码解析 DiscreteSeekBar 源码解析 CalendarListView 源码解析 PagerSlidingTabStrip 源码解析 公共

[Android编译(二)] 从谷歌官网下载android 6.0源码、编译并刷入nexus 6p手机

1 前言 经过一周的奋战,终于从谷歌官网上下载最新的android 6.0.1_r62源码,编译成功,并成功的刷入nexus6p,接着root完毕,现写下这篇博客记录一下实践过程. 2 简介 自己下载android系统源码,修改定制,然后编译刷入安卓手机,想想还有点小激动呢.简单点说一句话--定制我们自己的MIUI,这就是android的魅力,这篇博客博主就来教大家实现自己的定制系统. 首先,要明白下面的基础知识: (1) 什么是aosp? aosp就是android open source p