vendredi 4 décembre 2015

Downloading SQLite database to android

I am working on an app that works with databases and a SQLite database. The database works fine with my app. Then i tried uploading the db file to dropbox, download it from my app with asynctask and open it, but the file wont open. I tried the SQLiteViewer app to open it too, but it keeps telling me that the file might be corrupted. Am i doing something wrong while downloading? This is my downloading code:

@Override
    protected String doInBackground(String... params)
    {
        InputStream input=null;
        OutputStream output=null;
        HttpURLConnection connection=null;
        try
        {
            URL url=new URL(params[0]);
            connection= (HttpURLConnection) url.openConnection();
            connection.connect();

            if(connection.getResponseCode() !=  HttpURLConnection.HTTP_OK)
            {
                return "Server returned HTTP " + connection.getResponseCode()+" " +
                        connection.getResponseMessage();
            }

            int fileLength = connection.getContentLength();

            input = connection.getInputStream();
            File file = new File(Environment.getExternalStorageDirectory().getPath()+"/MyApp/");
            if(!file.exists())
                file.mkdirs();

            output = new FileOutputStream(file.getPath()+"/"+getActivity().getResources().getString(R.string.database_name));

            byte[] data=new byte[4096];
            long total=0;
            int count;

            while((count = input.read(data)) != -1)
            {
                if(isCancelled())
                {
                    input.close();
                    return null;
                }

                total+=count;

                if(fileLength > 0)
                    publishProgress((int)(total *100 / fileLength));

                output.write(data);
            }
        }
        catch (Exception e)
        {
            return e.toString();
        }
        finally
        {
            try
            {
                if(output !=null)
                    output.close();
                if(input != null)
                    input.close();
            }
            catch (IOException e)
            {
                System.out.println(e.toString());
            }

            if(connection != null)
                connection.disconnect();
        }
        return null;
    }

Aucun commentaire:

Enregistrer un commentaire