您的位置:首页 > 编程语言

第一行代码笔记,第六章-----详解数据存储

2016-10-11 19:45 387 查看
1:文件存储:

              原封不动的保存到文件中,适合存储一些文本数据或二进制数据。

          1.1   将数据存储到文件中:

                public  class MainActivity extends Activity   {

                                     private Editext edit;                 

                   onCreate  方法:

                                  edit= (EdxitText)findViewById(R.id.edit);获取文本信息

                  onDestroy方法:

                                   String   inputText = edit.getText().toString();

                                   save(inputText );

                    public void save(String inputText ){

                                  String  data = "我是奔跑的小田";

                                  FileOutputStream   out  =null;                 //输出流。

                                  BufferedWrite    write = null;                   

                           try{

                                 out  = openFileOutput("data",Context.MODE_PRIVATE);

                                write = new BufferedWrite(new OutputStreamWrite(out));

                               write.write(inputText );

                            这块是异常处理finally(不写了)

              1.2  从文件中读取数据

                           在Activity中:‘ 

                                        onCreate方法中:

                                         edit = (EditText)findViewById(R.id.edit);  

                                          String inputText = load();

                                                    if(!TextUtils.isEmpty(inputText )){

                                                          edit.setText(inputText);

                                                         edit.setSelection(input);

                                             Toast.makeText(this,"成功",Toast.LENGTH_SHORT).show;

                       Load方法存储文本

                                   public String load(){

                                                     FileInpuStream in = null;

                                                    BufferedReader reader = null;

                                               StringBuilder content = new StringBuilder();

                                               try{

                                                  in = openFileInput("data");

                                                  reader = new BufferedReader(new InputStreamReader(in));

                                                  String line = "";

                                                   while  ((line = reader.readLine())!=null)  {

                                                   content.append(line);

                           }catch  (IOException e){

                                 e.printStackTrace();

           }finally{

               if(reader!=null){

                           reader.close();

                      }  catch  (IOException e){

                                 e.printStackTrace();

                   }}}

                          return content.toString();

            }}

                                                       

2:SharedPreferences存储

           用键值对的方式存储数据,通过键取值,

                  2.1  将数据存储到SharedPreferences中。

                            获取SharedPreferences对象的方式有三种:

                              2.1.1   Context类中的getSharedPreferences()方法。

                                       两个参数:

                              第一个参数:  指定SharedPreferences文件名称,如过没有新建,(存储放在/data/data/<package name>/shared_prefs目录下)

                            第二个参数:指定操作模式,

                                                     第一种:MODE_PRIVATE,和传入0效果相同,表示只有在当前应用程序才可以对SharedPreferences文件读写。

                                                    第二种: MODE_MULTI_PROCESS ,表示多个进程对同一个SharedPreferences文件进行读写。

                           2.1.2  Activity中的getPreferences()方法。

                                     只接受一个操作模式参数。

                            2.1.3    PreferenceManager  类中的getDefaultSharedPreferences()方法。

                                     这是一个静态方法,只接受一个Context参数,并自动使用当前应用程序的包名作为前缀名来命名SharedPreferences文件。

                                    首先:调用SharedPreferences对象的edit()方法来获取一个SharedPreferences.Editor对象。

                                   其次:向SharedPreferences.Editor对象中添加数据(putBoolean,putString)

                                     最后:调用commit()方法将添加的数据提交。

  例子:                存储数据:

                              SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();

                              editor.putString("name","小田");

                              editor.putInt("age",24);;

                              editor.commit();

                             读取数据:

                           SharedPreferences pref = getSharedPreferences("data",MODE_PRIVATE);

                            String name = pref.getSting("name","");

                            int age = pref.getInt("age",0);

                            Log.d("MainActivity","名字是:"+name);

                             Log.d("MainActivity","年龄是:"+age);

3:SQLite数据库存储

      SQLite是一款轻量级的数据库。

            3.1   创建数据库。

                    Android专门提供了一个SQLiteOpenHelper帮助类, SQLiteOpenHelper是一个抽象类,使用时必须继承他,有两个方法:onCreate()和onUpgrade()。

      重写这两个方法,

                  SQLiteOpenHelper中的构造方法有四个参数:

                      第一个:  Context,上下文。

                      第二个:   数据库名

                      第三个:    一般传入 null就行。

                      第四个:   版本号。

     例子:   

                  3.2     创建DatabaseTest项目:

                    3.2.1   创建数据库:

                        public    class  MyDatabaseHelper  extends  SQLiteOpenHelper  {

               public static final String CREATE_BOOK =    "create table Book  ("                           新建Book表

                              +  " id integer primary  key   autoincrement,  "                (primary  key 将id列设为主键, autoincrement  表示自增长)

                            +    " author  text ,  "                                    文本类型

                             +    priva   real,       "                                  浮点型

                              +   pages  integer, "                                 整型

                              +   name    text)       ;

             private Context mContext ;

              

            public   MyDatabaseHelper(Context context,String name,CursorFactory factory,int version)  {

                                   super(context,name,factory,version) ;

                                   mContext   = context ;

                                        }

           public void onCreate(SQLiteDatabase db){

                               db.execSQL(CREATE_BOOK );

                               Toast.mackText(mContext,"创建成功",Toast.LENGTH_SHORT).show();

                                  }

            onUpgrade  方法 ,更新版本,

 

            3.2.2 在xml中创建一个按钮Button。

             3.2.3    public class MyActvity extends Activity {

                                private    MyDatabaseHelper  dbHelper;

                       onCreate  方法:

              dbHelper  = new  MyDatabaseHelper  (this,"BookStore.db",null,1);

              Button  createDatabase = (Button)findViewById(R.id.create_database);

             createDatabase .setOnClickListener(new OnClickListener(){

                                                  onClick方法:

                                          dbHelper.getWritableDatabase();//写入数据库的方法。

);

     3.3:   升级数据库:

                添加一张表:  Category 表:

             在上面的 数据库中加入:

                            public static final String CREATE_CATEGORY = "craete table Category("

                                                       +"id integer primary key autoincrement,"

                                                      +"category_name text,"

                                                      +"category_code integer)";

                        在OnCreate中:

                                      db.execSQL(CREATE_CATEGORY );

                         在onUpgrade中:

                                        db.execSQL("drop table if exists Book");

                                         db.execSQL("drop table if exists Category ");

                                        onCreate(db);

                       在Activity中:

                                       dbHelper = new  MyDatabaseHelper (this,"BookStore.db",null,2);

    3.4  添加数据:

                       SQLiteDatabase中的insert方法,三个参数:

                                      第一个参数:表名

                                      第二个参数:一般传入null;

                                     第三个参数:是一个ContentValues,提供了一系列的put()方法重载。

                 例子:

                                 在xml中,写个按钮Button

                                 在Activity中:

                                              获取xml中的布局,写个内部类监听:在onCreate中:

                                                    SQLiteDatabase db =  dbHelper.getWritableDatabase();

                                                    ContentValues values = new ContentValues();

                                                   //添加数据

                                                     values.put("name","这是一本新书");

                                                     values.put("author","小田");

                                                      values.put("pages","550");

                                                       values.put("price","25");

                                                       db.insert("Book",null,values);

                                                       values.clear();

3.5  更新数据:

                SQLiteDatabase中,update()方法中4个参数:

                                      第一个参数:表名

                                     第二个参数:ContentValues对象。

                                      第三,第四个参数: 指定更新某一行,或某几行中的内,不指定,就更新所有。

                         和添加不同的地方:

                                     ContentValues values =  new  ContentValues();

                                     values.put("price",20);

                                    db.update("Book",values,"name = ?",new String [] {"新更新的数据"});

3.6    删除数据

           SQLiteDatabase中 delete方法三个参数:

                       第一个参数:表名。

                       第二,四,个参数去除某一行或某几行,默认就是删除所有。

                            很简单

                                   SQLiteDatabase db =  dbHelper.getWritableDatabase();

                                    db.delete("Book","pages>?",new String [] {"600"});

3.7    查询数据

            SQLiteDatabase中  提供了一个query()方法,(最短7个参数)

               第一个参数:  表名

               第二个参数:   查询哪几列,不指定差所有。

               第三个参数:   约束查询某几行或一行数据,不指定查询所有的数据

               第四个参数:   约束查询某几行或一行数据,不指定查询所有的数据

               第五个参数:  指定group by 的列,不指定表示不对查询结果进行group by 操作。

               第六个参数:   对group by 的数据过滤,不指定表示不过滤。

               第七个参数:表示查询结果的排序方式。

        也不难:

                     SQLiteDatabase db= dbHelper.getWritableDatabase();

                    //查询表中的数据:

                    Cursor cursor = db.query("Book",null,null,null,null,null,null);

                     if(cursor.moveToFirst){

                                      do{

                                              //遍历Cursor对象,取出数据,打印。

                                          String name = cursor.getString(cursor.getColumnIndex("name"));

                                          String author= cursor.getString(cursor.getColumnIndex("author"));

                                          int pages  = cursor.getInt(cursor.getColumnIndex("pages  "));

                                           double price = cursor.getDouble(cursor.getColumnIndex("price "));

                                           Log.d("MainActivity","书名是"+name);

                                            Log.d("MainActivity","作者是"+name);

                                            Log.d("MainActivity","页数"+name);

                                            Log.d("MainActivity","价格"+name);

                                               }while(cursor.moveToNext());

                                                      }

                                     cursor.close();                                   //关闭游标

                         

           
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: