欢迎界面
登陆后的主界面,自动查询数据库并加载显示数据到ListView中
添加数据
长按删除
menu按钮排序
按ID逆序排列的界面
xml布局写的不是很好,若您有更好的布局方式,请回复一下,让我也学习学习哈,一同进步。。。。
第一次写这么多的代码,发帖不易,请不要让此贴沉下去哈,回复还有下载豆豆拿。。。
欢迎界面的java代码 StartLuncher.java
[mw_shl_code=java,true]package wj.sqlitedemo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class StartLuncher extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myluncher);
luncherStart();
}
public void luncherStart(){
new Thread(){
public void run(){
try{
Thread.sleep(2500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent intent = new Intent();
intent.setClass(StartLuncher.this,MainActivity.class);
startActivity(intent);
finish();
}
}.start();
}
}
[/mw_shl_code]
欢迎界面的XML代码 myluncher.xml
[mw_shl_code=xhtml,true]<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/login" >
</LinearLayout>[/mw_shl_code]
AndroidManifest.xml
[mw_shl_code=xhtml,true]<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="wj.sqlitedemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="3"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".StartLuncher"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".AddUser" android:label="@string/addUser"></activity>
<activity android:name="MainActivity" ></activity>
</application>
</manifest>[/mw_shl_code]
MainActivity.java 比较长,耐心看完哈,肯定会有收货的,我学的不咋地,但是我写的我能看懂,你也一定能看懂。。。
[mw_shl_code=java,true]package wj.sqlitedemo;
import java.util.Timer;
import java.util.TimerTask;
import android.R.drawable;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
@SuppressLint({ "ParserError", "ParserError", "ParserError", "ParserError",
"ParserError", "ParserError", "ParserError" })
public class MainActivity extends ListActivity {
// 数据表名称
private static final String TABLE_NAME = "data";
// 定义帮助类
private MyDatabaseHepler dbHelper;
// 定义数据库类
private SQLiteDatabase db;
private static final String NAME = "name";
private static final String AGE = "age";
SimpleAdapter adapter;
Button addButton;
EditText et_name;
EditText et_age;
TextView textView;
ListView list;
TextView tv_id;
TextView tv_age;
TextView tv_name;
Button button1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
// 实例化帮助类
dbHelper = new MyDatabaseHepler(getApplicationContext());
// 创建数据库
db = dbHelper.getWritableDatabase();
// 实例化帮助类
dbHelper = new MyDatabaseHepler(getApplicationContext());
// 创建数据库
db = dbHelper.getWritableDatabase();
// 取出组件
list = (ListView) findViewById(android.R.id.list);
// list=getListView(); 调用系统的list,和上边的一样
// 设置监听
// list.setOnItemClickListener(new MyOnItemClickListener());
// 注册ListView上下文菜单
this.registerForContextMenu(list);
list.setOnCreateContextMenuListener(this);
// 初始化,调用填充方法填充ListView
this.queryData();
addButton = (Button) findViewById(R.id.plus);
// add 功能实现
addButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
LayoutInflater inflater = getLayoutInflater();
final View layout = inflater.inflate(R.layout.dialog,
(ViewGroup) findViewById(R.id.dialog));
new AlertDialog.Builder(MainActivity.this)
.setTitle("增加信息")
.setView(layout)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,int which) {
et_name = (EditText) layout .findViewById(R.id.et_name);
et_age = (EditText) layout .findViewById(R.id.et_age);
// 取出值
String e_name = et_name.getText().toString();
String e_age = et_age.getText() .toString();
ContentValues cv = new ContentValues();
cv.put(NAME, e_name);
cv.put(AGE, e_age);
db.insert(TABLE_NAME, null, cv);
queryData();
}
})
.setNegativeButton("Cancle",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
});
}
// 查询,填充ListView
public void queryData() {
// 游标
Cursor cursor = db
.query(TABLE_NAME, null, null, null, null, null, null);
// 启动管理游标
this.startManagingCursor(cursor);
// 游标适配器
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
MainActivity.this, R.layout.userinfo, cursor, new String[] {
"_id", "name", "age" }, new int[] { R.id.id, R.id.name,
R.id.age });
System.out.println(adapter.getCount());
// 设置适配器
setListAdapter(adapter);
//下边这句话,我不知道应不应该加,若你知道,麻烦回复一下其功能用法,告知我,好么?
adapter.notifyDataSetChanged();
}
// 排序查询
// public Cursor query (String table, String[] columns, String selection,
//String[] selectionArgs, String groupBy, String having, String orderBy)
public void queryOrder() {
// 游标
Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null,
"_id desc");
// 启动管理游标
this.startManagingCursor(cursor);
// 游标适配器
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
MainActivity.this, R.layout.userinfo, cursor, new String[] {
"_id", "name", "age" }, new int[] { R.id.id, R.id.name,
R.id.age });
System.out.println(adapter.getCount());
// 设置适配器
setListAdapter(adapter);
}
// menu按钮 按默认排序
public void queryByIdAsc() {
// 游标
Cursor cursor = db
.query(TABLE_NAME, null, null, null, null, null, null);
// 启动管理游标
this.startManagingCursor(cursor);
// 游标适配器
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
MainActivity.this, R.layout.userinfo, cursor, new String[] {
"_id", "name", "age" }, new int[] { R.id.id, R.id.name,
R.id.age });
System.out.println(adapter.getCount());
// 设置适配器
setListAdapter(adapter);
}
//
// 删除
public void deleteData(final long id) {
System.out.println(".........");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("删除内容").setMessage("确定删除吗?")
.setIcon(R.drawable.home_trash)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 删除数据
db.delete(TABLE_NAME, "_id=?",
new String[] { String.valueOf(id) });
// 显示数据
queryData();
}
}).setNegativeButton("取消", null).create();
builder.show();
}
//上下文菜单
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
menu.setHeaderTitle("信息操作").setHeaderIcon(R.drawable.ic_launcher);
menu.add(0, 1, 0, "删除");
super.onCreateContextMenu(menu, v, menuInfo);
}
//上下文菜单选择
@Override
public boolean onContextItemSelected(MenuItem item) {
// 取得选项信息
AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item
.getMenuInfo();
// 传递ID
this.deleteData(menuInfo.id);
return super.onContextItemSelected(item);
}
//选项菜单选择
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.main, menu);
menu.add(0, 1, 1, "按ID排序");
menu.add(0, 2, 2, "按默认排序");
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1:
// 此处添加按年龄
queryOrder();
Toast.makeText(this, "id order", Toast.LENGTH_LONG).show();
break;
case 2:
// 此处添加按默认排序
queryByIdAsc();
Toast.makeText(this, "默认排序", Toast.LENGTH_LONG).show();
break;
}
return super.onOptionsItemSelected(item);
}
// 双击返回键退出程序
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
exitBy2Click();// 调用双击退出函数
}
return false;
}
// 准备退出
private static Boolean isExit = false;
private void exitBy2Click() {
Timer tExit = null;
if (isExit == false) {
isExit = true; // 准备退出
Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
tExit = new Timer();
tExit.schedule(new TimerTask() {
@Override
public void run() {
isExit = false; // 取消退出
}
}, 2000); // 如果2秒钟内没有按下返回键,则启动定时器取消掉刚才执行的任务
} else {
finish();
System.exit(0);
}
}
}
[/mw_shl_code]
MyDatabaseHelper.java 数据库类
[mw_shl_code=java,true]package wj.sqlitedemo;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MyDatabaseHepler extends SQLiteOpenHelper
{
// 数据库名称
private static final String DB_NAME = "notepad.db";
// 数据表名称
private static final String TABLE_NAME = "data";
// 数据库版本
private static final int DB_VERSION = 1;
// 创建数据表SQL语句
private static final String CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME
+ "("
+ "_id INTEGER PRIMARY KEY ,"
+ "name VARCHAR(50) NOT NULL ,"
+ "age"
+ ")";
// 删除数据表SQL语句
private static final String DROP_TABLE = "DROP IF TABLE EXISTS "
+ TABLE_NAME;
public MyDatabaseHepler(Context context)
{
super(context, DB_NAME, null, DB_VERSION);
System.out.println("--------------------数据库创建成功!!");
}
@Override
public void onCreate(SQLiteDatabase db)
{
// 创建数据表
db.execSQL(CREATE_TABLE);
System.out.println("------------------------数据表创建成功!!");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL(DROP_TABLE);
System.out.println("-------------------------数据表更新成功!!");
onCreate(db);
}
}
[/mw_shl_code]
AddUser.java 添加数据
[mw_shl_code=java,true]package wj.sqlitedemo;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
@SuppressLint("ParserError")
public class AddUser extends Activity {
// 数据表名称
private static final String TABLE_NAME = "data";
// 定义组件
private EditText et_name;
private EditText et_age;
private Button btnSave;
// 定义数据库对象
private MyDatabaseHepler dbHelper;
private SQLiteDatabase db;
private String e_id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog);
// 实例化数据库对象
dbHelper = new MyDatabaseHepler(getApplicationContext());
db = dbHelper.getWritableDatabase();
// 取得组件
et_name = (EditText) findViewById(R.id.et_name);
et_age = (EditText) findViewById(R.id.et_age);
// 获取传递过来的值
Intent intent = getIntent();
// 保存值
e_id = intent.getStringExtra("id");
String mTitle = intent.getStringExtra("name");
String mBody = intent.getStringExtra("age");
// 显示值
et_name.setText(mTitle);
et_age.setText(mBody);
btnSave.setOnClickListener(new MyOnClickListener());
}
/**
* 保存按钮监听方法
*/
public class MyOnClickListener implements OnClickListener {
@Override
public void onClick(View view) {
// 取出值
String mTitle = et_name.getText().toString();
String mBody = et_age.getText().toString();
// 定义ContentValues
ContentValues cValues = new ContentValues();
cValues.put("title", mTitle);
cValues.put("body", mBody);
// 调用方法
savaData(cValues, e_id);
// 返回
setResult(RESULT_OK);
finish();
}
}
/**
* 保存方法
*/
public void savaData(ContentValues values, String id) {
// 如果数据表中的id为空
if (id == null) {
db.insert(TABLE_NAME, null, values);
db.close();
} else {
db.update(TABLE_NAME, values, "_id=?",
new String[] { String.valueOf(id) });
db.close();
}
}
}
[/mw_shl_code]
Layout_Main.xml 主布局,写的有点乱,请谅解哈,假如您有更好的 listView数据列表的布局方式,请麻烦您回复一下,一同进步哈
[mw_shl_code=java,true]<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/linearLayout0"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<RelativeLayout
android:id="@+id/relativeLayout0"
android:layout_width="fill_parent"
android:layout_height="50dip"
android:background="@drawable/topmenu_bg"
android:gravity="center"
android:orientation="horizontal" >
<Button
android:id="@+id/plus"
android:layout_width="50dip"
android:layout_height="30dip"
android:layout_centerHorizontal="true"
android:background="@drawable/addxml" />
</RelativeLayout>
<TableLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="0,1"
>
<TableRow >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/id"
android:text="@string/id"
android:textSize="15pt"
android:textColor="#00BFFF"/>
<TextView
android:layout_width="wrap_content"
android:layout_gravity="center_vertical"
android:id="@+id/name"
android:text="@string/name"
android:textSize="15pt"
android:textColor="#00BFFF"/>
<TextView
android:id="@+id/age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/age"
android:textColor="#00BFFF"
android:textSize="15pt" />
</TableRow>
</TableLayout>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="false"
android:divider="#D4D4D4"
android:dividerHeight="1dp"
android:scrollbars="vertical" >
</ListView>
</LinearLayout>[/mw_shl_code]
userinfo.xml LsitView列表元素
[mw_shl_code=java,true]<?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:orientation="horizontal" >
<TextView android:id="@+id/id"
android:gravity="left"
android:layout_width="100dip"
android:layout_height="wrap_content"
android:singleLine="true"
android:paddingLeft="5dip"
android:paddingTop="3dip"
android:paddingBottom="3dip"
android:textSize="10pt"
/>
/>
<TextView android:id="@+id/name"
android:layout_width="100dip"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:singleLine="true"
android:paddingLeft="5dip"
android:paddingTop="3dip"
android:paddingBottom="3dip"
android:textSize="10pt"
/>
<TextView android:id="@+id/age"
android:layout_width="100dip"
android:layout_height="wrap_content"
android:gravity="right"
android:singleLine="true"
android:paddingLeft="5dip"
android:paddingTop="3dip"
android:paddingBottom="3dip"
android:textSize="10pt"
/>
</LinearLayout>[/mw_shl_code]
dialog.xml 就是添加按钮点击后的弹出输入框
[mw_shl_code=xhtml,true]<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/dialog"
android:layout_width="250dip"
android:layout_height="200dip"
android:background="#87CEFA"
android:gravity="center|center_horizontal"
android:layout_gravity="center_horizontal"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal" >
<TextView
android:id="@+id/tvname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/name1" />
<EditText
android:id="@+id/et_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="100dip" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal" >
<TextView
android:id="@+id/tvage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/age1" />
<EditText
android:id="@+id/et_age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:digits="0123456789"
android:minWidth="100dip" />
</LinearLayout>
</LinearLayout>[/mw_shl_code]
【转载】http://www.apkbus.com/android-64756-1-1.html