vendredi 4 décembre 2015

Downloading Sqlite files

I am working on an app that reads SQLite files. The app works fine while reading local files. I tried uploading the db file to dropbox, download it from my app with asynctask and open it, but the file wont open. I also tried opening the file with another app (SQLite viewer), but it keeps telling me that the file might be corrupt, so I guess the problem is not on my app reading the file. The file works fine when I download it from a browser on my pc, so i assume my download code isn't working properly. Is there a special way to download SQLite files? Any suggestions? Here 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