Example explains how to use Sqlitedatabase in Android _android

Source: Internet
Author: User
Tags gettext sqlite sqlite database

The SQLite database is a built-in database of Android, small and powerful enough to work with most SQL statements, while SQLite databases are just files. Although SQLite is a bit much, but not as powerful as the PC-side MySQL, and the Android system is not allowed to operate the remote database through JDBC, so only through the webservice and other means in the PHP, servlet interactive access to data.

The Sqlitedatabase class, which represents a database object, operates through Sqlitedatabase to manage the database.

Some basic uses:

Static Sqlitedatabase OpenDatabase (String path,sqlitedatabase.cursorfactory factory,int flag);

Static Sqlitedatabase Openorcreatedatabase (File file,sqlitedatabase.cursorfactory Factory);

Static Sqlitedatabase Openorcreatedatabase (String path,sqlitedatabse.cursorfactory Factory);

These static methods make it easy to open and create a new database.

1, Execsql (String sql,object[] bindargs)

2, Execsql (String sql)

3, Rawquery (String sql,string[] selectionargs);

4, BeginTransaction ()

5, Endtransaction ()

These functions can complete the SQL function, and the query results are represented by cursor, similar to the ResultSet classes in JDBC, in which the method move (int offset), Movetofirst (), Movetolast (), MoveToNext (), movetoposition (int position), movetoprivious () get the desired result rows.

Here is an example to illustrate the basic use of sqlitedatabase :

Main.xml:

<linearlayout 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:o" rientation= "Vertical" tools:context= ". Main "> <linearlayout android:layout_width=" match_parent "android:layout_height=" Wrap_content "Androi" d:orientation= "Horizontal" > <textview android:layout_width= "wrap_content" W
      Rap_content "android:gravity=" center "android:text=" key "/> <edittext android:id=" @+id/keys " Android:layout_width= "100SP" android:layout_height= "wrap_content"/> <textview android:layout  _width= "Wrap_content" android:layout_height= "wrap_content" android:gravity= "center" android:text= "value" /> <edittext android:id= "@+id/values" android:layout_width= "100SP" android:layout_height= "WR Ap_content "/&Gt
      <button android:id= "@+id/btn" android:layout_width= "100sp" android:layout_height= "Wrap_content" android:text= "Submit"/> </LinearLayout> <linearlayout android:layout_width= "Match_parent" Andro id:layout_height= "Wrap_content" > <listview android:id= "@+id/lv" android:layout_width= "Match_parent"

 "android:layout_height=" wrap_content "/> </LinearLayout> </LinearLayout>

Mytextview.xml for populating data:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
  android:layout_width=" match_parent "
  android:layout_height=" wrap_content "
  android:o" rientation= "Horizontal" >

  <textview
    android:id= "@+id/listkey" android:layout_width= "WRAP_"
    Content "
    android:layout_height=" wrap_content "
    android:layout_gravity=" left "/>

  <textview
    android:id= "@+id/listvalue"
    android:layout_width= "wrap_content"
    android:layout_height= "WRAP_" Content "
    android:layout_marginleft=" 300sp "/>

</LinearLayout>

Main.java

Package com.app.main;
Import Android.annotation.SuppressLint;
Import android.app.Activity;
Import Android.database.Cursor;
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.CursorAdapter;
Import Android.widget.EditText;
Import Android.widget.ListView;

Import Android.widget.SimpleCursorAdapter;
  public class Main extends activity {EditText ed1 = null;
  EditText ed2 = null;
  Button btn = null;
  ListView LV = null;

  Sqlitedatabase db = null;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);

    Setcontentview (R.layout.main);
    ed1 = (edittext) This.findviewbyid (R.id.keys);
    Ed2 = (edittext) This.findviewbyid (r.id.values);
    BTN = (Button) This.findviewbyid (R.ID.BTN);

    LV = (ListView) This.findviewbyid (r.id.lv); db = Sqlitedatabase.openorcreatedatabase (this.getfilesdIR (). toString () + "/MY.DB3", null);  Btn.setonclicklistener (New Onclicklistener () {@Override public void OnClick (view view) {String key

        = Ed1.gettext (). toString ();

        String value = Ed2.gettext (). toString ();

          try {insertdata (db, key, value);

          Cursor Cursor = Db.rawquery ("SELECT * from Tb_info", null);

        Inflatelistview (cursor); catch (Exception e) {String sql = "CREATE TABLE Tb_info" (_id integer primary key autoincrement,db_key varchar

          (a), Db_value varchar (50)) ";

          Db.execsql (SQL);

          InsertData (DB, key, value);

          Cursor Cursor = Db.rawquery ("SELECT * from Tb_info", null);
        Inflatelistview (cursor);

  }

      }

    }); ///Insert data to database private void InsertData (Sqlitedatabase db, String key, String value) {Db.execsql ("insert INTO tb_
    Info values (null,?,?) ", new string[] {key, value}); System.out.println ("------------------"); ///ListView Data @SuppressLint ("Newapi") public void Inflatelistview (Cursor Cursor) {Simplecursoradapter A Dapter = new Simplecursoradapter (main.this, R.layout.mytextview, cursor, new string[] {"Db_key", "db_

    Value "}, new int[] {r.id.listkey, r.id.listvalue}, Cursoradapter.flag_register_content_observer);

  Lv.setadapter (adapter);
    } @Override protected void OnDestroy () {Super.ondestroy ();
    if (db!= null && db.isopen ()) {db.close ());

 }
  }

}

Effect of implementation:

In particular, the column name for the primary key column of the underlying database table is required to be _id when cursor is encapsulated with Simplecursoradapter, because Simplecursoradapter can only recognize tables with a primary key column named _id.

The above is the entire content of this article, I hope to give you a reference, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.