先上两张应用截图
编辑界面
删除一条记录时
此应用共包括2个activity 主界面列表显示所有便笺的MainActivity和添加一条便笺的编辑界面SecondActivity
MainActivity
主要使用一个listView显示数据库中所有便笺 并添加点击条目编辑 长按条目删除
代码如下
public class MainActivity extends AppCompatActivity {
private Button button;
private ListView listView;
private MyDataBase myDataBase;
private LayoutInflater layoutInflater;
private ArrayList<Note> arrayList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
layoutInflater = getLayoutInflater();
myDataBase = new MyDataBase(this);
button = (Button) findViewById(R.id.button1);
arrayList = myDataBase.getArray();
MyAdapter myAdapter = new MyAdapter(layoutInflater,arrayList);
listView.setAdapter(myAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView,View view,int i,long l) {
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra("id",arrayList.get(i).getId());
startActivity(intent);
MainActivity.this.finish();
}
});
/** * 参数 parent 发生点击事件的 AbsListView。 view AbsListView 中被点击的视图。 position 视图在一览中的位置(索引)。 id 被点击条目的行 ID。 返回值 如果回调函数处理了长按事件,返回真;否则返回假。 */
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView,final int position,long l) {
new AlertDialog.Builder(MainActivity.this).setTitle("删除").setMessage("数据无价,谨慎操作!")
.setNegativeButton("关闭",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface,int i) {
}
}).setPositiveButton("删除",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface,int i) {
myDataBase.deleteNote(arrayList.get(position).getId());
arrayList = myDataBase.getArray();
MyAdapter myAdapter = new MyAdapter(layoutInflater,arrayList);
listView.setAdapter(myAdapter);
}
}).create().show();
return true;
}
});
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
startActivity(intent);
MainActivity.this.finish();
}
});
}
###SecondActivity 实现新建和编辑一条便笺的功能
和主界面通过Intent进行交互 并保存到数据库中
代码如下
public class SecondActivity extends Activity{
Button save;
TextView textView1; //标题
TextView textView2; //内容
EditText title;
EditText content;
MyDataBase myDataBase;
Note note2; //第二个activity里面的note
int id;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); save=(Button)findViewById(R.id.save); textView1=(TextView)findViewById(R.id.t1); textView2=(TextView)findViewById(R.id.t2); title=(EditText)findViewById(R.id.title2); content=(EditText)findViewById(R.id.content2); myDataBase=new MyDataBase(this); id=getIntent().getIntExtra("id",0); if(id!=0){ note2=myDataBase.getTitleandContent(id); title.setText(note2.getTitle()); content.setText(note2.getContent()); } save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isSave(); } } ); } @RequiresApi(api = Build.VERSION_CODES.N) @Override public void onBackPressed() { /* SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); */Date currentDate=new Date(System.currentTimeMillis());//获取当前时间 String time=currentDate.toLocaleString(); //simpleDateFormat.format(currentDate); String titles=title.getText().toString(); String contents=content.getText().toString(); //修改数据 if (id != 0) { note2 = new Note( id,titles,contents,time); myDataBase.toUpdate(note2); Intent intent = new Intent(SecondActivity.this,MainActivity.class); startActivity(intent); SecondActivity.this.finish(); } //新建文本 else { note2 = new Note(titles,time); myDataBase.toInsert(note2); Intent intent = new Intent(SecondActivity.this,MainActivity.class); startActivity(intent); SecondActivity.this.finish(); } } private void isSave(){ java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); Date curDate = new Date(System.currentTimeMillis());//获取当前系统时间 String times = formatter.format(curDate); String titles=title.getText().toString(); String contents=content.getText().toString(); //修改数据 if (id!=0) { note2 = new Note(id,times); myDataBase.toUpdate(note2); Intent intent = new Intent(SecondActivity.this,MainActivity.class); startActivity(intent); SecondActivity.this.finish(); } //新建一条便笺 else { if(titles!=null||contents!=null){ note2 = new Note(titles,times); myDataBase.toInsert(note2); } Intent intent = new Intent(SecondActivity.this,MainActivity.class); startActivity(intent); SecondActivity.this.finish(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main,menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub switch (item.getItemId()) { case R.id.action_settings: Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT,"标题" + title.getText().toString() + "内容" + content.getText().toString()); startActivity(intent); break; default: break; } return false; }
}
###数据库部分
MyDataBase 主要实现数据库的添加删除 修改 通过android提供的sqliteOpenHelper的自定义的子类MyDatabaseHelper实现对数据库的操作
MyDataBase代码
public class MyDataBase {
Context context;
sqliteDatabase sqliteDatabase;
MyDatabaseHelper myDatabaseHelper;
public MyDataBase(Context context){
this.context=context;
myDatabaseHelper=new MyDatabaseHelper(context);
}
public ArrayList getArray(){
ArrayList arrayList=new ArrayList();
ArrayList arrayList1=new ArrayList();
sqliteDatabase=myDatabaseHelper.getWritableDatabase();
//rawQuery()方法的第一个参数为select语句;
// 第二个参数为select语句中占位符参数的值,
// 如果select语句没有使用占位符,该参数可以设置为null。
Cursor cursor=sqliteDatabase.rawQuery(“select id,title,date from note”,null);
cursor.moveToFirst(); while (!cursor.isAfterLast()){ int id=cursor.getInt(cursor.getColumnIndex("id")); String title=cursor.getString(cursor.getColumnIndex("title")); String date=cursor.getString(cursor.getColumnIndex("date")); Note note=new Note(id,date); arrayList.add(note); cursor.moveToNext(); }cursor.close(); sqliteDatabase.close(); for(int i=arrayList.size();i>0;i--){ arrayList1.add(arrayList.get(i-1)); } return arrayList1; //return arrayList; } //第二个activity用到的 标题+内容 public Note getTitleandContent( int id){ sqliteDatabase=myDatabaseHelper.getWritableDatabase(); Cursor cursor=sqliteDatabase.rawQuery("select title,content from note where id='"+id+"'",null); cursor.moveToFirst(); String title=cursor.getString(cursor.getColumnIndex("title")); String content =cursor.getString(cursor.getColumnIndex("content")); Note note=new Note(title,content); cursor.close(); return note; } //execsql(String sql,Object[] bindArgs)方法的第一个参数为sql语句, // 第二个参数为sql语句中占位符参数的值,参数值在数组中的顺序要和占位符的位置对应。 // 修改数据 public void toUpdate(Note note){ sqliteDatabase =myDatabaseHelper.getWritableDatabase(); sqliteDatabase.execsql("update note set title='"+ note.getTitle()+"',date='"+note.getDate()+"',content='"+note.getContent() +"' where id='"+ note.getId()+"'"); sqliteDatabase.close(); } //插入数据,新建一条便笺 public void toInsert(Note note){ sqliteDatabase=myDatabaseHelper.getWritableDatabase(); sqliteDatabase.execsql("insert into note(title,content,date) values('"+ note.getTitle()+"','"+note.getContent()+"','"+note.getDate()+"')"); sqliteDatabase.close(); } //删除一条数据 public void deleteNote(int id){ sqliteDatabase=myDatabaseHelper.getWritableDatabase(); sqliteDatabase.execsql("delete from note where id=" + id+ "" ); sqliteDatabase.close(); }
}
MyDatabaseHelper代码如下:
public class MyDatabaseHelper extends sqliteOpenHelper {
private Context context;
public static final String CREATE_NOTE=”create table if not exists note (id integer primary key autoincrement,title text,content text,date text)”;
public MyDatabaseHelper(Context context) {
super(context,“note”,null,1);
this.context=context;
}
@Override public void onCreate(sqliteDatabase sqliteDatabase) { sqliteDatabase.execsql(CREATE_NOTE); } @Override public void onUpgrade(sqliteDatabase sqliteDatabase,int i,int j) { }
}
###下面是一些实体和工具类
Note`public class Note {
private String title;
private String content;
private int id;
private String date;
public Note(int id,String title,String content,String date){
this.content=content;
this.title=title;
this.date=date;
this.id=id;
}
public Note(int id,String date){
this.date=date;
this.title=title;
this.id=id;
}
public Note(String title,String content){
this.title=title;
this.content=content;
}
public Note(String title,String date) {
this.title=title;
this.date=date;
this.content=content;
}
public String getTitle(){
return title;
}
public String getContent(){
return content;
}
public int getId(){
return id;
}
public String getDate(){
return date;
}
}
adapter以及优化listView的viewHolder
public class MyAdapter extends BaseAdapter {
LayoutInflater layoutInflater;
ArrayList arrayList;
public MyAdapter(LayoutInflater layoutInflater,ArrayList arrayList){
this.arrayList=arrayList;
this.layoutInflater=layoutInflater;
}
@Override
public int getCount() {
return arrayList.size();
}
@Override public Object getItem(int i) { return arrayList.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int i,ViewGroup viewGroup) { ViewHolder viewHolder=new ViewHolder(); if(view==null){ view=layoutInflater.inflate(R.layout.adapter_listview,null); viewHolder.textView1=(TextView)view.findViewById(R.id.textview1); viewHolder.textView2=(TextView)view.findViewById(R.id.textview2); view.setTag(viewHolder); } viewHolder=(ViewHolder)view.getTag(); viewHolder.textView1.setText(arrayList.get(i).getTitle()); viewHolder.textView2.setText(arrayList.get(i).getDate()); return view; }
}
public class ViewHolder {
TextView textView1;
TextView textView2;
}
“`