1. 程式人生 > >極客學院案例-記事本程式碼

極客學院案例-記事本程式碼

*資料庫檔案NotesDB

package com.jikexueyuan.hellonotes;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class NotesDB extends SQLiteOpenHelper {
    public
static final String TABLE_NAME = "notes"; public static final String CONTENT = "content"; public static final String ID = "_id"; public static final String TIME = "time"; public static final String PATH = "path"; public static final String VIDEO = "video"; public NotesDB(Context context) { super
(context, "notes", null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + TABLE_NAME + "(" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + CONTENT + " TEXT NOT NULL," + PATH + " TEXT NOT NULL," + VIDEO + " TEXT NOT NULL,"
+ TIME + " TEXT NOT NULL)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }

MainActivity頁面

package com.jikexueyuan.hellonotes;


import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;

public class MainActivity extends Activity implements OnClickListener {
    private NotesDB notesDB;
    private SQLiteDatabase dbReader;
    private Button textbtn, imgbtn, videobtn;
    private ListView lv;
    private Intent i;
    private MyAdapter adapter;
    private Cursor cursor;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    public void initView() {
        lv = (ListView) findViewById(R.id.list);
        textbtn = (Button) findViewById(R.id.text);
        imgbtn = (Button) findViewById(R.id.img);
        videobtn = (Button) findViewById(R.id.video);
        textbtn.setOnClickListener(this);
        imgbtn.setOnClickListener(this);
        videobtn.setOnClickListener(this);

        notesDB = new NotesDB(this);//初始化資料庫檔案,獲取資料庫例項
        dbReader = notesDB.getReadableDatabase();//獲取讀取許可權
        /**
         * 實現listview每個子項的單機事件
         */
        lv.setOnItemClickListener(new OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                Log.d("TAG", position+"");
                Log.d("TAG", id+"");
                cursor.moveToPosition(position);//指標指向當前使用者點選的位置position,利用指標取出這個位置在資料庫的其他列資料
                Intent intent = new Intent(MainActivity.this,SelectAtc.class);
                intent.putExtra(NotesDB.ID, cursor.getInt(cursor.getColumnIndex(NotesDB.ID)));
                intent.putExtra(NotesDB.CONTENT, cursor.getString(cursor.getColumnIndex(NotesDB.CONTENT)));
                intent.putExtra(NotesDB.TIME, cursor.getString(cursor.getColumnIndex(NotesDB.TIME)));
                intent.putExtra(NotesDB.VIDEO, cursor.getString(cursor.getColumnIndex(NotesDB.VIDEO)));
                intent.putExtra(NotesDB.PATH, cursor.getString(cursor.getColumnIndex(NotesDB.PATH)));
                startActivity(intent);

            }



        });
    } 

    public void selectDB(){
        Cursor cursor = dbReader.query(NotesDB.TABLE_NAME, null, null, null, null, null, null);
        adapter = new MyAdapter(this,cursor);//呼叫介面卡頁面
        lv.setAdapter(adapter);
    }

    @Override
    public void onClick(View v) {
        i = new Intent(this, AddContent.class);
        switch (v.getId()) {
        case R.id.text:
            i.putExtra("flag", "1");
            startActivity(i);
            break;
        case R.id.img:
            i.putExtra("flag", "2");
            startActivity(i);
            break;
        case R.id.video:
            i.putExtra("flag", "3");
            startActivity(i);
            break;
        }

    }
    //在onResume()中來實現資料庫的載入
    @Override
    protected void onResume() {
        super.onResume();
        selectDB();
    }



}

介面卡頁面

package com.jikexueyuan.hellonotes;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MyAdapter extends BaseAdapter {

    private Context context;
    private Cursor cursor;
    private LinearLayout layout;

    // 傳遞上下文環境context,以及指標給介面卡
    public MyAdapter(Context context, Cursor cursor) {
        this.context = context;
        this.cursor = cursor;

    }

    @Override
    public int getCount() {
        return cursor.getCount();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater =LayoutInflater.from(context);//從當前 context中獲取佈局載入器
       //LayoutInflater layout =  (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        layout = (LinearLayout)inflater.inflate(R.layout.cell, null);//載入xml檔案cell,成為當前的佈局
        //從當前佈局中取出各個UI元件
        TextView contentTv= (TextView)layout.findViewById(R.id.list_content);
        TextView timeTv= (TextView)layout.findViewById(R.id.list_time);
        ImageView imgIv= (ImageView)layout.findViewById(R.id.list_img);
        ImageView videoIv= (ImageView)layout.findViewById(R.id.list_video);

        cursor.moveToPosition(position);
        String content = cursor.getString(cursor.getColumnIndex("content"));
        String time = cursor.getString(cursor.getColumnIndex("time"));
        String uri = cursor.getString(cursor.getColumnIndex("path"));
        String uri_video = cursor.getString(cursor.getColumnIndex("video"));
        contentTv.setText(content);
        timeTv.setText(time);
        videoIv.setImageBitmap(getVideoThumbnail(uri_video,200,200,MediaStore.Images.Thumbnails.MICRO_KIND));
        imgIv.setImageBitmap(getImageThumbnail(uri,200,200));
        return layout;
    }

    // 獲取相機照片的縮圖,直接獲取原始圖片會觸發系統 oom錯誤
    public Bitmap getImageThumbnail(String uri, int width, int height) {
        //72-75行是為了防止發生圖片過大導致記憶體溢位錯誤,用BitmapFactory.Options的方法,得到bitmap=要取出圖片的寬和高資訊
        Bitmap bitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        bitmap = BitmapFactory.decodeFile(uri, options);
        options.inJustDecodeBounds = false;//取出bitmap資訊之後關閉options.inJustDecodeBounds,與上面成對出現

        int beWidth = options.outWidth / width;
        int beHeight = options.outHeight / height;
        int be = 1;
        if (beWidth < beHeight) {
            be = beWidth;
        } else {
            be = beHeight;
        }
        if (be <= 0) {
            be = 1;
        }
        options.inSampleSize = be;
        bitmap = BitmapFactory.decodeFile(uri, options);//根據uri地址取出bitmap,同時options不為空時,這個bitmap將按照前面這隻的比例顯示
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
                ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        return bitmap;

    }

    private Bitmap getVideoThumbnail(String uri, int width, int height, int kind) {
        Bitmap bitmap = null;
        bitmap = ThumbnailUtils.createVideoThumbnail(uri, kind);
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
                ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        return bitmap;
    }
}

新增資料頁面

package com.jikexueyuan.hellonotes;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.VideoView;

public class AddContent extends Activity implements OnClickListener {
    private String val;
    private Button savebtn, deletebtn;
    private ImageView c_img;
    private EditText ettext;
    private VideoView v_video;
    private NotesDB notesDB;
    private SQLiteDatabase dbWriter;
    private File phoneFile;
    private File videoFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addcontent);
        val = getIntent().getStringExtra("flag");// 接受前面傳遞的按鈕型別
        savebtn = (Button) findViewById(R.id.save);
        deletebtn = (Button) findViewById(R.id.delete);
        c_img = (ImageView) findViewById(R.id.c_img);
        v_video = (VideoView) findViewById(R.id.c_video);
        ettext = (EditText) findViewById(R.id.text);
        savebtn.setOnClickListener(this);
        deletebtn.setOnClickListener(this);

        notesDB = new NotesDB(this);
        dbWriter = notesDB.getWritableDatabase();
        initView();
    }

    private void initView() {
        if (val.equals("1")) {// 新增的是文字
            c_img.setVisibility(View.GONE);
            v_video.setVisibility(View.GONE);
        }
        if (val.equals("2")) {// 新增的是圖片
            c_img.setVisibility(View.VISIBLE);
            v_video.setVisibility(View.GONE);
            Intent iimg = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 跳轉到系統相機
            // /storage/emulated/0/2016年12月07日 02:19:49.jpg
            phoneFile = new File(Environment.getExternalStorageDirectory()
                    .getAbsoluteFile() + "/" + getTime() + ".jpg");// 絕對路徑+圖片名稱
            iimg.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(phoneFile));
            Log.d("TAG", phoneFile + "");
            startActivityForResult(iimg, 1);
        }
        if (val.equals("3")) {
            c_img.setVisibility(View.GONE);
            v_video.setVisibility(View.VISIBLE);

            Intent video = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);// 跳轉到系統相機
            // /storage/emulated/0/2016年12月07日 02:19:49.jpg
            videoFile = new File(Environment.getExternalStorageDirectory()
                    .getAbsoluteFile() + "/" + getTime() + ".mp4");// 絕對路徑+圖片名稱
            video.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(videoFile));
            Log.d("TAG", videoFile + "");
            startActivityForResult(video, 2);



        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.save:
            addDB();
            finish();
            break;
        case R.id.delete:
            finish();
            break;
        }

    }

    public void addDB() {
        ContentValues cv = new ContentValues();
        cv.put(NotesDB.CONTENT, ettext.getText().toString());
        cv.put(NotesDB.TIME, getTime());
        Log.d("TAG", phoneFile+"");
        cv.put(NotesDB.PATH, phoneFile+"");
        cv.put(NotesDB.VIDEO, videoFile+"");
        dbWriter.insert(NotesDB.TABLE_NAME, null, cv);
    }

    private String getTime() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        Date date = new Date();
        String str = format.format(date);
        return str;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            Bitmap bitmap = BitmapFactory.decodeFile(phoneFile
                    .getAbsolutePath());
            c_img.setImageBitmap(bitmap);
        }
        if(requestCode ==2){
            v_video.setVideoURI(Uri.fromFile(videoFile));
            v_video.start();
        }
    }
}

幾個XML檔案
activity_main.xml

addcontent.xml
cell.xml頁面

select.xml