我正在使用我在另一个Android应用程序中创建的外部数据库,我尝试将其导入到我的实际项目中。我创建了ASSETS FOLDER并将数据库粘贴在其中,但它不起作用。我添加了“读取和写入存储”权限,但它也不起作用。
这是我的SQLite。类
public class MySQLiteHelper extends SQLiteOpenHelper {
// Database and Table version
public static final String DATABASE_NAME = "MyImages.sqlite";
public static final String DBLOCATION = "/data/data/bayram.com.historyimages/databases/";
public static final String TABLE_NAME = "Images";
//Columns
public static final String COLUMN_ID = "ID";
public static final String COLUMN_IMAGE = "Image";
public static final String COLUMN_YEAR = "Year";
public static final String COLUMN_KEYWORD = "Keyword";
public static final String COLUMN_PLACE = "Place";
public static final String COLUMN_RESUME="Resume";
//Database version
private static final int DATABASE_VERSION = 1;
// Database creation sql statement
// + COLUMN_IMAGE+ " BLOB NOT NULL,"
private static final String DATABASE_CREATE = "CREATE TABLE "
+ TABLE_NAME + "( "
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_IMAGE+" BLOB,"
+ COLUMN_YEAR+ " TEXT,"
+COLUMN_KEYWORD+ " TEXT,"
+COLUMN_PLACE+ " TEXT,"
+ COLUMN_RESUME+ " TEXT);";
Context mContext;
String databasePath;
String databaseFile;
public MySQLiteHelper(Context context) {
//,String databasePath, String databaseFile)
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.mContext=context;
//this.databasePath=databasePath;mContext.getFilesDir().getPath();
//this.databaseFile = databaseFile;
}
@Override
public void onCreate(SQLiteDatabase db) {
//db.execSQL(DATABASE_CREATE);
//Toast.makeText(mContext,"Data Base created",Toast.LENGTH_LONG).show();
}
public boolean insertImageWithInfos(ImageInfos imageInfos) throws SQLException {
SQLiteDatabase sqLiteDatabase= this.getWritableDatabase();
ContentValues contentValues= new ContentValues();
// contentValues.put(COLUMN_ID,imageInfos.getId());
contentValues.put(COLUMN_IMAGE, imageInfos.getImage());
contentValues.put(COLUMN_KEYWORD,imageInfos.getKeyword());
contentValues.put(COLUMN_YEAR,imageInfos.getYear());
contentValues.put(COLUMN_PLACE,imageInfos.getPlace());
contentValues.put(COLUMN_RESUME,imageInfos.getResume());
long i= sqLiteDatabase.insert(TABLE_NAME, null,contentValues);
if (i==-1)
{
Toast.makeText(mContext,"Elements are not inserted",Toast.LENGTH_LONG).show();
return false;
}
else
{
sqLiteDatabase.close();
Toast.makeText(mContext,"Elements are inserted",Toast.LENGTH_LONG).show();
return true;
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion>oldVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
public ArrayList<String> getAllImages() {
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from "+TABLE_NAME, null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(COLUMN_ID)));
res.moveToNext();
}
return array_list;
}
/*public void showDbElements(){
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor= db.rawQuery("select * from "+TABLE_NAME,null);
if (!cursor.isAfterLast()){
}
}
*/
SQLiteDatabase db;
public ArrayList<ImageInfos> getValuesFromDataBase() {
ArrayList<ImageInfos> imageInfosArrayList = new ArrayList<ImageInfos>();
try {
SQLiteDatabase db = this.getReadableDatabase();
Log.i("MySQLiteHelper","openDatabase is Successful");
Cursor cursor = db.rawQuery("select * from " + TABLE_NAME, null);
if (cursor != null && cursor.moveToFirst())
{
Log.e("moveToCursor: ", "Cursor.moveToFirst is true");
while(cursor.isAfterLast()==false)
{
ImageInfos imageInfos=new ImageInfos(mContext);
imageInfos.setImage();
imageInfos.setYear(cursor.getString(cursor.getColumnIndex(COLUMN_YEAR)));
imageInfos.setKeyword(cursor.getString(cursor.getColumnIndex(COLUMN_KEYWORD)));
imageInfos.setPlace(cursor.getString(cursor.getColumnIndex(COLUMN_PLACE)));
imageInfos.setResume(cursor.getString(cursor.getColumnIndex(COLUMN_RESUME)));
imageInfosArrayList.add(imageInfos);
cursor.moveToNext();
}
}
cursor.close();
db.close();
Log.e("database elements: ", String.valueOf(imageInfosArrayList.size()));
return imageInfosArrayList;
}catch (SQLException e)
{
e.printStackTrace();
return null;
}
// SQLiteDatabase db = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
}
public Bitmap getImage(){
SQLiteDatabase db=getReadableDatabase();
Cursor cursor=db.rawQuery("select "+COLUMN_IMAGE+" from "+TABLE_NAME, new String[]{});
if (cursor==null)
{
Toast.makeText(mContext,"Cursor is empty",Toast.LENGTH_LONG).show();
}
cursor.moveToFirst();
byte[] blob=cursor.getBlob(cursor.getColumnIndex(COLUMN_IMAGE));
ByteArrayInputStream inputStream = new ByteArrayInputStream(blob);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
}
这里是片段,我应该显示我的表格元素
public class UmgebungFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "UmgebungFragment";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
MySQLiteHelper dbHelper;
ArrayList<ImageInfos> imageInfosArrayList;
RecyclerView recyclerView;
RecyclerAdapter recyclerAdapter;
LinearLayoutManager mLayoutManager;
private OnFragmentInteractionListener mListener;
private Context mContext;
private static final String DATABASE_NAME = "Images.db";
public UmgebungFragment() {
}
public static UmgebungFragment newInstance(String param1) {
UmgebungFragment fragment = new UmgebungFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1,null);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext=getContext();
dbHelper=new MySQLiteHelper(mContext);
imageInfosArrayList= new ArrayList<>();
dbHelper.getReadableDatabase();
try {
InputStream inputStream = mContext.getAssets().open(MySQLiteHelper.DATABASE_NAME);
String outFileName = MySQLiteHelper.DBLOCATION + MySQLiteHelper.DATABASE_NAME;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[]buff = new byte[1024];
int length = 0;
while ((length = inputStream.read(buff)) > 0) {
outputStream.write(buff, 0, length);
}
outputStream.flush();
outputStream.close();
Log.w("Umgebung","DB copied");
}catch (Exception e) {
e.printStackTrace();
}
imageInfosArrayList=dbHelper.getValuesFromDataBase();
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.fragment_umgebung, container, false);
recyclerView=(RecyclerView) view.findViewById(R.id.recycler_view_umgebung);
// imageInfosArrayList=dbHelper.getValuesFromDataBase();
if (imageInfosArrayList!=null)
{
recyclerAdapter= new RecyclerAdapter(mContext,imageInfosArrayList);
mLayoutManager = new LinearLayoutManager(mContext,LinearLayoutManager.HORIZONTAL,false);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.scrollToPosition(0);
recyclerView.setAdapter(recyclerAdapter);
return view;
}else{
Log.i(mContext.toString(),"imageInfosArrayList returned null");
}
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
答案 0 :(得分:0)
我认为您的问题是,在从资产中复制文件之前,您是在有效地创建数据库。也就是说,方法onCreate
中的fragmet dbHelper=new MySQLiteHelper(mContext);
以及dbHelper.getReadableDatabase();
中的以下行将创建数据库并调用帮助程序的onCreate
方法。结果将是一个空数据库,因为帮助程序的onCreate
方法不会创建表。
之后复制文件会有问题,因为缓存/内存组件将反映没有表的数据库,即使基础文件包含一个或多个表。即使结构/模式匹配,即匹配的表,您也可能会遇到问题。
一个修复方法是将行dbHelper=new MySQLiteHelper(mContext);
和dbHelper.getReadableDatabase();
移到复制之后,以便打开复制的数据库而不是另一个数据库。
e.g。
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext=getContext();
// Line (1st) moved from here
imageInfosArrayList= new ArrayList<>();
// Line (2nd) moved from here
try {
InputStream inputStream = mContext.getAssets().open(MySQLiteHelper.DATABASE_NAME);
String outFileName = MySQLiteHelper.DBLOCATION + MySQLiteHelper.DATABASE_NAME;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[]buff = new byte[1024];
int length = 0;
while ((length = inputStream.read(buff)) > 0) {
outputStream.write(buff, 0, length);
}
outputStream.flush();
outputStream.close();
Log.w("Umgebung","DB copied");
}catch (Exception e) {
e.printStackTrace();
}
dbHelper=new MySQLiteHelper(mContext); //<< Line (1st) moved here
dbHelper.getReadableDatabase(); //<< Line (2nd) moved here
imageInfosArrayList=dbHelper.getValuesFromDataBase();