SQLite是Android系统内置的轻量级的关系型数据库,运行速度非常快;ListView是Android中最常用的的控件之一,几乎所有的应用程序都会用到它。本文通过一个实例介绍如何通过ListView列表展示数据以及实现SQLite数据库的增删改查,并且用到了登录、动画等功能。
首先,新建Android应用程序FileDemo2。代码如下:
1、src文件夹内,com.demo.adapter包内FileNameAdapter.java文件:
public class FileNameAdapter extends ArrayAdapter {
private int resourceId;
public FileNameAdapter(Context context, int resource, List objects) {
super(context, resource, objects);
resourceId=resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
FileName fileName=getItem(position);
View view;
ViewHolder viewHolder;
if (convertView==null) {
view=LayoutInflater.from(getContext()).inflate(resourceId, null);
viewHolder=new ViewHolder();
viewHolder.fileName=(TextView)view.findViewById(R.id.file_name);
viewHolder.fileAuthor=(TextView)view.findViewById(R.id.file_author);
viewHolder.id=0;
view.setTag(viewHolder);
} else {
view=convertView;
viewHolder=(ViewHolder)view.getTag();
}
viewHolder.fileName.setText(fileName.getName());
viewHolder.fileAuthor.setText(fileName.getAuthor());
viewHolder.id=fileName.getId();
return view;
}
class ViewHolder{
TextView fileName;
TextView fileAuthor;
int id;
}
}
2、src文件夹内,com.demo. beans包内FileName.java文件:
public class FileName {
private int id;
private String name;
private String author;
public FileName(int id,String name, String author) {
this.id=id;
this.name = name;
this.author = author;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getAuthor() {
return author;
}
public void setName(String name) {
this.name = name;
}
public void setAuthor(String author) {
this.author = author;
}
}
3、src文件夹内,com.demo.data包内MyDatabaseHelper.java文件(创建数据库):
public class MyDatabaseHelper extends SQLiteOpenHelper {
public static final String CREATE_MENUNAME="create table MenuName ("
+"id integer primary key autoincrement, "
+"menuname text, "
+"isChosen boolean)";
public static final String CREATE_FILE="create table FileInfo("
+"id integer primary key autoincrement, "
+"title text, "
+"subtitle text, "
+"author text, "
+"partone text, "
+"parttwo text, "
+"partthree text, "
+"partfour text)";
private Context mContext;
public MyDatabaseHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
mContext=context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_MENUNAME);
db.execSQL("insert into MenuName (menuname,isChosen) values (?,?)",new String[]{"标题","1"});
db.execSQL("insert into MenuName (menuname,isChosen) values (?,?)",new String[]{"副标题","1"});
db.execSQL("insert into MenuName (menuname,isChosen) values (?,?)",new String[]{"作者","1"});
db.execSQL("insert into MenuName (menuname,isChosen) values (?,?)",new String[]{"版块一","1"});
db.execSQL("insert into MenuName (menuname,isChosen) values (?,?)",new String[]{"版块二","1"});
db.execSQL("insert into MenuName (menuname,isChosen) values (?,?)",new String[]{"版块三","1"});
db.execSQL("insert into MenuName (menuname,isChosen) values (?,?)",new String[]{"版块四","1"});
db.execSQL(CREATE_FILE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
4、src文件夹内,com.demo.filedemo2包内ActivityCollector.java文件:
public class ActivityCollector {
public static List activities = new ArrayList();
//添加activity
public static void addActivity(Activity activity){
activities.add(activity);
}
//移除activity
public static void removeActivity(Activity activity){
activities.remove(activity);
}
//退出
public static void finishAll(){
for(Activity activity:activities){
if (!activity.isFinishing()) {
activity.finish();
}
}
}
}
5、src文件夹内,com.demo.filedemo2包内BaseActivity.java文件:
public class BaseActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityCollector.addActivity(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
ActivityCollector.removeActivity(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item_show:
Intent intent=new Intent(BaseActivity.this, ShowFileNameActivity.class);
startActivity(intent);
break;
case R.id.exit:
ActivityCollector.finishAll();
break;
default:
break;
}
return true;
}
}
6、src文件夹内,com.demo.filedemo2包内FileItemActivity.java文件:
public class FileItemActivity extends BaseActivity {
private EditText titleText;
private EditText subtitleText;
private EditText authorText;
private EditText partoneText;
private EditText parttwoText;
private EditText partthreeText;
private EditText partfourText;
private Button updateBtn;
private MyDatabaseHelper dbHelper;
public static void actionStart(Context context,String fileid){
Intent intent =new Intent(context,FileItemActivity.class);
intent.putExtra("id", fileid);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fileitem);
final String fileid=getIntent().getStringExtra("id");
titleText=(EditText)findViewById(R.id.title);
subtitleText=(EditText)findViewById(R.id.subtitle);
authorText=(EditText)findViewById(R.id.author);
partoneText=(EditText)findViewById(R.id.partone);
parttwoText=(EditText)findViewById(R.id.parttwo);
partthreeText=(EditText)findViewById(R.id.partthree);
partfourText=(EditText)findViewById(R.id.partfour);
updateBtn=(Button)findViewById(R.id.update);
dbHelper = new MyDatabaseHelper(this, "FileDemo.db", null, 1);
final SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor=db.rawQuery("select * from FileInfo where id=?", new String[]{fileid});
if (cursor.moveToFirst()) {
String title=cursor.getString(cursor.getColumnIndex("title"));
String subtitle=cursor.getString(cursor.getColumnIndex("subtitle"));
String author=cursor.getString(cursor.getColumnIndex("author"));
String partone=cursor.getString(cursor.getColumnIndex("partone"));
String parttwo=cursor.getString(cursor.getColumnIndex("parttwo"));
String partthree=cursor.getString(cursor.getColumnIndex("partthree"));
String partfour=cursor.getString(cursor.getColumnIndex("partfour"));
titleText.setText(title);
subtitleText.setText(subtitle);
authorText.setText(author);
partoneText.setText(partone);
parttwoText.setText(parttwo);
partthreeText.setText(partthree);
partfourText.setText(partfour);
}
cursor.close();
updateBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String utitle=titleText.getText().toString();
String usubtitle=subtitleText.getText().toString();
String uauthor=authorText.getText().toString();
String upartone=partoneText.getText().toString();
String uparttwo=parttwoText.getText().toString();
String upartthree=partthreeText.getText().toString();
String upartfour=partfourText.getText().toString();
db.execSQL("update FileInfo set title=? , subtitle =? , author=? , partone=? , parttwo=? , partthree=? , partfour =? where id=?",
new String[]{utitle,usubtitle,uauthor,upartone,uparttwo,upartthree,upartfour,fileid});
Toast.makeText(FileItemActivity.this, "更新成功", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(FileItemActivity.this,ShowFileNameActivity.class);
startActivity(intent);
finish();
}
});
}
@Override
public void onBackPressed() {
Intent intent=new Intent(FileItemActivity.this,ShowFileNameActivity.class);
startActivity(intent);
finish();
}
}
7、src文件夹内,com.demo.filedemo2包内LoginActivity.java文件:
public class LoginActivity extends BaseActivity {
private SharedPreferences pref;
private SharedPreferences.Editor editor;
private EditText accountEdit;
private EditText passwordEdit;
private Button login;
private CheckBox rememberPass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
pref=PreferenceManager.getDefaultSharedPreferences(this);
accountEdit=(EditText)findViewById(R.id.account);
passwordEdit=(EditText)findViewById(R.id.password);
rememberPass=(CheckBox)findViewById(R.id.remember_pass);
login=(Button)findViewById(R.id.login);
boolean isRemember=pref.getBoolean("remember_password", false);
if (isRemember) {
//将账户和密码都设置到文本框中
String account=pref.getString("account", "");
String password=pref.getString("password", "");
accountEdit.setText(account);
passwordEdit.setText(password);
rememberPass.setChecked(true);
}
login.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String account=accountEdit.getText().toString();
String password=passwordEdit.getText().toString();
//默认admin & 123456 登录成功
if (account.equals("admin") && password.equals("123456")) {
editor=pref.edit();
if (rememberPass.isChecked()) {//检查复选框是否被选中
editor.putBoolean("remember_password", true);
editor.putString("account", account);
editor.putString("password", password);
} else {
editor.clear();
}
editor.commit();
Intent intent=new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
finish();
} else {
Toast.makeText(LoginActivity.this, "account or password is invalid", Toast.LENGTH_SHORT).show();
}
}
});
}
}
8、src文件夹内,com.demo.filedemo2包内MainActivity.java文件:
public class MainActivity extends BaseActivity {
public static Activity mainActivity=null;
private EditText titleText;
private EditText subtitleText;
private EditText authorText;
private Button openpage02Btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.page01);
mainActivity=this;
titleText=(EditText)findViewById(R.id.title);
subtitleText=(EditText)findViewById(R.id.subtitle);
authorText=(EditText)findViewById(R.id.author);
openpage02Btn=(Button)findViewById(R.id.openpage02);
openpage02Btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this, Page02Activity.class);
String title=titleText.getText().toString();
String subtitle=subtitleText.getText().toString();
String author=authorText.getText().toString();
Bundle bundle=new Bundle();
bundle.putString("title", title);
bundle.putString("subtitle", subtitle);
bundle.putString("author", author);
intent.putExtras(bundle);
startActivity(intent);
overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
}
});
}
}
9、src文件夹内,com.demo.filedemo2包内Page02Activity.java文件:
public class Page02Activity extends BaseActivity {
public static Activity p2Activity=null;
private EditText partoneText;
private Button openpage03Btn;
private Button backBtn;
private String title;
private String subtitle;
private String author;
private String partone;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.page02);
p2Activity=this;
Bundle bundle=this.getIntent().getExtras();
title=bundle.getString("title");
subtitle=bundle.getString("subtitle");
author=bundle.getString("author");
openpage03Btn=(Button)findViewById(R.id.openpage03);
backBtn=(Button)findViewById(R.id.backto1);
partoneText=(EditText)findViewById(R.id.partone);
openpage03Btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
partone=partoneText.getText().toString();
Intent intent2=new Intent(Page02Activity.this, Page03Activity.class);
Bundle bundle=new Bundle();
bundle.putString("title", title);
bundle.putString("subtitle", subtitle);
bundle.putString("author", author);
bundle.putString("partone", partone);
intent2.putExtras(bundle);
startActivity(intent2);
overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
}
});
backBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
10、 src文件夹内,com.demo.filedemo2包内Page03Activity.java文件:
public class Page03Activity extends BaseActivity {
public static Activity p3Activity=null;
private EditText parttwoText;
private Button openpage04Btn;
private Button backBtn;
private String title;
private String subtitle;
private String author;
private String partone;
private String parttwo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.page03);
p3Activity=this;
Bundle bundle=this.getIntent().getExtras();
title=bundle.getString("title");
subtitle=bundle.getString("subtitle");
author=bundle.getString("author");
partone=bundle.getString("partone");
parttwoText=(EditText)findViewById(R.id.parttwo);
openpage04Btn=(Button)findViewById(R.id.openpage04);
backBtn=(Button)findViewById(R.id.backto2);
openpage04Btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
parttwo=parttwoText.getText().toString();
Intent intent2=new Intent(Page03Activity.this, Page04Activity.class);
Bundle bundle=new Bundle();
bundle.putString("title", title);
bundle.putString("subtitle", subtitle);
bundle.putString("author", author);
bundle.putString("partone", partone);
bundle.putString("parttwo", parttwo);
intent2.putExtras(bundle);
startActivity(intent2);
overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
}
});
backBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
11、 src文件夹内,com.demo.filedemo2包内Page04Activity.java文件:
public class Page04Activity extends BaseActivity {
public static Activity p4Activity=null;
private EditText partthreeText;
private Button openpage05Btn;
private Button backBtn;
private String title;
private String subtitle;
private String author;
private String partone;
private String parttwo;
private String partthree;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.page04);
p4Activity=this;
Bundle bundle=this.getIntent().getExtras();
title=bundle.getString("title");
subtitle=bundle.getString("subtitle");
author=bundle.getString("author");
partone=bundle.getString("partone");
parttwo=bundle.getString("parttwo");
partthreeText=(EditText)findViewById(R.id.partthree);
openpage05Btn=(Button)findViewById(R.id.openpage05);
backBtn=(Button)findViewById(R.id.backto3);
openpage05Btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
partthree=partthreeText.getText().toString();
Intent intent2=new Intent(Page04Activity.this, Page05Activity.class);
Bundle bundle=new Bundle();
bundle.putString("title", title);
bundle.putString("subtitle", subtitle);
bundle.putString("author", author);
bundle.putString("partone", partone);
bundle.putString("parttwo", parttwo);
bundle.putString("partthree", partthree);
intent2.putExtras(bundle);
startActivity(intent2);
overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
}
});
backBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
12、 src文件夹内,com.demo.filedemo2包内Page05Activity.java文件:
public class Page05Activity extends BaseActivity {
public static Activity p5Activity=null;
private EditText partfourText;
private Button saveBtn;
private Button backBtn;
private MyDatabaseHelper dbHelper;
private String title;
private String subtitle;
private String author;
private String partone;
private String parttwo;
private String partthree;
private String partfour;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.page05);
p5Activity=this;
dbHelper = new MyDatabaseHelper(this, "FileDemo.db", null, 1);
Bundle bundle=this.getIntent().getExtras();
title=bundle.getString("title");
subtitle=bundle.getString("subtitle");
author=bundle.getString("author");
partone=bundle.getString("partone");
parttwo=bundle.getString("parttwo");
partthree=bundle.getString("partthree");
partfourText=(EditText)findViewById(R.id.partfour);
saveBtn=(Button)findViewById(R.id.save);
backBtn=(Button)findViewById(R.id.backto4);
saveBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
partfour=partfourText.getText().toString();
SQLiteDatabase db=dbHelper.getWritableDatabase();
db.execSQL("insert into FileInfo (title,subtitle,author,partone,parttwo,partthree,partfour) values (?,?,?,?,?,?,?)",
new String[]{title,subtitle,author,partone,parttwo,partthree,partfour});
Toast.makeText(Page05Activity.this, "保存成功", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(Page05Activity.this,ShowFileNameActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
finish();
Page04Activity.p4Activity.finish();
Page03Activity.p3Activity.finish();
Page02Activity.p2Activity.finish();
MainActivity.mainActivity.finish();
}
});
backBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
13、 src文件夹内,com.demo.filedemo2包内ShowFileNameActivity.java文件:
public class ShowFileNameActivity extends BaseActivity {
private MyDatabaseHelper dbHelper;
private List fileNameList=new ArrayList();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_showfilename);
dbHelper = new MyDatabaseHelper(this, "FileDemo.db", null, 1);
final SQLiteDatabase db = dbHelper.getWritableDatabase();
initFileNames();
FileNameAdapter adapter=new FileNameAdapter(ShowFileNameActivity.this, R.layout.filename_item, fileNameList);
ListView listView=(ListView)findViewById(R.id.showfilename_list_view);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view,
int position, long id) {
int fileid=fileNameList.get(position).getId();
String final_id=Integer.toString(fileid);
FileItemActivity.actionStart(ShowFileNameActivity.this, final_id);
finish();
}
});
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView> parent, View view,
int position, long id) {
int fileid=fileNameList.get(position).getId();
final String final_id=Integer.toString(fileid);
AlertDialog.Builder dialog=new AlertDialog.Builder(ShowFileNameActivity.this);
dialog.setTitle("删除");
dialog.setMessage("确认删除该条文档信息?");
dialog.setCancelable(false);
dialog.setPositiveButton("删除", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
db.execSQL("delete from FileInfo where id=?", new String[]{final_id});
finish();
Intent intent=new Intent(ShowFileNameActivity.this, ShowFileNameActivity.class);
startActivity(intent);
}
});
dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.show();
return true;
}
});
}
private void initFileNames(){
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor=db.rawQuery("select * from FileInfo", null);
if (cursor.moveToFirst()) {
do {
String id=cursor.getString(cursor.getColumnIndex("id"));
int idint=Integer.parseInt(id);
String fileName=cursor.getString(cursor.getColumnIndex("title"));
String fileAuthor=cursor.getString(cursor.getColumnIndex("author"));
FileName fN = new FileName(idint,fileName, fileAuthor);
fileNameList.add(fN);
} while (cursor.moveToNext());
}
cursor.close();
}
@Override
public void onBackPressed() {
if (Page05Activity.p5Activity!=null) {
Page05Activity.p5Activity.finish();
}
if (Page04Activity.p4Activity!=null) {
Page04Activity.p4Activity.finish();
}
if (Page03Activity.p3Activity!=null) {
Page03Activity.p3Activity.finish();
}
if (Page02Activity.p2Activity!=null) {
Page02Activity.p2Activity.finish();
}
if (MainActivity.mainActivity!=null) {
MainActivity.mainActivity.finish();
}
Intent intent=new Intent(ShowFileNameActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
14、 res\anim文件夹内,in_from_right.xml文件:
15、 res\anim文件夹内,out_to_left.xml文件:
16、 res\layout文件夹下,activity_fileitem.xml文件:
17、 res\layout文件夹下,activity_login.xml文件:
18、 res\layout文件夹下,activity_main.xml文件:
19、 res\layout文件夹下,activity_showfilename.xml文件:
20、 res\layout文件夹下,filename_item.xml文件:
21、 res\layout文件夹下,page01.xml文件:
22、 res\layout文件夹下,page02.xml文件:
23、 res\layout文件夹下,page03.xml文件:
24、 res\layout文件夹下,page04.xml文件:
25、 res\layout文件夹下,page05.xml文件:
26、 res\menu文件夹下,main.xml文件:
27、 AndroidManifest.xml文件:
该demo使用Android自带的SQLIte数据库,将所需要存储的文件的标题、副标题、作者、具体内容等信息存储在数据库中。
1. 软件启动界面,输入账号和密码登录。如果用户名或密码错误会提示“account or password is invalid”。
2. 登录成功后界面如图左所示,可以在此界面输入需要存储的文件的标题、副标题、作者信息,如图右所示。点击下一页进入到下一界面。
3. 该界面可以用来存储文件的其他信息,如图左所示。点击上一页返回,点击下一页会进入下一界面,下一界面和该界面类似。此类界面在demo中设置了四个,提示标题分别为“版块一”,“版块二”,“版块三”,“版块四”,均以文本形式存储内容,此类界面可添加删减。版块四界面如图右所示。点击保存可以把信息保存到数据库,并自动跳转到文件列表界面。
4. 文件列表界面,该界面显示文件的标题和作者,如图左所示。刚添加的信息在列表最下方一个。长按某一个item会提示是否删除该item,如图右所示。点击某个item进入到详细信息界面。
5. 详细信息界面,如图所示,在该界面可以再次进行编辑,然后点击按钮“更新”进行保存,并再跳转到列表界面。
6. 登录成功后,在主界面使用手机上的Menu键可以通过点击图中“打开文件列表”直接进入到列表界面,如图所示。在软件使用过程中可以通过此操作退出软件。
源码下载