一、文件方式
直接上代码:
package com.fileop.demo.service; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import android.content.Context; import android.os.Environment; /** * 业务类 * @author sky * */ public class FileService { private Context context; public FileService(Context context) { this.context = context; } /** * 以私有模式保存文件 * 会保存到 /data/data/应用程序包名/files/filename * @param filename * @param content * @throws Exception */ public void save(String filename, String content) throws Exception { /* Context.MODE_PRIVATE 为默认操作模式 Context.MODE_APPEND 也是私有数据,但可以追加文件 Context.MODE_WORLD_READABLE 表示当前文件可以被其他应用所读取 Context.MODE_WORLD_WRITEABLE 表示当前文件可以被其他应用所写入 如果希望文件被其他应用读和写,可传入 openFileOutput(filename, Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE); */ FileOutputStream outStream = context.openFileOutput(filename, Context.MODE_PRIVATE); outStream.write(content.getBytes()); outStream.close(); } /** * 读取文件 * @param filename * @return * @throws Exception */ public String readFile(String filename) throws Exception{ FileInputStream inStream = context.openFileInput(filename); byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream outStream = new ByteArrayOutputStream(); while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } byte[] data = outStream.toByteArray(); outStream.close(); inStream.close(); return new String(data); } /** * 保存文件到SDCard中 * 在SDCard中穿件与删除文件权限: * <uses-permission android:name="android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> * 向SDCard中写入数据权限: * <uses-permission android:name="android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> * @param filename * @param content */ public void saveToSDCard(String filename, String content) throws Exception{ File file = new File(Environment.getExternalStorageDirectory(), filename); FileOutputStream outStream = new FileOutputStream(file); outStream.write(content.getBytes()); outStream.close(); } /** * 判断sdcard是否存在于手机上,并且没有写保护 * @return true 可用; false不可用 */ public boolean isSDCardAvailable(){ if(Environment.getExternalStorageDirectory().equals(Environment.MEDIA_MOUNTED)){ return true; } return false; } }
package com.fileop.demo; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; public class SharedPreferencesDemo extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); SharedPreferences sp = this.getSharedPreferences("filename", Context.MODE_PRIVATE); Editor editor = sp.edit(); editor.putInt("age", 12); editor.putString("name", "sky"); editor.putBoolean("sex", true); editor.putFloat("money", 11.20F); editor.putLong("maxlife", 10000000000L); // 调用commit()之前数据都存在内存中 // 调用之后存放在/data/data/应用程序包名/shared_prefs/下 editor.commit(); //读取sharedPreferences数据 int age = sp.getInt("age", 0); String name = sp.getString("name", ""); boolean sex = sp.getBoolean("sex", true); float money = sp.getFloat("money", 0.00F); long maxlife = sp.getLong("maxlife", 999999999999L); } }
package com.db.demo; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class DBOpenHelper extends SQLiteOpenHelper { private static final String DB_NAME = "demo.db"; private static final int DB_VERSION = 1; public DBOpenHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // 数据库第一次被创建的时候被调用, 所以在此来完成表的创建 String sql = "create table person (personid integer primary key autoincrement, name varchar(20))"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // 数据库版本发生改变时调用 } }
package com.db.demo; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class PersonService { private DBOpenHelper dbOpenHelper; public PersonService(Context context) { dbOpenHelper = new DBOpenHelper(context); } public void insert(Person person) { // 如果要对数据进行更改,就调用getWritableDatabase()方法得到用于操作数据库的实例,该方法以读和写的方式打开数据库 SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); db.execSQL("insert into person(name) values(?)", new Object[] { person.getName() }); } public void update(Person person) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); db.execSQL("update person set name=? where person", new Object[] { person.getName(), person.getId() }); } public void delete(Integer id) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); db.execSQL("delete from person where personid=?", new Object[] { id.toString() }); } public Person find(Integer id) { // 如果只对数据进行读取,建议用getReadableDatabase() SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select * from person where personid=?", new String[] { id.toString() }); if (cursor.moveToFirst()) { int personId = cursor.getInt(cursor.getColumnIndex("personid")); String name = cursor.getString(cursor.getColumnIndex("name")); return new Person(personId, name); } return null; } public List<Person> getScrollData(Integer offset, Integer maxResult) { List<Person> persons = new ArrayList<Person>(); SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select * from person limit ?,?", new String[] {offset.toString(), maxResult.toString()}); while(cursor.moveToNext()) { int personId = cursor.getInt(cursor.getColumnIndex("personid")); String name = cursor.getString(cursor.getColumnIndex("name")); Person person = new Person(personId, name); persons.add(person); } return persons; } public long getCount() { SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select count(*) from person", null); // 肯定有一条记录, 所以不用if判断 cursor.moveToFirst(); return cursor.getLong(0); } }
事物操作:
public void payment(){ SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); db.beginTransaction(); // 事启事务 try { db.execSQL("update person set amount=amount-10 where personid=?", new Object[]{1}); db.execSQL("update person set amount=amount+10 where personid=?", new Object[]{2}); db.setTransactionSuccessful(); // 设置事务标志为成功,当结束事务时就会提交事务 } finally { db.endTransaction(); // 结束事物 } }