SlavisaPetkovic SlavisaPetkovic - 5 months ago 24
Android Question

Android: Get SQLite file from server and replace the existing

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.

Answer

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.

Comments