0

我有一个 sqlite 数据库存储在 assets 文件夹中。当我从 assest 文件夹中复制数据库时,它没有复制数据库。大小始终为 0 字节。

这是我的 DBhelper

  public class DBhelper extends  SQLiteOpenHelper {



private static String DB_NAME = "channels";
private SQLiteDatabase myDataBase; 
private DBhelper db;
public Context myContext;
File dbFile;
File dbFilePath;
Cursor ch;

public DBhelper(Context myContext) { 

    super(myContext, DB_NAME, null, 1);
    this.myContext = myContext;

    System.out.println("Context value from database helper:--"+myContext);
    String state=Environment.getExternalStorageState();
    System.out.println("My Storage State:-"+state);



}   


public void createDataBase(Context mycontext) throws IOException{


    boolean dbExist = checkDataBase();
    if(dbExist){
        System.out.println("Yes Database Exists");
        String path = dbFile.getAbsolutePath();

        System.out.println("My database Path:--"+path);
    }
    if(!dbExist)
    {



        //System.out.println("No Databse Exists so we created Directory:-"+flag); 
        try {

            copyDataBase(); 
        } catch (IOException e) {
            throw new Error("Error copying database");
        }
    }   



}

public boolean checkDataBase() {
    dbFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+"channels");
    return dbFile.exists();
}

/*public boolean checkDataBase()
{
    dbFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+"photodb");
    return dbFile.exists();
}*/



private void copyDataBase() throws IOException{

    dbFile= new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+"NewsFeed");
    boolean flag=dbFile.mkdir();
    dbFilePath = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+"NewsFeed"+"/"+"channels");
    dbFilePath.createNewFile();


    InputStream myInput = myContext.getAssets().open("channels");



    String outFileName = dbFilePath.getAbsolutePath();


    OutputStream myOutput = new FileOutputStream(outFileName);



    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
        myOutput.write(buffer, 0, length);
    }


    myOutput.flush();
    myOutput.close();
    myInput.close();

    System.out.println("Database copy");

}

public void preservedata() throws IOException{

    InputStream myInput = new FileInputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+"NewsFeed"+"/"+"channels") ;
            //myContext.getAssets().open("photodb");



    String outFileName = dbFilePath.getAbsolutePath();


    OutputStream myOutput = new FileOutputStream(outFileName);



    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
        myOutput.write(buffer, 0, length);
    }


    myOutput.flush();
    myOutput.close();
    myInput.close();
}

public void openDataBase() throws SQLException{

    String myPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+"NewsFeed"+"/"+"channels" ;

    System.out.println("MY DATABASE PATH:----"+myPath);
    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}

@Override
public synchronized void close() {
    if(myDataBase != null)
        myDataBase.close();
    super.close();
}

@Override
public void onCreate(SQLiteDatabase db) {

}

我从 getView 方法的 listviewadapter 类调用数据库

 @Override
 public View getView(int i, View view, ViewGroup viewGroup) {
    final ViewHolder vh;
    // View v = view;
    System.out.println("My Context Value from India List :-"+context);



     if (view == null) {
        vh= new ViewHolder();
        LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = vi.inflate(R.layout.newschannelrow, null,false);
     // LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      //   v = vi.inflate(R.layout.newschannelrow, null);



        //  vh.textview = new TextView(mycontext);
           vh.ivNewsChanIcon = (ImageView)view.findViewById(R.id.ivNewsChanIcon);
           vh.tvNameOfChannel = (TextView)view.findViewById(R.id.tvNameOfChannel);
           vh.tvNewsFeedLink = (TextView)view.findViewById(R.id.tvNewsFeedLink);
           vh.tvNewsFav = (CheckBox)view.findViewById(R.id.tvNameofChannelFav);
           vh.tvNewsFav.setTag(i);
            view.setTag(vh); 
            }
            else 
            { 
            vh = (ViewHolder) view.getTag();  
            }       

     NewsFeedLink nfl = data.get(i);
     String name = nfl.getChannelName();
     String link = nfl.getFeedLink();
    vh.tvNameOfChannel.setText(name);
     vh.tvNewsFeedLink.setText(link);
            //ImageView imageView = new ImageView(mycontext);
        //    vh.imageView.setImageResource(ImageIds[position]);
         //   vh.imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);


         //   vh.textview.setText(Imagename[position]);


            //imageView.setLayoutParams(new GridView.LayoutParams(100, 100));

    vh.tvNewsFav.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // TODO Auto-generated method stub
            if(isChecked==false){
            System.out.println("This "+(Integer)buttonView.getTag()+" CheckBox Is un-Clicked");
            }
            if(isChecked==true){
                System.out.println("I am from onCheck Changed in India List context value:-"+context);
                mydb = new DBhelper(context);
                try {
                    mydb.createDataBase(context);
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                mydb.openDataBase();

                System.out.println("This "+(Integer)buttonView.getTag()+" CheckBox Is Clicked");
                mydb.add((vh.tvNameOfChannel).getText().toString(), (vh.tvNewsFeedLink).getText().toString());
                try {
                    mydb.preservedata();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                mydb.close();
                }
        }
    });



            return view;

}

请在这方面提供帮助..

4

1 回答 1

0

试试这个代码

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;

public class SqliteAdapter_InsideDB extends SQLiteOpenHelper {



 private static String DB_PATH = "your path where you need to copy DB ";

 private static String DB_NAME = "your.db";

 private SQLiteDatabase database;

 private final Context myContext;


 public SqliteAdapter_InsideDB(Context context) {

  super(context, DB_NAME, null, 1);
  this.myContext = context;
  try {
   createDataBase();
  } catch (IOException e) {


   e.printStackTrace();

  } catch (Exception e) {
   Log.e("DB-Exception", e.toString());
  }
 } 


 public void createDataBase() throws IOException {

  boolean dbExist = checkDataBase();

  if (dbExist) {

   openDataBase();

  } else {


   this.getReadableDatabase();

   try {

    copyDataBase();
    openDataBase();

   } catch (IOException e) {

    throw new Error("Error copying database");

   }
  }

 }


 private boolean checkDataBase() {

  SQLiteDatabase checkDB = null;

  try {
   String myPath = DB_PATH + DB_NAME;
   checkDB = SQLiteDatabase.openDatabase(myPath, null,
     SQLiteDatabase.OPEN_READWRITE);

  } catch (SQLiteException e) {



  }

  return checkDB != null ? true : false;
 }


 private void copyDataBase() throws IOException {

  InputStream myInput = myContext.getAssets().open(DB_NAME);


  String outFileName = DB_PATH + DB_NAME;


  OutputStream myOutput = new FileOutputStream(outFileName);


  byte[] buffer = new byte[1024];
  int length;
  while ((length = myInput.read(buffer)) > 0) {
   myOutput.write(buffer, 0, length);
  }


  myOutput.flush();
  myOutput.close();
  myInput.close();

 }

 public void openDataBase() throws SQLException {


  String myPath = DB_PATH + DB_NAME;
  database = SQLiteDatabase.openDatabase(myPath, null, 
    SQLiteDatabase.OPEN_READWRITE);

 }



 @Override
 public synchronized void close() {

  if (database != null)
   database.close();

  super.close();

 }

 @Override
 public void onCreate(SQLiteDatabase db) {

 }

 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

 }


 public boolean isOpen() {
  if (database != null) {
   return database.isOpen();
  }
  return false;
 }



 public Cursor executeSQLQuery(String sql, String[] selectionArgs) {
  Cursor cursor = null;
  try {
   if (database != null) {
    cursor = database.rawQuery(sql, selectionArgs);
   }
  } catch (SQLiteException sqle) {
   Toast.makeText(this.myContext,
     "Unable to execute sql query \n" + sqle.getMessage(),
     Toast.LENGTH_SHORT).show();
  }
  return cursor;
 }

 public int getRow(String scanCodeNo) {
  int count;
  count = database
    .query("table_name", null,
      "column_name" + " = '" + value + "'", null, null,
      null, null).getCount();
  database.close();
  return count;
 }
}

不要忘记在Manifest中添加权限

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
于 2013-10-18T10:03:25.203 回答