0

I tried using many codes I've found for downloading files with an AsyncTask with no success yet. I get an error on the logcat: E/Error:: No such file or directory. Despite looking for solutions for this error, couldn't find What's missing or wrong.

This is the doInBackground method in which I assume something is missing/wrong:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);

    new DownloadJSON().execute("http://api.androidhive.info/json/movies.json");
}

protected String doInBackground(String...fileUrl) {
        int count;
        try {
            String root = "data/data/com.example.jsonapp2";

            URL url = new URL(fileUrl[0]);

            URLConnection connection = url.openConnection();
            connection.connect();

            // input stream to read file - with 8k buffer
            InputStream input = new BufferedInputStream(url.openStream(), 8192);

            File fileName = new File(root+"/movies.json");
            boolean existsOrNot = fileName.createNewFile(); // if file already exists will do nothing

            // Output stream to write file

            OutputStream output = new FileOutputStream(fileName,false);
            byte data[] = new byte[1024];

            System.out.println("Downloading");
            long total = 0;
            while ((count = input.read(data)) != -1) {
            total += count;

            // writing data to file
            output.write(data, 0, count);
        }
            // flushing output
            output.flush();
            // closing streams
            output.close();
            input.close();
        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }
        return null;
    }

Thanks.

Didn't want to bombard with redundant code. If some other code is needed, I'd love to provide it.

D. Joe
  • 81
  • 10

2 Answers2

0

Your root is wrong

String root = "data/data/package.appname";

make sure your root contains right package name or file path.

package name which should be your application id

Priyanka
  • 3,369
  • 1
  • 10
  • 33
0

UPDATED ANSWER

this is working for me, write file in local storage and read it again on method PostExecute

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

        String fileName;
        String responseTxt;
        String inputLine;
        String folder;

        @Override
        protected Void doInBackground(String... strings) {
            try {
                String root = "data/data/com.example.jsonapp2";
                URL url = new URL(strings[0]);
                HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
                //Set methods and timeouts
                urlConnection.setRequestMethod("GET");
                urlConnection.setReadTimeout(15000);
                urlConnection.setConnectTimeout(15000);

                urlConnection.connect();

                //Create a new InputStreamReader
                InputStreamReader streamReader = new
                        InputStreamReader(urlConnection.getInputStream());
                BufferedReader reader = new BufferedReader(streamReader);

                StringBuilder response  = new StringBuilder();

                //Check if the line we are reading is not null
                while((inputLine = reader.readLine()) != null){
                    response.append(inputLine);
                }

                //Close our InputStream and Buffered reader
                reader.close();
                streamReader.close();

                responseTxt = response.toString();

                Log.d(TAG, "doInBackground: responseText " + responseTxt);

                // PREPARE FOR WRITE FILE TO DEVICE DIRECTORY
                FileOutputStream fos = null;
                fileName = "fileName.json";
                folder = fileFolderDirectory();

                try {
                    fos = new FileOutputStream(new File(folder + fileName));
                    //fos = openFileOutput(folder + fileName, MODE_PRIVATE);
                    fos.write(responseTxt.getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if(fos != null){
                        fos.close();
                    }
                }


            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            // -- THIS METHOD IS USED TO ENSURE YOUR FILE AVAILABLE INSIDE LOCAL DIRECTORY -- //

            FileInputStream fis = null;
            try {
                fis = new FileInputStream(new File(folder +fileName));
                InputStreamReader isr = new InputStreamReader(fis);
                BufferedReader br = new BufferedReader(isr);
                StringBuilder sb = new StringBuilder();
                String text;

                while ((text = br.readLine()) != null) {
                    sb.append(text).append("\n");
                }

                Toast.makeText(TestActivity.this, "result " + sb.toString(), Toast.LENGTH_SHORT).show();

            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

ops, almost forget this method

public static String fileFolderDirectory() {
        String folder = Environment.getExternalStorageDirectory() + File.separator + "write_your_app_name" + File.separator;
        File directory = new File(folder);
        if(!directory.exists()){
            directory.mkdirs();
        }
        return folder;
    }
Nanda Z
  • 1,604
  • 4
  • 15
  • 37
  • can you tell me what device emulator you use? in my side, thats code is working – Nanda Z Feb 18 '19 at 01:25
  • Wait, now i understood why this reproduce empty file. It's because you using using Rest API response without write it in a file – Nanda Z Feb 18 '19 at 09:28
  • I am getting a null pointer exception: `java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.FileInputStream.close()' on a null object reference` This means fis is already garbage collected? – D. Joe Feb 18 '19 at 16:54
  • I think I fixed it. Now I see that that another exception is cought: `W/System.err: java.io.FileNotFoundException: /storage/emulated/0/JSONApp/fileName.json (No such file or directory)`. – D. Joe Feb 18 '19 at 18:49
  • Is it relevant that there's no sd card on my phone? – D. Joe Feb 18 '19 at 19:47
  • In my sample the data will save on internalStorage and folder "write_your_app_name". I have clarified it works on my side after removing close(). Even through you do not have SD card it will keep running to saving your file in InternalStorage – Nanda Z Feb 19 '19 at 01:15
  • That's file has been download, you can check your local Storage inside your folder name. That's Toast only my own code to read data in your local storage, you can remove code inside `onPostExecute()` – Nanda Z Feb 19 '19 at 10:36
  • I removed the parts with close() (there are 2). I see the splash screen and it seems like no file is downloaded. I'll see whay can be done. If you have an idea what might be the problem I'd love to hear it. Thanks. – D. Joe Feb 19 '19 at 11:02
  • Can't find it. If you'll see the logcat it might help? – D. Joe Feb 19 '19 at 11:09
  • The file not there? Can you figure out what is difference your code and my code? – Nanda Z Feb 19 '19 at 11:45
  • Please check your explorer file and find your folder name then look inside. In my postExecute, if the toast appear thats mean your file has been write – Nanda Z Feb 19 '19 at 11:46
  • Maybe it has something to do with permissions to access the app. – D. Joe Feb 19 '19 at 13:12
  • Yup, you need – Nanda Z Feb 19 '19 at 14:09
  • Finally found it! can't see it in my phone. Only on the Device File Explorer. Thank you for your patience! – D. Joe Feb 19 '19 at 21:14
  • I am glad to heard that :D – Nanda Z Feb 20 '19 at 00:37