标签:
链接来源
http://www.tutorialspoint.com/android/android_sqlite_database.htm
SQLite是一个开源的SQL数据库,这个数据库把数据存储到设备的一个文本文件里。Android里面已经集成了SQLite数据库工具。
SQLite 支持所有的关系数据库特点。为了进入SQLite数据,你不需要建立任何像JDBC,ODBC之类的连接。
数据库-包
主要的包是android.database.sqlite,这个包里面包含了管理你自己数据库的类。
数据库-创建
想要创建一个数据库,你仅仅需要使用以下方法:openOrCreateDatabase,加上两个参数--名字(name)和标志模式(mode)。这样就会返回一个SQLite的实例,你需要在你自己的对象里接收这一实例。以下是它的语法:
SQLiteDatabase mydatabase = openOrCreateDatabase("your database name",MODE_PRIVATE,null);
除此以外,在数据包里还有其他方法来实现以上方法。以下:
Sr.No | Method & Description |
---|---|
1 | openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags, DatabaseErrorHandler errorHandler)
这个方法仅仅打开已存在的数据库,这个数据库需要适当的标志模式。 一般的标记模式是 OPEN_READWRITE 或者 OPEN_READONLY |
2 | openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags)
这个方法与上述方法类似,此方法也是打开已经存在的数据库,但是它并没有定义任务管理者去处理数据库错误。 |
3 | openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)
此方法不仅仅打开,如果数据库不存在,它也会创建些数据库。这个方法与openDatabase方法是等价的。 |
4 | openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)
此方法与上述方法类似,但是它使用的参数是File而不是String。这个等价于file.getPath()。 |
数据库-插入
我们可以使用定义在SQLiteDatabase类里面的execSQL方法来创建一个表或者在表里插入数据。它的语法如下:
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS TutorialsPoint(Username VARCHAR,Password VARCHAR);"); mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES(‘admin‘,‘admin‘);");
这样会在我们数据库的表里面插入一些值。另一个方法也能做同样的工作,但是这个方法需要额外的参数。如下:
Sr.No | Method & Description |
---|---|
1 | execSQL(String sql, Object[] bindArgs)
这个方法不仅仅插入数据,同时也能更新或者修改数据库里已经存在的数据。同时,这个方法需要绑定参数。 |
数据库-获取
我们可以使用指针类的对象来获取在数据库里的任何数据。我们可以使用在指针类里的rawQuery方法,它会返回一个结果集,这个结果集里的指针指向表。我们可以向前移动指针来获取数据。
Cursor resultSet = mydatbase.rawQuery("Select * from TutorialsPoint",null); resultSet.moveToFirst(); String username = resultSet.getString(1); String password = resultSet.getString(2);
另外,在指针类里也有其他的方法允许我们有效的检索数据。方法包括:
Sr.No | Method & Description |
---|---|
1 |
getColumnCount() 这个方法返回表里面的列数。 |
2 | getColumnIndex(String columnName)
这个方法通过指定列里面的名字来返回它在列里面的位置。 |
3 | getColumnName(int columnIndex)
与上面相反,这方法通过指定在列里面的位置返回列的名字。 |
4 | getColumnNames()
这个方法返回在表里面的所有列名。 |
5 | getCount()
这个方法返回列的总数量。 |
6 | getPosition()
这个方法返回现在表里面指针的位置。 |
7 | isClosed()
如果指针是关闭的则返回true,否则false。 |
数据库-Helper 类
我们可以通过一个叫SQLiteOpenHelper的帮助类来实现所有数据库的操作。它自动地处理数据库的创建与更新。
它的语法如下:
public class DBHelper extends SQLiteOpenHelper { public DBHelper(){ super(context,DATABASE_NAME,null,1); } public void onCreate(SQLiteDatabase db) {} public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {} }
实例
这里有一个实例来演示一下SQLite数据库的用法。它创建了一个基本的联系人应用,这个应用允许插入,删除和修改联系人。
想要实现此实例,你需要在支持摄像头的实体机上面运行此程序。
步骤 | 描述 |
---|---|
1 | 你使用android studio 去创建一个android 应用,包名叫com.example.sairamkrishna.myapplication。当创建这个应用的时候,你需要确认你的Target SDK和Compile的最低版本足以应用这些API。(就是说,你的版本要比较新) |
2 | 修改 src/MainActivity.java 文件以获得所有 XML 控件的参照并且在listView里填充这些联系人 |
3 | 创建一个新的 src/DBHelper.java用来管理数据库工作 |
4 | 创建一个新的 Activity 叫 DisplayContact.java 用来在屏幕上显示所有的联系人 |
5 | 修改 res/layout/activity_main 去增加各自的XML控件 |
6 | 修改 res/layout/activity_display_contact.xml 去增加各自的XML控件 |
7 | 修改 res/values/string.xml 去增加必要的字符串控件 |
8 | 修改 res/menu/display_contact.xml 去增加必要的菜单控件 |
9 | 创建一个新的 menu 叫 res/menu/mainmenu.xml 去增加插入联系选项 |
10 | 运行android studio,选择一台android 设备安装程序,并核实结果 |
下面是MainActivity.java的内容
package com.example.sairamkrishna.myapplication; import android.content.Context; import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import java.util.ArrayList; import java.util.List; public class MainActivity extends ActionBarActivity { public final static String EXTRA_MESSAGE = "MESSAGE"; private ListView obj; DBHelper mydb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mydb = new DBHelper(this); ArrayList array_list = mydb.getAllCotacts(); ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list); obj = (ListView)findViewById(R.id.listView1); obj.setAdapter(arrayAdapter); obj.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) { // TODO Auto-generated method stub int id_To_Search = arg2 + 1; Bundle dataBundle = new Bundle(); dataBundle.putInt("id", id_To_Search); Intent intent = new Intent(getApplicationContext(),DisplayContact.class); intent.putExtras(dataBundle); startActivity(intent); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item){ super.onOptionsItemSelected(item); switch(item.getItemId()) { case R.id.item1:Bundle dataBundle = new Bundle(); dataBundle.putInt("id", 0); Intent intent = new Intent(getApplicationContext(),DisplayContact.class); intent.putExtras(dataBundle); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } public boolean onKeyDown(int keycode, KeyEvent event) { if (keycode == KeyEvent.KEYCODE_BACK) { moveTaskToBack(true); } return super.onKeyDown(keycode, event); } }
下面是用来显示联系人的activity,DisplayContact.java
package com.example.addressbook; import android.os.Bundle; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class DisplayContact extends Activity { int from_Where_I_Am_Coming = 0; private DBHelper mydb ; TextView name ; TextView phone; TextView email; TextView street; TextView place; int id_To_Update = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_contact); name = (TextView) findViewById(R.id.editTextName); phone = (TextView) findViewById(R.id.editTextPhone); email = (TextView) findViewById(R.id.editTextStreet); street = (TextView) findViewById(R.id.editTextEmail); place = (TextView) findViewById(R.id.editTextCity); mydb = new DBHelper(this); Bundle extras = getIntent().getExtras(); if(extras !=null) { int Value = extras.getInt("id"); if(Value>0){ //means this is the view part not the add contact part. Cursor rs = mydb.getData(Value); id_To_Update = Value; rs.moveToFirst(); String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME)); String phon = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_PHONE)); String emai = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_EMAIL)); String stree = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STREET)); String plac = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_CITY)); if (!rs.isClosed()) { rs.close(); } Button b = (Button)findViewById(R.id.button1); b.setVisibility(View.INVISIBLE); name.setText((CharSequence)nam); name.setFocusable(false); name.setClickable(false); phone.setText((CharSequence)phon); phone.setFocusable(false); phone.setClickable(false); email.setText((CharSequence)emai); email.setFocusable(false); email.setClickable(false); street.setText((CharSequence)stree); street.setFocusable(false); street.setClickable(false); place.setText((CharSequence)plac); place.setFocusable(false); place.setClickable(false); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. Bundle extras = getIntent().getExtras(); if(extras !=null) { int Value = extras.getInt("id"); if(Value>0){ getMenuInflater().inflate(R.menu.display_contact, menu); } else{ getMenuInflater().inflate(R.menu.main, menu); } } return true; } public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch(item.getItemId()) { case R.id.Edit_Contact: Button b = (Button)findViewById(R.id.button1); b.setVisibility(View.VISIBLE); name.setEnabled(true); name.setFocusableInTouchMode(true); name.setClickable(true); phone.setEnabled(true); phone.setFocusableInTouchMode(true); phone.setClickable(true); email.setEnabled(true); email.setFocusableInTouchMode(true); email.setClickable(true); street.setEnabled(true); street.setFocusableInTouchMode(true); street.setClickable(true); place.setEnabled(true); place.setFocusableInTouchMode(true); place.setClickable(true); return true; case R.id.Delete_Contact: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.deleteContact) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mydb.deleteContact(id_To_Update); Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(getApplicationContext(),MainActivity.class); startActivity(intent); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog } }); AlertDialog d = builder.create(); d.setTitle("Are you sure"); d.show(); return true; default: return super.onOptionsItemSelected(item); } } public void run(View view) { Bundle extras = getIntent().getExtras(); if(extras !=null) { int Value = extras.getInt("id"); if(Value>0){ if(mydb.updateContact(id_To_Update,name.getText().toString(), phone.getText().toString(), email.getText().toString(), street.getText().toString(), place.getText().toString())){ Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(getApplicationContext(),MainActivity.class); startActivity(intent); } else{ Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show(); } } else{ if(mydb.insertContact(name.getText().toString(), phone.getText().toString(), email.getText().toString(), street.getText().toString(), place.getText().toString())){ Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show(); } Intent intent = new Intent(getApplicationContext(),MainActivity.class); startActivity(intent); } } } }
下面是数据库类的内容DBHelper.java
package com.example.addressbook; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase; public class DBHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "MyDBName.db"; public static final String CONTACTS_TABLE_NAME = "contacts"; public static final String CONTACTS_COLUMN_ID = "id"; public static final String CONTACTS_COLUMN_NAME = "name"; public static final String CONTACTS_COLUMN_EMAIL = "email"; public static final String CONTACTS_COLUMN_STREET = "street"; public static final String CONTACTS_COLUMN_CITY = "place"; public static final String CONTACTS_COLUMN_PHONE = "phone"; private HashMap hp; public DBHelper(Context context) { super(context, DATABASE_NAME , null, 1); } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL( "create table contacts " + "(id integer primary key, name text,phone text,email text, street text,place text)" ); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub db.execSQL("DROP TABLE IF EXISTS contacts"); onCreate(db); } public boolean insertContact (String name, String phone, String email, String street,String place) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("name", name); contentValues.put("phone", phone); contentValues.put("email", email); contentValues.put("street", street); contentValues.put("place", place); db.insert("contacts", null, contentValues); return true; } public Cursor getData(int id){ SQLiteDatabase db = this.getReadableDatabase(); Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null ); return res; } public int numberOfRows(){ SQLiteDatabase db = this.getReadableDatabase(); int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME); return numRows; } public boolean updateContact (Integer id, String name, String phone, String email, String street,String place) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("name", name); contentValues.put("phone", phone); contentValues.put("email", email); contentValues.put("street", street); contentValues.put("place", place); db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } ); return true; } public Integer deleteContact (Integer id) { SQLiteDatabase db = this.getWritableDatabase(); return db.delete("contacts", "id = ? ", new String[] { Integer.toString(id) }); } public ArrayList<String> getAllCotacts() { ArrayList<String> array_list = new ArrayList<String>(); //hp = new HashMap(); SQLiteDatabase db = this.getReadableDatabase(); Cursor res = db.rawQuery( "select * from contacts", null ); res.moveToFirst(); while(res.isAfterLast() == false){ array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME))); res.moveToNext(); } return array_list; } }
res/layout/activity_main.xml
<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:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:textSize="30dp" android:text="Data Base" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tutorials Point" android:id="@+id/textView2" android:layout_below="@+id/textView" android:layout_centerHorizontal="true" android:textSize="35dp" android:textColor="#ff16ff01" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView" android:layout_below="@+id/textView2" android:layout_centerHorizontal="true" android:src="@drawable/logo"/> <ScrollView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/scrollView" android:layout_below="@+id/imageView" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true"> <ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" > </ListView> </ScrollView> </RelativeLayout>;
res/layout/activity_display_contact.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/scrollView1" android:layout_width="match_parent" android:layout_height="wrap_content" tools:context=".DisplayContact" > <RelativeLayout android:layout_width="match_parent" android:layout_height="370dp" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin"> <EditText android:id="@+id/editTextName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_marginTop="5dp" android:layout_marginLeft="82dp" android:ems="10" android:inputType="text" > </EditText> <EditText android:id="@+id/editTextEmail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editTextStreet" android:layout_below="@+id/editTextStreet" android:layout_marginTop="22dp" android:ems="10" android:inputType="textEmailAddress" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/editTextName" android:layout_alignParentLeft="true" android:text="@string/name" android:textAppearance="?android:attr/textAppearanceMedium" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editTextCity" android:layout_alignParentBottom="true" android:layout_marginBottom="28dp" android:onClick="run" android:text="@string/save" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/editTextEmail" android:layout_alignLeft="@+id/textView1" android:text="@string/email" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/textView5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/editTextPhone" android:layout_alignLeft="@+id/textView1" android:text="@string/phone" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/editTextEmail" android:layout_alignLeft="@+id/textView5" android:text="@string/street" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/editTextCity" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/editTextName" android:layout_below="@+id/editTextEmail" android:layout_marginTop="30dp" android:ems="10" android:inputType="text" /> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/editTextCity" android:layout_alignBottom="@+id/editTextCity" android:layout_alignParentLeft="true" android:layout_toLeftOf="@+id/editTextEmail" android:text="@string/country" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/editTextStreet" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editTextName" android:layout_below="@+id/editTextPhone" android:ems="10" android:inputType="text" > <requestFocus /> </EditText> <EditText android:id="@+id/editTextPhone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editTextStreet" android:layout_below="@+id/editTextName" android:ems="10" android:inputType="phone|text" /> </RelativeLayout> </ScrollView>
res/value/string.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Address Book</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <string name="Add_New">Add New</string> <string name="edit">Edit Contact</string> <string name="delete">Delete Contact</string> <string name="title_activity_display_contact">DisplayContact</string> <string name="name">Name</string> <string name="phone">Phone</string> <string name="email">Email</string> <string name="street">Street</string> <string name="country">City/State/Zip</string> <string name="save">Save Contact</string> <string name="deleteContact">Are you sure, you want to delete it.</string> <string name="yes">Yes</string> <string name="no">No</string> </resources>
Following is the content of the res/menu/main_menu.xml
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/item1" android:icon="@drawable/add" android:title="@string/Add_New" > </item> </menu>
res/menu/display_contact.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/Edit_Contact" android:orderInCategory="100" android:title="@string/edit"/> <item android:id="@+id/Delete_Contact" android:orderInCategory="100" android:title="@string/delete"/> </menu>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sairamkrishna.myapplication" > <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".DisplayContact"/> </application> </manifest>
下面我们来运行此APP.我假设你的实体机已经连到你的电脑。运行Android studio。
链接到源
http://www.tutorialspoint.com/android/android_sqlite_database.htm
标签:
原文地址:http://www.cnblogs.com/kuangzhuaikuxuandiaozhatian/p/5809139.html