Android(安卓)打开资源raw文件
16lz
2021-01-26
定义工具类:
package com.apicloud.A699.utils; import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream; import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.os.Environment;import android.util.Log;import com.apicloud.A699.R;public class LocationDBMgr { private final int BUFFER_SIZE = 1024; public static final String DB_NAME = "city_cn.s3db"; public static final String PACKAGE_NAME = "com.apicloud.A699"; public static final String DB_PATH = "/data" + Environment.getDataDirectory().getAbsolutePath() + "/"+ PACKAGE_NAME; private SQLiteDatabase database; private Context context; private File file=null; public LocationDBMgr(Context context) { this.context = context; } public void openDatabase() { this.database = this.openDatabase(DB_PATH + "/" + DB_NAME); } public SQLiteDatabase getDatabase(){ return this.database; } private SQLiteDatabase openDatabase(String dbfile) { try { file = new File(dbfile); if (!file.exists()) { InputStream is = context.getResources().openRawResource(R.raw.city_cn); if(is!=null){ Log.e("cc", "is null"); }else{ } FileOutputStream fos = new FileOutputStream(dbfile); if(is!=null){ Log.e("cc", "fosnull"); }else{ } byte[] buffer = new byte[BUFFER_SIZE]; int count = 0; while ((count =is.read(buffer)) > 0) { fos.write(buffer, 0, count); Log.e("cc", "while"); fos.flush(); } fos.close(); is.close(); } database = SQLiteDatabase.openOrCreateDatabase(dbfile,null); return database; } catch (FileNotFoundException e) { Log.e("cc", "File not found"); e.printStackTrace(); } catch (IOException e) { Log.e("cc", "IO exception"); e.printStackTrace(); } catch (Exception e){ Log.e("cc", "exception "+e.toString()); } return null; } public void closeDatabase() { if(this.database!=null) this.database.close(); }}
在需要地方调用:
public void initSpinner2(int pcode) { // private LocationDBMgr dbm; // private SQLiteDatabase db; dbm = new LocationDBMgr(this); dbm.openDatabase(); db = dbm.getDatabase(); list2 = new ArrayList<AddressItem>(); try { String sql = "select * from city where pcode='" + pcode + "'"; Cursor cursor = db.rawQuery(sql, null); while (cursor.moveToNext()) { int code = cursor.getInt(cursor.getColumnIndex("code")); String name = cursor.getString(cursor.getColumnIndex("name")); AddressItem myListItem = new AddressItem(); myListItem.setName(name); myListItem.setPcode(code); list2.add(myListItem); } } catch (Exception e) { e.printStackTrace(); } dbm.closeDatabase(); db.close(); AddressAdapter myAdapter = new AddressAdapter(this, list2); mSpCity.setAdapter(myAdapter);}
更多相关文章
- 模拟按键操作的几种方式
- 自定义AlertDialog button的样式
- 解析#android.view.InflateException#
- 安卓通知栏自定义布局提示(NotificationCompat.Builder)
- Java - Android(安卓)自定义控件之圆形进度条
- 【备忘】Android模拟小球自由落体(SurfaceView)
- RxJava2源码分析
- Intent的定义及用法
- 安卓自定义简单loading