Java 如何使用预加载的sqlite数据库[Android Studio]
最近,我正在尝试使用Android Studio构建一个可以打开现有SQLite数据库的应用程序,而我仍然是Android编程的新手……当我搜索打开数据库的方法时,我发现了以下链接:Java 如何使用预加载的sqlite数据库[Android Studio],java,android,database,sqlite,Java,Android,Database,Sqlite,最近,我正在尝试使用Android Studio构建一个可以打开现有SQLite数据库的应用程序,而我仍然是Android编程的新手……当我搜索打开数据库的方法时,我发现了以下链接: 顺便说一句,我仍然不知道如何将链接上的代码实现到我的项目中……这里是否有人愿意帮助制作示例,或者至少给出一些关于如何使用它的指导?仅举一个简单的例子就足够了……thx before:您可以在活动中使用新的DBManager.getAllCities /** * author zaaach on 2016/1/26
顺便说一句,我仍然不知道如何将链接上的代码实现到我的项目中……这里是否有人愿意帮助制作示例,或者至少给出一些关于如何使用它的指导?仅举一个简单的例子就足够了……thx before:您可以在活动中使用新的DBManager.getAllCities
/**
* author zaaach on 2016/1/26.
*/
public class DBManager {
private static final String ASSETS_NAME = "china_cities.db";
private static final String DB_NAME = "china_cities.db";
private static final String TABLE_NAME = "city";
private static final String NAME = "name";
private static final String PINYIN = "pinyin";
private static final int BUFFER_SIZE = 1024;
private String DB_PATH;
private Context mContext;
// public static DBManager init(){
// if (mInstance == null){
// synchronized (DBManager.class){
// if (mInstance != null){
// mInstance = new DBManager();
// }
// }
// }
// return mInstance;
// }
public DBManager(Context context) {
this.mContext = context;
DB_PATH = File.separator + "data"
+ Environment.getDataDirectory().getAbsolutePath() + File.separator
+ context.getPackageName() + File.separator + "databases" + File.separator;
}
@SuppressWarnings("ResultOfMethodCallIgnored")
public void copyDBFile(){
File dir = new File(DB_PATH);
if (!dir.exists()){
dir.mkdirs();
}
File dbFile = new File(DB_PATH + DB_NAME);
if (!dbFile.exists()){
InputStream is;
OutputStream os;
try {
is = mContext.getResources().getAssets().open(ASSETS_NAME);
os = new FileOutputStream(dbFile);
byte[] buffer = new byte[BUFFER_SIZE];
int length;
while ((length = is.read(buffer, 0, buffer.length)) > 0){
os.write(buffer, 0, length);
}
os.flush();
os.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public List<City> getAllCities(){
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(DB_PATH + DB_NAME, null);
Cursor cursor = db.rawQuery("select * from " + TABLE_NAME, null);
List<City> result = new ArrayList<>();
City city;
while (cursor.moveToNext()){
String name = cursor.getString(cursor.getColumnIndex(NAME));
String pinyin = cursor.getString(cursor.getColumnIndex(PINYIN));
city = new City(name, pinyin);
result.add(city);
}
cursor.close();
db.close();
Collections.sort(result, new CityComparator());
return result;
}
}
指定您尝试此操作时发生的情况,它是否如您预期的那样工作?或者显示任何错误?可能更像是我不知道如何使用它,,,你能给我一些使用该链接代码的示例吗?:我对android编程还是个新手,但如果至少有一个关于如何实现代码的示例,我会很快理解的您是否愿意将已创建的数据库复制到您的应用程序中?此库使用预加载的sqlite数据库