Android03

    xiaoxiao2021-12-14  14

    Android03

    sharedpreference保存数据

    1.获取sp = getSharedPreferences("config", 0); 2.获取编辑器 Editor editor = sp.edit(); 3.editor.putString(key, value); 4.editor.commit(); 5.获取数据 sp.getString(key ,dafvalue); sp.getInt()...

    利用sp开发一个设置功能

    1.UI界面

    <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:orientation="vertical" tools:context=".MainActivity" > <RelativeLayout android:layout_width="match_parent" android:layout_height="65dp" > <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="8dp" android:text="是否开启音效" android:textSize="22sp" /> <CheckBox android:id="@+id/checkBox1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:layout_marginRight="8dp" /> </RelativeLayout> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="#11000000" /> <SeekBar android:id="@+id/seekBar1" android:layout_width="278dp" android:layout_height="wrap_content" android:max="100" /> </LinearLayout>

    2.逻辑

    public class MainActivity extends Activity { protected static final String TAG = "MainActivity"; private CheckBox cb; private SeekBar seekBar; private SharedPreferences sp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); cb = (CheckBox) findViewById(R.id.checkBox1); seekBar = (SeekBar) findViewById(R.id.seekBar1); sp = this.getSharedPreferences("config", 0); //回显复选框 boolean isChecked = sp.getBoolean("isChecked", false); cb.setChecked(isChecked); //回显进度条 int progress=sp.getInt("progress", 0); seekBar.setProgress(progress); cb.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Log.i(TAG, "当前状态是:"+isChecked); Editor edit = sp.edit(); edit.putBoolean("isChecked", isChecked); edit.commit(); } }); seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { int progress = seekBar.getProgress(); Log.i(TAG,"当前进度"+progress); Editor edit = sp.edit(); edit.putInt("progress", progress); edit.commit(); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { } }); } }

    利用stringbuilder生成xml文件

    /* <?xml version="1.0" encoding="utf-8"?> <student> <name>zhangsan</name> <number>s001</number> <sex>male</sex> </student> */ StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); sb.append("<student>"); sb.append("<name>"); sb.append(name); sb.append("</name>"); sb.append("<number>"); sb.append(num); sb.append("</number>"); sb.append("<sex>"); sb.append(sex); sb.append("</sex>"); sb.append("</student>"); try { File file = new File(getFilesDir(), name+".xml"); FileOutputStream os = new FileOutputStream(file); os.write(sb.toString().getBytes()); os.close(); Toast.makeText(this, "数据保存成功", 0).show(); } catch (Exception e) { Toast.makeText(this, "数据保存失败", 0).show(); e.printStackTrace(); } }

    stringbuilder生成xml文件注意的问题

    输入时 张三

    采用xml序列化器生成xml文件

    1.得到xml文件的序列化器

    XmlSerializer serializer = Xml.newSerializer();

    2.指定序列化器的一些初始参数

    File file = new File(getFilesDir(), name+".xml"); FileOutputStream os = new FileOutputStream(file); serializer.setOutput(os, "utf-8");

    3.写xml文件

    serializer.startDocument("utf-8", true);写开头 serializer.startDocument("utf-8", null);也可以 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); serializer.endDocument();写结束 serializer.startTag(null, "number");开始标签 serializer.endTag(null, "number");结束标签 serializer.text();写文本标签 serializer.attribute(namespace, name, value);写属性

    xml文件的解析

    *SAX

    *DOM & DOM4J

    *PULL解析

    //1.获取到一个xml解析器 XmlPullParser parser = Xml.newPullParser(); //2.设置解析器的初始参数 FileInputStream inputStream = new FileInputStream(file); parser.setInput(inputStream, "utf-8"); //3.解析xml文件 XmlPullParser.START_TAG;开始节点 XmlPullParser.END_TAG;结束节点 parser.nextText();2个节点中的值 parser.getName();获取当前节点的名称 parser.next();让解析器解析下一个节点

    采用调试的方式观察pull解析的流程

    一步一步调试就行

    需求

    完成本地的XML文件解析

    @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView tv = (TextView) this.findViewById(R.id.textView1); // <?xml version="1.0" encoding="gbk"?> // <smartresult> // <product type="mobile"> // <phonenum>13512345678</phonenum> // <location>重庆移动神州行卡</location> // <phoneJx>有得有失,华而不实,须防劫财,始保平安 吉带凶</phoneJx> // </product> // </smartresult> try { StringBuilder sb = new StringBuilder(); InputStream is = this.getAssets().open("local.xml"); XmlPullParser parser = Xml.newPullParser(); parser.setInput(is, "utf-8"); int type =XmlPullParser.START_DOCUMENT; while ((type = parser.getEventType())!=XmlPullParser.END_DOCUMENT) { if (type == XmlPullParser.START_TAG) { if ("phonenum".equals(parser.getName())) { sb.append("电话:"+parser.nextText()+"\n"); } else if ("location".equals(parser.getName())) { sb.append("地址:"+parser.nextText()+"\n"); }else if ("phoneJx".equals(parser.getName())) { sb.append("数据:"+parser.nextText()+"\n"); } } parser.next(); } tv.setText(sb.toString()); } catch (Exception e) { e.printStackTrace(); } }

    Android下如何创建数据库

    sqlite

    开源项目,c,嵌入式轻量级数据库

    java中创建文件,类比Android创建数据文件

    //文件的帮助类,得到一个文件的引用,如果文件不存在,第一行代码.第一行代码执行文件不会被创建 File file = new File("文件的名称.db"); file.createNewFile();//创建文件 //2.通过输出流向文件写数据 FileOutputStream fos = new FileOutputStream(file); fos.write("hello".getBytes()); fos.close();

    如何创建数据库

    1.定义一个数据库创建的帮助类

    MyDataBaseOpenHelper extends SQLiteOpenHelper

    2.指定数据库文件的名称,数据库的版本号,默认的游标工厂

    3.通过helper得到一个可写或者是可读的数据库,数据库才会被创建

    helper.getWritableDatabase();

    注意点

    1. 写一个类继承SQLiteOpenHelper 2. 重写构造方法 参数是上下文 3. 从写方法onCreate() onUpgrade()

    onCreate是数据库第一次被创建的时候调用,这个方法只执行一次 onUpgrade是数据库需要被更新的时候被调用,只能升级不能降级

    创建数据库的表结构

    public class StudentDBOpenHelper extends SQLiteOpenHelper { public StudentDBOpenHelper(Context context) { super(context, "info.db ", null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table student (_id integer primary key autoincrement ,name varchar(20) ,sex varchar(6))"); } }

    数据库的升级更新

    @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { System.out.println("数据库 onUpgrade"); db.execSQL("alter table student add account varchar(20)"); }

    数据库的增删改查的sql语句

    *增

    insert into student (name , phone) values ('张三','100');

    *删

    delete from student where name='张三';

    *改

    update student set phone = '119' where name='张三';

    *查

    select * from student;

    数据库的增删改查的实现

    public class StudentDao { private StudentDBOpenHelper helper; public StudentDao(Context context) { helper = new StudentDBOpenHelper(context); } public void add(String name, String sex) { SQLiteDatabase db = helper.getWritableDatabase(); db.execSQL("insert into student (name , sex) values (?,?)", new Object[] { name, sex }); db.close(); } public void delete(String name) { SQLiteDatabase db = helper.getWritableDatabase(); db.execSQL("delete from student where name=?", new Object[] { name }); db.close(); } public void update(String name, String newSex) { SQLiteDatabase db = helper.getWritableDatabase(); db.execSQL("update student set sex = ? where name=?", new Object[] { newSex,name }); db.close(); } public String find(String name) { String sex = null; SQLiteDatabase db = helper.getReadableDatabase(); Cursor cursor = db.rawQuery("select sex from student where name = ?", new String[] { name }); boolean result = cursor.moveToNext(); if (result) { sex = cursor.getString(0); } cursor.close(); db.close(); return sex; } }

    对增删改查的方法进行单元测试

    Junit

    1. 写个类,继承AndroidTestCase 2. 写方法 public throws Exception 3. 清单文件添加 测试框架和测试指令集 public class TestStdentDao extends AndroidTestCase { public void testAdd() throws Exception{ StudentDao dao = new StudentDao(getContext()); dao.add("zhangsan", "male"); } public void testDelete() throws Exception{ StudentDao dao = new StudentDao(getContext()); dao.delete("zhangsan"); } public void testUpdate() throws Exception{ StudentDao dao = new StudentDao(getContext()); dao.update("zhangsan", "female"); } public void testfind() throws Exception{ StudentDao dao = new StudentDao(getContext()); String sex = dao.find("zhangsan"); if (TextUtils.isEmpty(sex)) { System.out.println("学生不存在"); }else{ System.out.println("学生的性别为:"+sex); } } }

    采用命名行查看sqlite数据库的内容

    cmd adb shell cd data/data/com.xxx.studentinfosystem ls -l cd databases ls -l sqlite3 info.db 选择编码utf-8 chcp 65001 选择字体 Lucida Console
    转载请注明原文地址: https://ju.6miu.com/read-963844.html

    最新回复(0)