Android学习-----如何使用sqlite对于后台数据交换,sqlite使用例程入门



SQLite 这是一个非常流行的嵌入式数据库。它支持 SQL 查询,和只使用很少的内存。Android 在集成实施 SQLite,所以每 Android 应用程序能够使用 SQLite 数据库。对数熟悉 SQL 的开发者来时。使用 SQLite 相当简单。

能够。因为 JDBC 不适合手机这样的内存受限设备。所以 Android 开发者须要学习新的 API 来使用 SQLite。本文以一个注冊登录Demo简介一下sqlite入门使用。

先上一下执行结果:(请忽略丑陋的界面~~)

以下贴上主要代码,后面分析:

/**
 * 登录页面的activity
 * @author D_xiao
 *
 */
public class MainActivity extends Activity {
	SQLiteDatabase db;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Button loginbtn = (Button)findViewById(R.id.loginbtn);
		Button regbtn = (Button)findViewById(R.id.regbtn);
		db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString()+"/android1.db3", null); //创建或打开数据库
		loginbtn.setOnClickListener(new OnClickListener(){
			public void onClick(View sourse){
				boolean flag = false;
				String userName = ((EditText)findViewById(R.id.userEditText)).getText().toString();
				String userPassword = ((EditText)findViewById(R.id.passwordEditText)).getText().toString();
				try{
					Cursor cursor = db.rawQuery("select * from users where name = ? and password = ?",new String[]{userName,userPassword});
					
					if(cursor.getCount()==0){
						Intent intentE = new Intent(MainActivity.this,ErrorActivity.class);
						startActivity(intentE);
					}else{
						Intent intentS = new Intent(MainActivity.this,HomeActivity.class);
						intentS.putExtra("name", userName);
						startActivity(intentS);
					}
				}catch(SQLiteException se){
					Intent intentE = new Intent(MainActivity.this,ErrorActivity.class);
					startActivity(intentE);
				}
			}
		});
		regbtn.setOnClickListener(new OnClickListener(){
			public void onClick(View sourse){
				Intent intentReg = new Intent(MainActivity.this,RegActivity.class);
				startActivity(intentReg);
			}
		});
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
}
/**
 * 注冊Activity
 * @author D_xiao
 *
 */
public class RegActivity extends Activity {
	SQLiteDatabase db;
	ListView listView;
	Button btn;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_reg);
		db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString()+"/android1.db3", null);
		final String a = this.getFilesDir().toString();
		Button regOK = (Button)findViewById(R.id.regOK);
		Button backtologin = (Button)findViewById(R.id.backtologin);
		regOK.setOnClickListener(new OnClickListener(){
			public void onClick(View sourse){
				String name = ((EditText)findViewById(R.id.name)).getText().toString();
				String password = ((EditText)findViewById(R.id.password)).getText().toString();
				TextView suc = (TextView)findViewById(R.id.suc);
				try{
					db.execSQL("insert into users values(null,?

,?)",new String[]{name,password}); suc.setText("注冊成功。请点取消button返回到登录界面"); }catch(SQLiteException se){ db.execSQL("create table users(_id integer primary key autoincrement," +"name varchar(20) ," +"password varchar(200))"); db.execSQL("insert into users values(null,?,?)",new String[]{name,password}); suc.setText("注冊成功。请点取消button返回到登录界面"); } } }); backtologin.setOnClickListener(new OnClickListener(){ public void onClick(View sourse){ Intent intent = new Intent(RegActivity.this,MainActivity.class); startActivity(intent); } }); } public void onDestroy(){ super.onDestroy(); if(db!=null&&db.isOpen()){ db.close(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }


/**
 * 登录成功显示主页,能够发微博 并显示朋友圈
 * @author D_xiao
 *
 */
public class HomeActivity extends Activity {
	SQLiteDatabase db;
	ListView listView;
	Button btn;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);
		db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString()+"/android1.db3", null);
		listView = (ListView)findViewById(R.id.show);
		btn = (Button)findViewById(R.id.send);
		btn.setOnClickListener(new OnClickListener(){
			Cursor cursor = null;
			public void onClick(View sourse){
				String weibo = ((EditText)findViewById(R.id.newtext)).getText().toString();
				Intent intent = getIntent();
				String name = intent.getStringExtra("name");
				try{
					insertData(db,name,weibo);
					//select * from weibo3
					cursor = db.rawQuery("select * from weiboa", null);
					inflateList(cursor);
				}catch(SQLiteException se){
					//primary key autoincrement
					db.execSQL("create table weiboa(_id integer primary key autoincrement," 
							+"name varchar(20) ,"
							+"weibo varchar(200))");
					insertData(db,name,weibo);
					//查询
					cursor = db.rawQuery("select * from weiboa", null);
					inflateList(cursor);
				}finally{
					//cursor.close();
				}
			}
		});
	}
	private void insertData(SQLiteDatabase db,String name,String weibo){
		//运行插入语句
		db.execSQL("insert into weiboa values(null,?,?)",new String[]{name,weibo});
	}
	private void inflateList(Cursor cursor){
		//填充SimpleCursorAdapter
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(HomeActivity.this,R.layout.line,cursor,
				new String[]{"name","weibo"},
				new int[]{R.id.my_name,R.id.my_weibo},
				CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
				listView.setAdapter(adapter);
	}
	public void onDestroy(){
		super.onDestroy();
		if(db!=null&&db.isOpen()){
			db.close();
		}
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
}


/**
 * username或password错误跳转
 * @author D_xiao
 *
 */
public class ErrorActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_error);

		Button backbtn = (Button)findViewById(R.id.Ebackbtn);
		backbtn.setOnClickListener(new OnClickListener(){
			public void onClick(View sourse){
				Intent intentBack = new Intent(ErrorActivity.this,MainActivity.class);
				startActivity(intentBack);
			}
		});
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
}


通过此例,能够看出来sqlite和sql server 等数据库的差别联系:

sqlite没有图形界面,也不须要不论什么的配置安装打开连接等等的操作,几句简单的语句就能够完毕增删改查操作。使用起来还是非常方便的。并且sqlite和sql server ,MySQL是有非常多相似的地方的。除了大多数查询语句在sqlite里面都能够用以外,sqlite还有自己的api提供的方法进行查询,这个以后再叙。并且运行语句也非常相似。

比方db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString()+"/android1.db3", null);  这句相当于sql server中的建立连接,所以在使用完以后要关闭连接,都是一样的。

       Cursor cursor = db.rawQuery("select * from users where name = ? and password = ?",new String[]{userName,userPassword});这句中的cursor相当于sql server 中的resultSet结思集。

没有图形界面有一点还是比較麻烦的,就是不好操作查看数据表,必需要执行cmd查看,相对来说比較麻烦。请看下篇博文:http://blog.csdn.net/frightingforambition/article/details/24439981

完整Demo:

http://download.csdn.net/detail/u011250851/7248227






版权声明:本文博客原创文章,博客,未经同意,不得转载。

posted @ 2015-08-07 17:30  hrhguanli  阅读(398)  评论(0编辑  收藏  举报