Fragment实例,数据存储,数据库SQLite

来源:互联网 发布:sql server 2008服务器 编辑:程序博客网 时间:2024/06/14 08:59

Fragment的用法

模拟微信界面,可滑动切换,也可以点击下面图标切换

public class MainActivity extends FragmentActivity {    private MyFirstFragment myFirstFragment;    private MySecondFragment mySecondFragment;    private MyThirdFragment myThirdFragment;    private FragmentManager mFragmentmanager;    private RadioGroup mRadioGroup;    private ViewPager mViewPager;    private FragmentPagerAdapter mAdapter;    private List<Fragment> mFragments;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mFragmentmanager = getSupportFragmentManager();        mFragments = new ArrayList<>();        myFirstFragment = new MyFirstFragment();        mySecondFragment = new MySecondFragment();        myThirdFragment = new MyThirdFragment();        mFragments.add(myFirstFragment);        mFragments.add(mySecondFragment);        mFragments.add(myThirdFragment);        mViewPager = (ViewPager) findViewById(R.id.viewpager);        mRadioGroup = (RadioGroup) findViewById(R.id.radiogroup);        mAdapter = new MyFragmentAdapter(mFragmentmanager,mFragments);        mViewPager.setAdapter(mAdapter);        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {            @Override            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {                switch (checkedId){                    case R.id.radiobutton1:                        mViewPager.setCurrentItem(0);                        break;                    case R.id.radiobutton2:                        mViewPager.setCurrentItem(1);                        break;                    case R.id.radiobutton3:                        mViewPager.setCurrentItem(2);                        break;                }            }        });        mRadioGroup.check(R.id.radiobutton1);    }

需要写一个adapter,注意继承FragmentPagerAdapter,复写相关方法,

public class MyFragmentAdapter extends FragmentPagerAdapter {    private List<Fragment> mFragments;    public MyFragmentAdapter(FragmentManager fm, List<Fragment> mFragments) {        super(fm);        this.mFragments = mFragments;    }    @Override    public Fragment getItem(int position) {        return mFragments.get(position);    }    @Override    public int getCount() {        return mFragments.size();    }}

布局文件,注意viewpager的写法,要写完整的包名

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:orientation="vertical"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity">    <android.support.v4.view.ViewPager        android:id="@+id/viewpager"        android:layout_width="match_parent"        android:layout_weight="1"        android:layout_height="match_parent">    </android.support.v4.view.ViewPager>    <RadioGroup        android:id="@+id/radiogroup"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_alignParentBottom="true"        android:orientation="horizontal"        android:background="@color/gray">        <RadioButton            android:id="@+id/radiobutton1"            style="@style/main_activity"            android:background="@drawable/msg_background"/>        <RadioButton            android:id="@+id/radiobutton2"            style="@style/main_activity"            android:background="@drawable/fri_background" />        <RadioButton            android:id="@+id/radiobutton3"            style="@style/main_activity"            android:background="@drawable/dyn_background" />    </RadioGroup></LinearLayout>

数据存储

java课程中讲过三种存储方式:
1、文本存储
2、MySql 数据库存储
3、网络存储—Server Lite
Android中有五种存储方式:
1、xml存储
2、文件存储,包括缓存和本地文件
3、数据库—SQLite(最新版本是SQLite3)
4、网络存储
5、ContentProvider 最常见的是手机联系人的存储
存储分为内部存储和外部存储

public class MainActivity extends Activity implements View.OnClickListener{    private TextView mTextview;    private EditText mEditText;    private Button mButtonRead;    private Button mButtonWrite;    private Button mButtonWriteCache;    private Button mButtonReadCache;    private Button mButtonWriteCacheDir;    private Button mButtonWriteSdcard;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mTextview = (TextView) findViewById(R.id.textview);        mEditText = (EditText) findViewById(R.id.edittext);        mButtonRead = (Button) findViewById(R.id.button_read);        mButtonWrite = (Button) findViewById(R.id.button_write);        mButtonWriteCache = (Button) findViewById(R.id.button_write_cache);        mButtonReadCache = (Button) findViewById(R.id.button_read_cache);        mButtonWriteCacheDir = (Button) findViewById(R.id.button_write_cache_dir);        mButtonWriteSdcard = (Button) findViewById(R.id.button_write_sdcard);        mButtonRead.setOnClickListener(this);        mButtonWrite.setOnClickListener(this);        mButtonWriteCache.setOnClickListener(this);        mButtonReadCache.setOnClickListener(this);        mButtonWriteCacheDir.setOnClickListener(this);        mButtonWriteSdcard.setOnClickListener(this);    }    @Override    public void onClick(View view) {        switch (view.getId()){            case R.id.button_read:                SharedPreferences preferences = getSharedPreferences("preferences_test", MODE_PRIVATE);//                SharedPreferences preferences = getPreferences(MODE_PRIVATE);                String content = preferences.getString("edittext_input","默认值");                mTextview.setText(content);                break;            case R.id.button_write:                SharedPreferences preferences2 = getSharedPreferences("preferences_test",MODE_PRIVATE);                SharedPreferences.Editor editor = preferences2.edit();                editor.putString("edittext_input",mEditText.getText().toString());                editor.commit();                break;            case R.id.button_write_cache:                try {                    FileOutputStream outputStream = openFileOutput("HelloCache",MODE_PRIVATE);                    PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream));                    writer.write("你好,缓存");                    writer.flush();                    writer.close();                    outputStream.close();                } catch (FileNotFoundException e) {                    e.printStackTrace();                } catch (IOException e) {                    e.printStackTrace();                }            case R.id.button_read_cache:                try {                    FileInputStream is = openFileInput("HelloCache");                    BufferedReader br = new BufferedReader(new InputStreamReader(is));                    String line = br.readLine();                    while (line!=null){                        Log.d("readcache",""+line);                        line = br.readLine();                    }                } catch (FileNotFoundException e) {                    e.printStackTrace();                } catch (IOException e) {                    e.printStackTrace();                }                break;            case R.id.button_write_cache_dir:                File file = new File(getCacheDir(),"helloworld.txt");                if (!file.exists()){                    try {                        file.createNewFile();                    } catch (IOException e) {                        e.printStackTrace();                    }                }                FileOutputStream outputStream = null;                try {                    outputStream = new FileOutputStream(file);                    PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream));                    writer.write("你好,新的缓存");                    writer.flush();                    writer.close();                    outputStream.close();                } catch (FileNotFoundException e) {                    e.printStackTrace();                } catch (IOException e) {                    e.printStackTrace();                }                break;            case R.id.button_write_sdcard:                Toast toast = Toast.makeText(getApplicationContext(),"写入本地磁盘cache",Toast.LENGTH_SHORT);                File file1 = new File(Environment.getExternalStorageDirectory(),"helloworld.txt");                if (!file1.exists()){                    try {                        file1.createNewFile();                    } catch (IOException e) {                        e.printStackTrace();                    }                }                FileOutputStream outputStream1 = null;                try {                    outputStream = new FileOutputStream(file1);//                    PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream));//                    writer.write("你好,本地磁盘");//                    writer.flush();//                    writer.close();                    outputStream.write("你好,本地磁盘".getBytes());                    outputStream.flush();                    outputStream.close();                } catch (FileNotFoundException e) {                    e.printStackTrace();                } catch (IOException e) {                    e.printStackTrace();                }                break;            default:                break;        }    }
<TextView        android:id="@+id/textview"        android:layout_width="wrap_content"        android:layout_height="wrap_content" />    <EditText        android:id="@+id/edittext"        android:layout_width="match_parent"        android:layout_height="wrap_content" />    <Button        android:id="@+id/button_read"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="读取数据"/>    <Button        android:id="@+id/button_write"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="写入数据"/>    <Button        android:id="@+id/button_write_cache"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="写入缓存数据"/>    <Button        android:id="@+id/button_read_cache"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="读取缓存数据"/>    <Button        android:id="@+id/button_write_cache_dir"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="写入缓存数据到cache文件夹"/>    <Button        android:id="@+id/button_write_sdcard"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="写入本地磁盘"/>

注意读写权限的设置,在manifest里面

<!--插拔式扩展卡读写权限-->    <uses-permission android:name="ANDROID.PERMISSION.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>    <!--手机本身存储的读写权限-->    <uses-permission android:name="ANDROID.PERMISSION.WRITE_EXTERNAL_STORAGE"></uses-permission>

数据库 SQLite

SQLite库可以解析大部分标准SQL语言。但它也省去了一些特性并且加入了一些自己的新特性。
需要写一个类继承SQLiteOpenHelper,复写相应方法,写构造器,注意参数的设定

public class TestSqliteOpenHelper extends SQLiteOpenHelper {    public TestSqliteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {        super(context, name, factory, version);    }    public TestSqliteOpenHelper(Context context,String name){        this(context,name, null,1);    }    @Override    public void onCreate(SQLiteDatabase sqLiteDatabase) {        sqLiteDatabase.execSQL("create table if not exists user(id integer primary key autoincrement,name varchar(20),password varchar(20))");    }    @Override    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {    }}
public class MainActivity extends Activity implements View.OnClickListener{    private Button mButtonCreateDB;    private Button mButtonInsert;    private SQLiteDatabase db;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        TestSqliteOpenHelper helper = new TestSqliteOpenHelper(getApplicationContext(),"my_first_db");        db =  helper.getWritableDatabase();        mButtonCreateDB = (Button) findViewById(R.id.button_create_db);        mButtonInsert = (Button) findViewById(R.id.button_insert);        mButtonCreateDB.setOnClickListener(this);        mButtonInsert.setOnClickListener(this);    }    @Override    public void onClick(View view) {        switch (view.getId()){            case R.id.button_create_db:                break;            case R.id.button_insert:                ContentValues values = new ContentValues();                values.put("name","zhangsan");                values.put("password","123456");                db.insert("user",null,values);                break;        }    }}

数据库SQLite(重新认识)

2016-08-02
数据库的创建,并且创建了两个表book 和Category,并且在onUpgrade方法中完成数据库的升级。

package com.example.databasetest;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteDatabase.CursorFactory;import android.database.sqlite.SQLiteOpenHelper;import android.widget.Toast;public class MyDatabaseHelper extends SQLiteOpenHelper {    private static final String CREATE_BOOK = "create table book("  //创建一个book表            +"id integer primary key autoincrement,"             +"author text,"            +"price real,"            +"pages integer,"            +"name text)";    private static final String CREATE_CATEGORY = "create table Category(" +  //创建一个category表            "id integer primary key autoincrement," +            "category_name text," +            "category_code integer)";    private Context mContext;    public MyDatabaseHelper(Context context, String name,            CursorFactory factory, int version) {        super(context, name, factory, version);        mContext = context;    }    @Override    public void onCreate(SQLiteDatabase db) {        db.execSQL(CREATE_BOOK);        db.execSQL(CREATE_CATEGORY);        Toast.makeText(mContext, "创建数据库成功", Toast.LENGTH_SHORT).show();    }    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {        db.execSQL("drop table if exists book");    //删除表book        db.execSQL("drop table if exists Category");//删除表category        onCreate(db);  //然后再创建数据库,在activity的onCreate方法中,设置数据库version为2,实现了数据库的升级    }}

在activity中进行数据库的操作,包括创建数据库,数据的增删改查,使用事务替换数据。

package com.example.databasetest;import android.support.v7.app.ActionBarActivity;import android.content.ContentValues;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;import android.os.Bundle;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends ActionBarActivity implements OnClickListener{    private Button mButtonCreate;    private Button mButtonAdd;    private Button mButtonUpdate;    private Button mButtonDelete;    private Button mButtonSelect;    private Button mButtonReplace;    private MyDatabaseHelper dbHelper;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 2);//版本升级为2        mButtonCreate = (Button) findViewById(R.id.create_db);        mButtonAdd = (Button) findViewById(R.id.add_data);        mButtonUpdate = (Button) findViewById(R.id.update_data);        mButtonDelete = (Button) findViewById(R.id.delate_data);        mButtonSelect = (Button) findViewById(R.id.select_data);        mButtonReplace = (Button) findViewById(R.id.replace_data);        mButtonCreate.setOnClickListener(this);        mButtonAdd.setOnClickListener(this);        mButtonUpdate.setOnClickListener(this);        mButtonDelete.setOnClickListener(this);        mButtonSelect.setOnClickListener(this);        mButtonReplace.setOnClickListener(this);    }    @Override    public void onClick(View view) {        switch (view.getId()) {        case R.id.create_db:            dbHelper.getWritableDatabase();//以读写方式打开数据库,一旦数据库的磁盘空间满了,数据库就只能读而不能写,            break;        case R.id.add_data:            SQLiteDatabase db = dbHelper.getWritableDatabase();            ContentValues values = new ContentValues();            //开始组装第一条数据            values.put("name", "第一行代码");            values.put("author", "guo");            values.put("pages", 456);            values.put("price", 16.2);            db.insert("book", null, values);//插入第一条数据            values.clear();            //开始组装第二条数据            values.put("name", "java编程思想");            values.put("author", "li");            values.put("pages", 566);            values.put("price", 19.2);            db.insert("book", null, values);//插入第二条数据            break;        case R.id.update_data:            SQLiteDatabase db2 = dbHelper.getWritableDatabase();            ContentValues values2 = new ContentValues();            values2.put("price", 29.99);            db2.update("book", values2, "name = ?", new String[] {"第一行代码"}); //将《第一行代码》的价格改为29.99            break;        case R.id.delate_data:            SQLiteDatabase db3 = dbHelper.getWritableDatabase();            db3.delete("book", "pages > ?", new String[]{"500"});  //删除页码超过500页的书            break;        case R.id.select_data:            SQLiteDatabase db4 = dbHelper.getWritableDatabase();            //查询book表中的所有数据            Cursor cursor = db4.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", "book name is "+name);                    Log.d("MainActivity", "book author is "+author);                    Log.d("MainActivity", "book pages is "+pages);                    Log.d("MainActivity", "book price is "+price);                } while (cursor.moveToNext());            }            break;        case R.id.replace_data://使用事务替换数据            SQLiteDatabase db5 = dbHelper.getWritableDatabase();            db5.beginTransaction();//开启事务            try{                db5.delete("book", null, null);                if (true) {//                  throw new NullPointerException();                }                ContentValues values3 = new ContentValues();                values3.put("name", "权利的游戏");                values3.put("author", "Martin");                values3.put("pages", 720);                values3.put("price", 20.85);                db5.insert("Book", null, values3);                db5.setTransactionSuccessful();//事务执行成功            }catch (Exception e) {                e.printStackTrace();            }finally{                db5.endTransaction();//结束事务            }            break;        default:            break;        }    }}

布局文件,只是按钮而已

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:orientation="vertical"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.example.databasetest.MainActivity" >    <Button         android:id="@+id/create_db"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="创建数据库"/>    <Button         android:id="@+id/add_data"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="添加数据"/>    <Button         android:id="@+id/update_data"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="更新数据"/>    <Button         android:id="@+id/delate_data"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="删除数据"/>    <Button         android:id="@+id/select_data"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="查询数据"/>    <Button         android:id="@+id/replace_data"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="替换数据"/></LinearLayout>
0 0
原创粉丝点击