**
Android–小小记事本
**
1:文本数据的存储
2:图片数据存储
3:SQlite的创建
4:数据listview列表的显示
**
activity_main.xml布局文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.jl.festival_sms.MainActivity">
<TextView
android:id="@+id/tv_titile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="备忘录"
android:textSize="25sp"
android:textColor="#000000"
android:gravity="center"
android:background="@color/main_color"
android:padding="5dp"
/>
<ListView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_margin="5dp"
android:background="#FFFFFF"
>
</ListView>
<Button
android:id="@+id/bt_add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:padding="5dp"
android:text="添加备忘录"
/>
</LinearLayout>
edittext_activity.xml布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="编辑"
android:padding="5dp"
android:textSize="25dp"
android:gravity="center"
android:background="@color/main_color"
/>
<EditText
android:id="@+id/et_center"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="start"
android:textSize="18sp"
android:layout_margin="5dp"
/>
<TextView
android:id="@+id/tv_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#807c7c"
android:text="时间"
/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/bt_ok"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="保存"
/>
<Button
android:id="@+id/bt_cancel"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="取消"
/>
</LinearLayout>
</LinearLayout>
item.xml布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:textSize="20sp"
android:textColor="#000"
android:text="标题" />
<TextView
android:id="@+id/tv_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="时间" />
</LinearLayout>
数据库文件
定义了数据库中的表明,以及用到的数列,因为此项目仅对文字进行了保存,因此对变量都定义成static final类型的,使得名称和列名不可被更改。
在继承SQLiteDatabase 的时候不光需要实现 :
onUpgrade(SQLiteDatabse dv, int oldVersion,int new Version):当打开数据库时传入的版本号与当前的版本号不同时会调用该方法。
并且还需要调用其父类构造器 context是上下文,name为数据库的名字,Cursor的工厂类以及版本号
public MySQLiteHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}
数据库文件具体代码:
package com.example.jl.festival_sms;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by jl on 2017/7/27.
*/
public class DBHelper extends SQLiteOpenHelper {
public static final String TABLE_NAME="note";
public static final String ID = "id";
public static final String CONTENT = "content";
public static final String DATE = "date";
public static final String SQL="CREATE TABLE " + TABLE_NAME + " (" + ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT," + CONTENT
+ " TEXT NOT NULL," + DATE + " TEXT NOT NULL)";
public DBHelper(Context context){
super(context,TABLE_NAME,null,1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
}
主界面代码的实现
SQLiteDatabase : 获取数据库对象
ContentValues : 数据库的操作的时候需要ContentValues类 也是一个key对应一个数据
Bundle : 两个activity之间的通讯可以通过bundle类来实现,bundle类中加入数据(key-
value的形式,另一个activity里面取数据的时候,就要用到key,找出对应的
value)。加入到intent的当中使用intent.putExtras()方法。
package com.example.jl.festival_sms;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.app.AlertDialog.Builder;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements OnItemClickListener, OnItemLongClickListener {
private ListView mListView;
private Button mButton;
private TextView tv_content;
private DBHelper dbHelper;
private SQLiteDatabase DB;
private SimpleAdapter simple_adapter;
private List<Map<String, Object>> dataList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
//初始化视图
private void init() {
tv_content = (TextView) findViewById(R.id.tv_content);
mListView = (ListView) findViewById(R.id.lv);
mButton = (Button) findViewById(R.id.bt_add);
dataList = new ArrayList<Map<String, Object>>();
dbHelper = new DBHelper(this);
DB = dbHelper.getReadableDatabase();
mListView.setOnItemClickListener(this);
mListView.setOnItemLongClickListener(this);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,EditActivity.class);
Bundle bundle = new Bundle();
bundle.putString("info","");
bundle.putInt("enter_state",0);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
//当页面重新打开的时候
@Override
protected void onStart() {
super.onStart();
//刷新页面
RefreshNotesList();
}
private void RefreshNotesList() {
//如果dataList已经有的内容,全部删掉
//并且更新simp_adapter
int size = dataList.size();
if(size>0){
dataList.removeAll(dataList);
simple_adapter.notifyDataSetChanged();
}
//从数据库读取信息
Cursor cursor = DB.query("note", null, null, null, null, null, null);
startManagingCursor(cursor);
while (cursor.moveToNext()){
String name = cursor.getString(cursor.getColumnIndex("content"));
String date = cursor.getString(cursor.getColumnIndex("date"));
Map<String,Object> map = new HashMap<>();
map.put("tv_content",name);
map.put("tv_date",date);
dataList.add(map);
}
simple_adapter =new SimpleAdapter(this,dataList,R.layout.item,new String[]{"tv_content","tv_date"}
,new int[]{R.id.tv_content,R.id.tv_date});
mListView.setAdapter(simple_adapter);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String content = mListView.getItemAtPosition(position) + "";
String content1 = content.substring(content.indexOf("=") + 1, content.indexOf(","));
Intent Intent = new Intent(MainActivity.this, EditActivity.class);
Bundle bundle = new Bundle();
bundle.putString("info", content1);
bundle.putInt("enter_state", 1);
Intent.putExtras(bundle);
startActivity(Intent);
}
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
Builder builder = new Builder(this);
builder.setTitle("删除该日志");
builder.setMessage("确认删除吗?");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//获取listview中此个item中的内容
//删除该行后刷新listview的内容
String content = mListView.getItemAtPosition(position) + "";
String content1 = content.substring(content.indexOf("=") + 1,
content.indexOf(","));
DB.delete("note", "content = ?", new String[]{content1});
RefreshNotesList();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create();
builder.show();
return true;
}
}
编辑界面
package com.example.jl.festival_sms;
import android.app.Activity;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by jl on 2017/7/27.
*/
public class EditActivity extends Activity implements View.OnClickListener {
private TextView tv_date;
private EditText et_content;
private Button bt_ok;
private Button bt_cancel;
private DBHelper DBHelper;
public int ENTER_STATIC = 0;//用来区分是新建一个note还是更改原来的note
public String last_content;//用来获取edittext内容
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edittext_activity);
init();
}
private void init() {
tv_date = (TextView) findViewById(R.id.tv_data);
et_content = (EditText) findViewById(R.id.et_center);
bt_ok = (Button) findViewById(R.id.bt_ok);
bt_cancel = (Button) findViewById(R.id.bt_cancel);
DBHelper = new DBHelper(this);
//获取此时时刻时间
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String dateString = sdf.format(date);
tv_date.setText(dateString);
//接收内容和id
Bundle myBundle = this.getIntent().getExtras();
last_content = myBundle.getString("info");
ENTER_STATIC = myBundle.getInt("enter_state");
et_content.setText(last_content);
//设置其点击事件
bt_ok.setOnClickListener(this);
bt_cancel.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.bt_ok:
SQLiteDatabase db =DBHelper.getReadableDatabase();
// 获取输入框的内容
String mesg = et_content.getText().toString();
//添加
if(ENTER_STATIC==0){
if(!mesg.isEmpty()){
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String dateString = sdf.format(date);
//向数据库添加信息
ContentValues cv = new ContentValues();
cv.put("content",mesg);
cv.put("date",dateString);
db.insert("note",null,cv);
}else {
Toast.makeText(getBaseContext(),"请输入内容",Toast.LENGTH_LONG).show();
}
}else {
// 查看并修改一个已有的日志
ContentValues cv = new ContentValues();
cv.put("content",mesg);
db.update("note",cv,"content=?",new String[]{last_content});
}
finish();
break;
case R.id.bt_cancel:
finish();
break;
default:
break;
}
}
}
SQlite有个问题,就是主键不能够自动排序。比如说主键id为1 2 3 4,共4条记录。现在删除2 3,还剩下1 4记录,当再次插入时,id会变成5,而不是2.假设在初始4条记录的基础上,把这4条记录全都删掉,再次插入时,得到的id是5.
所以,需要从listview的每个item中获取内容,然后到数据库中通过内容搜索该记录,最后对其进行操作。