Android:从服务器获取SQLite文件并替换现有的 [英] Android: Get SQLite file from server and replace the existing

查看:585
本文介绍了Android:从服务器获取SQLite文件并替换现有的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开发了一个本地基于SQLite的数据库的Android应用程序。
现在我试图用一个简单的文件替换这个SQLite .db数据库与服务器 - 只是从服务器下载.db并替换当前。



我已经创建了一个带有true / false的JSON响应来检查联机.db文件是否比本地.db文件更新,所以我的问题是:如何从www.domain.com/获取.db sqlite.db,并从我的应用程序中替换现有的Android sqlite .db文件。试试这个代码来检查数据库的版本:

解决方案



  class CheckDb扩展AsyncTask< String,Void,String> {
$ b $ @覆盖
保护字符串doInBackground(String ... params){
//创建新的JSON解析器
JSONParser jParser = new JSONParser();

//从URL获取JSON
c = jParser.getJSONFromUrl(url);

尝试{
//获取JSON数组;

//在变量中存储JSON项目
final String id = c.getString(verzija).toString()。trim();

$ b catch(JSONException e){
e.printStackTrace();
}
返回null;

$ b @Override
protected void onPostExecute(String s){
//导入TextView
final TextView json =(TextView)findViewById(R。 id.textView);
//在TextView中设置JSON数据
try {
json.setText(c.getString(verzija).toString()。trim());
String db_version = c.getString(verzija).toString()。trim();
String current_version =3;
if(!db_version.equals(current_version)){

new Thread(new Runnable(){
public void run(){
downloadFile();
}
})。start();

}
else {
dialog.hide();
Toast.makeText(MainActivity.this,您有数据库的有效版本,Toast.LENGTH_SHORT).show();
}
} catch(JSONException e){
e.printStackTrace();
}
super.onPostExecute(s);




$ b $ p
$ b

下载新版本并替换现有的版本:

  void downloadFile(){

尝试{
URL url = new URL dwnload_file_path);
HttpURLConnection urlConnection =(HttpURLConnection)url.openConnection();

urlConnection.setRequestMethod(GET);
urlConnection.setDoOutput(true);

// connect
urlConnection.connect();

//设置我们要保存文件的路径
文件SDCardRoot = Environment.getExternalStorageDirectory();
//创建一个新文件,保存下载的文件
文件文件=新建文件(SDCardRoot,download_db.db);

FileOutputStream fileOutput = new FileOutputStream(file);

//用于从互联网读取数据的流
InputStream inputStream = urlConnection.getInputStream();

//这是我们正在下载的文件的总大小
totalSize = urlConnection.getContentLength();

runOnUiThread(new Runnable(){
public void run(){
pb.setMax(totalSize);
}
});

//创建缓冲区...
byte [] buffer = new byte [1024];
int bufferLength = 0; ((bufferLength = inputStream.read(buffer))> 0){
fileOutput.write(buffer,0,bufferLength);

while
downloadedSize + = bufferLength;
//更新进度条//
runOnUiThread(new Runnable(){
public void run(){
pb.setProgress(downloadedSize);
float per = ((float)downloadedSize / totalSize)* 100;
cur_val.setText(Downloaded+ downloadedSize +KB /+ totalSize +KB(+(int)per +%));
}
});

//完成后关闭输出流//
fileOutput.close();
runOnUiThread(new Runnable(){
public void run(){
// pb.dismiss(); //如果要关闭它..
}
});
$ b} catch(final MalformedURLException e){
showError(Error:MalformedURLException+ e);
e.printStackTrace();
catch(final IOException e){
showError(Error:IOException+ e);
e.printStackTrace();

catch(final Exception e){
showError(错误:请检查您的网络连接+ e);


$ / code $ / pre

另外,你需要改变你想要的路径保存文件并将Internet权限添加到 AndroidManifest


I have developed an Android app with a local SQLite based database. Now I'm trying to sync this SQLite .db database with a server with a simple file replace - Just to download .db from server and replace the current one.

I have already created an JSON response with true/false just to check if the online .db file is newer than the local .db file so my question is: How to get the .db from the www.domain.com/sqlite.db and replace the existing Android sqlite .db file from my app.

解决方案

Try this code to check version of database:

class CheckDb extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        // Creating new JSON Parser
        JSONParser jParser = new JSONParser();

        // Getting JSON from URL
        c = jParser.getJSONFromUrl(url);

        try {
            // Getting JSON Array;

            // Storing  JSON item in a Variable
           final String id = c.getString(verzija).toString().trim();

      }
        catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        //Importing TextView
        final TextView json = (TextView)findViewById(R.id.textView);
        //Set JSON Data in TextView
        try {
            json.setText(c.getString(verzija).toString().trim());
            String db_version = c.getString(verzija).toString().trim();
            String current_version = "3";
            if(!db_version.equals(current_version)) {

                new Thread(new Runnable() {
                    public void run() {
                        downloadFile();
                    }
                }).start();

            }
            else {
                dialog.hide();
                Toast.makeText(MainActivity.this, "You have valid version of database", Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        super.onPostExecute(s);
    }
}

And this for downloading the new version and replacing the existing:

void downloadFile(){

    try {
        URL url = new URL(dwnload_file_path);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);

        //connect
        urlConnection.connect();

        //set the path where we want to save the file
        File SDCardRoot = Environment.getExternalStorageDirectory();
        //create a new file, to save the downloaded file
        File file = new File(SDCardRoot,"download_db.db");

        FileOutputStream fileOutput = new FileOutputStream(file);

        //Stream used for reading the data from the internet
        InputStream inputStream = urlConnection.getInputStream();

        //this is the total size of the file which we are downloading
        totalSize = urlConnection.getContentLength();

        runOnUiThread(new Runnable() {
            public void run() {
                pb.setMax(totalSize);
            }
        });

        //create a buffer...
        byte[] buffer = new byte[1024];
        int bufferLength = 0;

        while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
            fileOutput.write(buffer, 0, bufferLength);
            downloadedSize += bufferLength;
            // update the progressbar //
            runOnUiThread(new Runnable() {
                public void run() {
                    pb.setProgress(downloadedSize);
                    float per = ((float)downloadedSize/totalSize) * 100;
                    cur_val.setText("Downloaded " + downloadedSize + "KB / " + totalSize + "KB (" + (int)per + "%)" );
                }
            });
        }
        //close the output stream when complete //
        fileOutput.close();
        runOnUiThread(new Runnable() {
            public void run() {
                // pb.dismiss(); // if you want close it..
            }
        });

    } catch (final MalformedURLException e) {
        showError("Error : MalformedURLException " + e);
        e.printStackTrace();
    } catch (final IOException e) {
        showError("Error : IOException " + e);
        e.printStackTrace();
    }
    catch (final Exception e) {
        showError("Error : Please check your internet connection " + e);
    }
}

Also, you need to change path where you want to save the file and add internet permission to your AndroidManifest.

这篇关于Android:从服务器获取SQLite文件并替换现有的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆