Android學習-----如何使用sqlite進行後台資料互動,sqlite入門使用常式

來源:互聯網
上載者:User



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;@Overrideprotected 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);}});}@Overridepublic 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("註冊成功,請點取消按鈕返回到登入介面");}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("註冊成功,請點取消按鈕返回到登入介面");}}});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();}}@Overridepublic 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 weibo3cursor = db.rawQuery("select * from weiboa", null);inflateList(cursor);}catch(SQLiteException se){//primary key autoincrementdb.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){//填充SimpleCursorAdapterSimpleCursorAdapter 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();}}@Overridepublic 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 ErrorActivity extends Activity {@Overrideprotected 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);}});}@Overridepublic 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查看,相對來說比較麻煩,下篇部落格總結一下,想瞭解的可以關注。

另外完整的Demo稍後傳上。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.