android中的Sqlite数据库操作
第一步:创建数据库,创建表,(添加、修改、删除)方法!
package example.gznprojklc;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class SqliteDBHelper extends SQLiteOpenHelper {
// 创建库
public static final String CREATE_DATABASE = "MonitorMeasuration.db";
// 表名
public static final String USER_TABLE = "Users";
public static final String FAULTSURFACE_TABLE = "FaultSurface";
public static final String TUNNEL_TABLE = "Tunnel";
public static final String POINT_TABLE = "Point";
public static final String SURFACESUBSIDENCE_TABLE = "SurfaceSubsidence";
public static final String DISPLACEMENT_TABLE = "Displacement";
public static final String VAULTSETTLEMENT_TABLE = "ValutSettlement";
// 创建表
public static final String CREATE_USER_TABLE = "CREATE TABLE "
+ USER_TABLE
+ " (ID INTEGER PRIMARY KEY AUTOINCREMENT,UserName TEXT,UserPwd TEXT,DateTime TEXT,Reserve1 TEXT,Reserve2 TEXT,Reserve3 TEXT);";
private SQLiteDatabase db;
public SqliteDBHelper(Context context) {
super(context, CREATE_DATABASE, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
this.db = db;
db.execSQL(CREATE_USER_TABLE);
}
// 关闭数据库
public void Close() {
if (db != null) {
db.close();
}
}
// 添加数据
public long Insert(ContentValues values, String TableName) {
SQLiteDatabase db = this.getWritableDatabase();
long count = db.insert(TableName, null, values);
if (count == -1) {
count = -1;
} else {
count = 1;
}
db.close();
return count;
}
// 隧道删除数据
public void Tunneldelete(int id) {
if (db == null)
db = this.getWritableDatabase();
db.execSQL("delete from SurfaceSubsidence where ID=" + id);
db.close();
}
// 断面删除数据
public void Pointsdelete(int id) {
if (db == null)
db = this.getWritableDatabase();
db.execSQL("delete from ValutSettlement where ID=" + id);
db.close();
}
// 测点删除数据
public void Testdelete(int id) {
if (db == null)
db = this.getWritableDatabase();
db.execSQL("delete from Displacement where ID=" + id);
db.close();
}
// 地表沉降
public void update(int id, ContentValues values, String TableName,
String whereID) {
SQLiteDatabase db = this.getWritableDatabase();
String where = whereID + " = ?";
String[] whereValue = { Integer.toString(id) };
db.update(TableName, values, where, whereValue);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
第二步:用户登录后台代码(注:用户登录是在有网络的时候才能登录,第一次登录成功后第二次可以关闭网络登录,这里是调用了Asp.Net平台开发的WebService接口)。
在这里需要导入一个jar包:ksoap2-android-assembly-2.3-jar-with-dependencies.jar 放在libs文件夹下即可!
package example.gznprojklc;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.MarshalBase64;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity {
public SqliteDBHelper helper;
public EditText txtUserName;
public EditText txtUserPwd;
public Button btnLogin;
public SQLiteDatabase db;
public int userId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
txtUserName = (EditText) findViewById(R.id.txtUserName);
txtUserPwd = (EditText) findViewById(R.id.txtUserPwd);
txtUserName.requestFocus();
txtUserName.setCursorVisible(true);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(loginlistener);
}
// 用户登录
OnClickListener loginlistener = new OnClickListener() {
@Override
public void onClick(View v) {
String url = "http://117.34.91.188:8055/WebServices/login.asmx";
String nameSpace = "http://tempuri.org/";
String SOAP_ACTION = "http://tempuri.org/LoginInfo";
String method = "LoginInfo";
String userName = txtUserName.getText().toString();
String userPwd = txtUserPwd.getText().toString();
SoapObject request = new SoapObject(nameSpace, method);
request.addProperty("username", userName);
request.addProperty("pwd", userPwd);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.bodyOut = request;
(new MarshalBase64()).register(envelope);
AndroidHttpTransport transport = new AndroidHttpTransport(url);
envelope.dotNet = true;
try {
if (isOpenNetWork()) {
transport.call(SOAP_ACTION, envelope);
if (envelope.getResponse() != null) {
if (userName.equals("") || userPwd.equals("")) {
ShowDialog("用户名或者密码不能为空");
} else {
Object object = envelope.getResponse();
String str = object.toString();
if (str.equals("anyType{}")) {
ShowDialog("登录失败用户名或者密码错误");
} else {
userId = Integer.parseInt(str.toString());
ListSelectActivity.id = userId;
AddDepth.id=userId;
CommonSpinner.userId=userId;
ContentValues values = new ContentValues();
SimpleDateFormat fort = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Date curDate = new Date(
System.currentTimeMillis());// 获取当前时间
String time = fort.format(curDate);
values.put("UserName", userName);
values.put("UserPwd", userPwd);
values.put("DateTime", time);
values.put("Reserve1", "");
values.put("Reserve2", "");
values.put("Reserve3", "");
helper = new SqliteDBHelper(getApplicationContext());
db = helper.getReadableDatabase();
Cursor c = db.rawQuery("select * from Users",
null);
if (c.getCount() == 0) {
helper.Insert(values,helper.USER_TABLE);
}
Intent intent = new Intent();
intent.setClass(LoginActivity.this,
ListSummersActivity.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "登录成功",
Toast.LENGTH_SHORT).show();
}
}
}
} else {
if (userName.equals("") || userPwd.equals("")) {
ShowDialog("请输入用户名或者密码");
} else {
if (IsLogin(userName, userPwd)) {
Toast.makeText(getApplicationContext(), "本地登录成功",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.setClass(LoginActivity.this,
ListSummersActivity.class);
startActivity(intent);
} else {
ShowDialog("登录失败用户名或者密码错误");
}
}
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "网络或者服务器断开不能登录",
Toast.LENGTH_SHORT).show();
}
}
};
// 用户登录
public boolean IsLogin(String Name, String Pwd) {
helper = new SqliteDBHelper(this);
db = helper.getReadableDatabase();
Cursor c = db.rawQuery(
"select * from Users where UserName=? and UserPwd=?",
new String[] { Name.toString(), Pwd.toString() });
if (c.moveToFirst() == true) {
c.close();
return true;
}
return false;
}
// 信息提示
private void ShowDialog(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("提示");
builder.setMessage(message);
builder.setPositiveButton("确定", null);
builder.create().show();
}
// 网络监测
private boolean isOpenNetWork() {
ConnectivityManager connManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if (connManager.getActiveNetworkInfo() != null) {
return connManager.getActiveNetworkInfo().isAvailable();
}
return false;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
}
第三步:用户登录界面前台设计(注:布局建议使用RelativeLayout布局和LinearLayout布局,交叉布局)
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".LoginActivity" >
<TextView
android:id="@+id/TextView01"
android:layout_width="80sp"
android:layout_height="40dp"
android:textSize="20sp"
android:gravity="center_vertical|left"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/txtUserName"
android:layout_marginTop="10dp"
android:text="@string/txt_Pwd" />
<Button
android:id="@+id/btnLogin"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:layout_alignLeft="@+id/TextView01"
android:layout_alignRight="@+id/txtUserPwd"
android:layout_below="@+id/txtUserPwd"
android:textSize="20sp"
android:layout_marginTop="42dp"
android:text="@string/btn_Login" />
<TextView
android:id="@+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="29dp"
android:gravity="center"
android:text="@string/txt_Title"
android:textSize="35sp" />
<EditText
android:id="@+id/txtUserName"
android:layout_width="150sp"
android:layout_height="50dp"
android:layout_alignRight="@+id/textView2"
android:layout_alignTop="@+id/textView1"
android:layout_toRightOf="@+id/textView1"
android:hint=""
android:ems="10" >
</EditText>
<TextView
android:id="@+id/textView1"
android:layout_width="80sp"
android:layout_height="40dp"
android:gravity="center_vertical|left"
android:layout_alignLeft="@+id/textView2"
android:layout_below="@+id/textView2"
android:layout_marginLeft="14dp"
android:layout_marginTop="48dp"
android:text="@string/txt_Name"
android:textSize="20sp" />
<EditText
android:id="@+id/txtUserPwd"
android:layout_width="150sp"
android:layout_height="50dp"
android:inputType="textPassword"
android:layout_alignLeft="@+id/txtUserName"
android:layout_alignRight="@+id/txtUserName"
android:layout_alignTop="@+id/TextView01"
android:hint=""
android:ems="10" />
</RelativeLayout>
到这里的话,操作数据库用户登录基本就成功了!

浙公网安备 33010602011771号