2

I think my connection failed but I cant Repair code.

URL url = new URL( imageURL);
File file = new File(fileName);
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);

when debug it crashed in this part of code. I use

<uses-permission android:name="android.permission.INTERNET"/>

and

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Hamid Shatu
  • 9,664
  • 4
  • 30
  • 41
mohammad madani
  • 135
  • 3
  • 11

3 Answers3

2

Write below code into your MainActivity after setContentView(R.layout.activity_main)

 if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
eliasetm
  • 1,399
  • 11
  • 20
0

Above android 3.0 you need to do all your networking in a seperate thread. So if you try that code in the main thred it will throw a NetworkOnMainThread exception.

try this to verify it:

try{
    URL url = new URL( imageURL);
    File file = new File(fileName);
    URLConnection ucon = url.openConnection();
    InputStream is = ucon.getInputStream();
    BufferedInputStream bis = new BufferedInputStream(is);
}
catch (android.os.NetworkOnMainThreadException ex){
    // Skipp.
}

If your app doesn't crashes this way then you need to use an AssyncTask for the networking. Here is a good examplehow to .

And don't forget to check your filepath as well like @LucianNovac suggests.

Community
  • 1
  • 1
Hegi
  • 193
  • 2
  • 11
0

Try to initialize the file like this:

File extStore = Environment.getExternalStorageDirectory();
File file = new File(extStore, fileName);

and don't forget to put in your manifest file

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Also to avoid Network exception put this into an asynk

class DownloadMyFIle extends AsyncTask<String, Void, DownloadProcess> {

    private Exception exception;

    protected DownloadProcess doInBackground(String... urls) {
        try {
            File extStore = Environment.getExternalStorageDirectory();
            File file = new File(extStore, fileName);
            ....
        } catch (Exception e) {
            this.exception = e;
            return null;
        }
    }

    protected void onPostExecute(DownloadProcess process) {
        // TODO: check this.exception 

    }
}
Lucian Novac
  • 1,255
  • 12
  • 18