Sqlite&&sharedpreferences&&io Reading and writing SDcard learning notes

Source: Internet
Author: User
Tags sqlite database

Sqlite

Lightweight, embedded, relational database

Widely used database systems such as Android and iOS

SQLite database can be easily used in SQL statements, to achieve data increase, modification, deletion, query and other operations

Sqliteopenhelper: Responsible for creating, opening, updating, closing databases, and creating data tables

sqlitedatabase: Executing SQL statements, adding additions and deletions to data tables

Store the file name , and the data will be saved in the package name/databases/xxxx.db of the/data/data/program

Storing data using Sqlitedatabase
    1. 1. Open or create a test.db database

Sqlitedatabase db = Openorcreatedatabase ("Test.db", Context. Mode_private, null);

Db.execsql ("DROP TABLE IF EXISTS person");

    1. 2. Create a table person

Db.execsql ("CREATE TABLE person (_id INTEGER PRIMARY KEY autoincrement, _name VARCHAR, _age SMALLINT)");

    1. 3. inserting Data

Method "One"

Db.execsql ("INSERT into person VALUES (NULL,?,?)", new object[]{"Mar", 1});

Method "Two" contentvalues storing data in the form of key-value pairs

Contentvalues CV = new contentvalues ();

Cv.put ("_name", "Joy");

Cv.put ("_age", 2);

Db.insert ("person", null, CV); Inserting data from a contentvalues

    1. 4. How to Modify the data "key-value pairs"

CV = New contentvalues ();

Cv.put ("_age", 35);

Db.update ("Person", CV, "name =?", new string[]{"Joy"});

    1. 5. Querying Data

Method "One" Rawquery

Cursor C = Db.rawquery ("Select * from the person WHERE the age >=?", new string[]{"33"});

Method "Two" executes the Query method

Cursor c=db.query ("Users", new string[]{"_id", "_name", "_pwd"},

"_name=?",new string[]{"User01"},null,null,null);

while (C.movetonext ()) {

int id = c.getint (c.getcolumnindex ("_id"));

String name = c.getstring (C.getcolumnindex ("_name"));

int age = C.getint (C.getcolumnindex ("_age"));

Log. D ("DB", "_id=>" + ID + ", name=>" + name + ", age=>" + age);

}

C.close ();//Close result set

    1. 6. Delete Data

Db.delete ("Person", "Age <?", new string[]{"35"});//

Db.delete ("Test", "WHERE _id=" +0, NULL);

Db.execsql ("Delete from table name where condition");

    1. 7. Close the current database

Db.close ();

    1. 8. Deleting a database test.db

DeleteDatabase ("test.db");

Sharedpreferences

A lightweight data retention method that stores data in an XML file in a key-value pair and extracts data from a file via key

There are two ways to get sharedpreferences:
    1. Call the Getsharedpreferences () method of the context object
    2. Invoke the Getpreferences () method of the Activity object

The difference between the two ways:

    • The Sharedpreferences object obtained by invoking the Getsharedpreferences () method of the context object can be shared by other components under the same application.
    • The Sharedpreferences object obtained by invoking the Getpreferences () method of the activity object can only be used in that activity.

Sharedpreferences sp=Supergetsharedpreferences ("App_param", Context. Mode_private);

Store file name , data will be saved in/data/data/base Package/shared_prefs/app_param.xml

Define the operating mode of the file
    1. Current application actions: Context.mode_private

is the default mode of operation, which means that the file is private and can only be accessed by the app itself, where the contents of the original file are overwritten by the written content

    1. Currently applied operation, append mode: Context.mode_append

The schema checks whether the file exists, appends content to the file, or creates a new file.

    1. Can be read by other applications: context.mode_world_readable
    2. Can be written by other applications: context.mode_world_writeable

Read/write SD card

With Sharedpreferences, you can easily complete the storage of your data, but it can only save some very simple data, and if you want to store more types of data, you could use the file's storage operations

Implementation steps:
    1. 1. Add read/write SD card Permissions

<uses-permission android:name="Android.permission.READ_EXTERNAL_STORAGE" />

<uses-permission android:name="Android.permission.WRITE_EXTERNAL_STORAGE" />

    1. 2. determine if the SD card exists "whether read or write, you must judge"

Environment. getexternalstoragestate (). Equals (Environment. Media_mounted

    1. 3. Read and write files

Deposit Data---putxxx (key,value)

Sharedpreferences sp=Supergetsharedpreferences ("App_param", Context. Mode_private);

Sharedpreferences.editor Editor=sp.edit ();

Editor.putstring ("Use", "Tom");

Editor.putint ("Age", 1); Default value 1

Editor.commit ();

Remove data----GetXXX (Key,default)

Sharedpreferences sp=Supergetsharedpreferences ("App_param", Context. Mode_private);

Sp.getint ("use", 0);//Default value 0

IO operation enables sdcard access operation to store data

Private int Save (String Filename,newsitem Item) {

Log. D ("Io", "Save ()");

int ret=0;

Environment.getexternalstoragedirectory () take directory environment.media_mounted loaded

if (! Environment. getexternalstoragestate (). Equals (Environment. media_mounted)) {

return -1;

}

ObjectOutputStream oos=null;

Super.getfilesdir ();//system path

String filepath=environment. getexternalstoragedirectory (). ToString ()

+file. Separator+filename;//file.separator Path

File file=new file (FilePath);//Create files to determine if a file exists

File Parentfile=file.getparentfile ();

if (!parentfile.exists ()) {//parent folder does not exist

Parentfile.mkdir ();//The directory where the files are created

}

Try {

oos=New objectoutputstream ( new Bufferedoutputstream (new fileoutputstream (file));

Oos.writeobject (item);

Ret=1;

} catch (FileNotFoundException e) {

E.printstacktrace ();

} catch (IOException e) {

E.printstacktrace ();

}finally{

Try {

Oos.flush ();

if (oos!=null) Oos.close ();

} catch (IOException e) {

E.printstacktrace ();

}

}

return ret;

}

Fetch data

Private NewsItem Read (String fileName) {

Log. D ("IO", "read ()");

NewsItem item=null; if (! Environment. getexternalstoragestate (). Equals (Environment. media_mounted)) {//if SDcard exists

return null;

}

String filepath=environment. getexternalstoragedirectory (). ToString ()

+file. Separator+filename;//file.separator Path

File file=new file (FilePath);

if (!file.exists ()) {

return null;

}

ObjectInputStream ois=null;

Try {

ois=New objectinputstream ( new Bufferedinputstream (new fileinputstream (file));

Item= (NewsItem) ois.readobject ();

} catch (Streamcorruptedexception e) {

E.printstacktrace ();

} catch (FileNotFoundException e) {

E.printstacktrace ();

} catch (IOException e) {

E.printstacktrace ();

} catch (ClassNotFoundException e) {

E.printstacktrace ();

}finally{

Try {

Ois.close ();

} catch (IOException e) {

E.printstacktrace ();

}

}

return item;

}

Sqlite&&sharedpreferences&&io Reading and writing SDcard learning notes

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.