(对于我可怜的英语,我深感抱歉)
对于学校项目,我必须实现一个Android应用程序。它使用实习SQLite数据库,它是来自网站MySQL数据库的副本。 (android应用程序是电气工程数据库的搜索引擎) 由于它必须独立于网站(离线),我必须创建一个更新选项。
为此,我制作了一个特殊的DownloadHelper类:
@SuppressLint("SdCardPath")
public final class DownloadHelper extends AsyncTask<Void,Void,Void>
{
Context context;
File cheminBdd = new File("/data/data/com.example.btc_pe/databases/basesqlite.db");
public DownloadHelper(Context ctxt)
{ this.context = ctxt; }
@Override
protected Void doInBackground(Void... params)
{
// TODO Auto-generated method stub
try
{
downloadDatabase(cheminBdd);
//copyServerDatabase(this.context);
}
catch (Exception ex)
{
Log.e("BTC","Failed to download database !",ex);
}
return null;
}
private static void downloadDatabase(File destFile) throws IOException
{
URLConnection ucon;
InputStream is = null;
OutputStream os = null;
try
{
Log.d("BTC","start DL");
URL url = new URL("adresse" + "basesqlite.db");
ucon = url.openConnection();
Log.d("BTC","Connection open");
is = ucon.getInputStream();
Log.d("BTC","Stream In got");
os = new FileOutputStream(destFile);
Log.d("BTC","Debut copy()");
copy(is,os);
Log.d("BTC","end DL");
}
finally
{
if (os != null) try { os.close(); } catch (Exception ex) { Log.e("BTC","Failed to gracefully close output stream",ex); }
if (is != null) try { is.close(); } catch (Exception ex) { Log.e("BTC","Failed to gracefully close input stream",ex); }
}
}
public static int copy(InputStream input, OutputStream output) throws IOException
{
byte[] buffer = new byte[8192];
int count = 0;
int n = 0;
while (-1 != (n = input.read(buffer)))
{
output.write(buffer, 0, n);
count += n;
}
output.flush();
return count;
}
@SuppressLint("SdCardPath")
private void copyServerDatabase(Context context)
{
BtcDb db = new BtcDb(context,"clean.db",null,0);
// by calling this line an empty database will be created into the default system path
// of this app - we will then overwrite this with the database from the server
db.getReadableDatabase();
db.close();
OutputStream os = null;
InputStream is = null;
try {
// Log.d("BTC", "Copying DB from server version into app");
is = context.openFileInput("basesqlite.db");
os = new FileOutputStream("/data/data/com.example.btc_pe/databases/");
copyFile(os, is);
}
catch (Exception e)
{
Log.e("BTC", "Server Database was not found - did it download correctly?", e);
}
finally
{
try
{
//Close the streams
if(os != null)
{
os.close();
}
if(is != null)
{
is.close();
}
}
catch (IOException e)
{
Log.e("BTC", "failed to close databases");
}
}
Log.d("BTC", "Done Copying DB from server");
}
private static void copyFile(OutputStream os, InputStream is) throws IOException
{
byte[] buffer = new byte[1024];
int length;
while((length = is.read(buffer))>0)
{
os.write(buffer, 0, length);
}
os.flush();
}
}
我通过操作栏按钮调用更新,使用instanciated对象中的DownloadHelper.execute()方法。 然后我在传递“is = ucon.getInputStream();”后得到一个异常,我得到这个LogCat: http://www.dump-it.fr/btcpng/7865ef3fef44de25fd62f01dad23d02d.png.html
当然,我在服务器,我的网址,我的Android设备上检查了这个文件。没事做。
如果有人能帮助我,我迷路了:/