0

This is my code to download the file from xampp server.but i can not download file.Can anybody fix it?.My teacher said use AsyncTaskn in it how to use it?it show the error "the application may be doing too much work on its main thread."

public class MainActivity extends ActionBarActivity 
{
Button b1;
String FileDownloadPath="http://192.168.1.25/dinesh/di.mp3";
String FileSavePath="com.example.music11/music";
ProgressDialog dialog=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener(){
public void onClick(View arg0)
{
dialog=ProgressDialog.show(MainActivity.this,"", "file is being download", true);
new Thread(new Runnable()
{
public void run()
{
downlaodfile(FileDownloadPath,FileSavePath);
}
}).start();
}
});
}
public void downlaodfile(String FileDownloadPath,String FileSavePath )
{
try{
File SaveFile=new File(FileSavePath);
URL U=new URL(FileDownloadPath);
URLConnection con=U.openConnection();
            int lengthofcontent=con.getContentLength();
            DataInputStream ds=new DataInputStream(U.openStream());
            byte[] buffer=new byte[lengthofcontent];
            ds.readFully(buffer);
            ds.close();
            DataOutputStream db=new DataOutputStream(new FileOutputStream(SaveFile));
            db.write(buffer);
            db.flush();
            db.close();

            hideProgressIndicator();
    }
    catch(FileNotFoundException e)
    {
        hideProgressIndicator();
    }
    catch(IOException e)
    {
        hideProgressIndicator();
    }

    catch(Exception e){

    }
}

private void hideProgressIndicator() {
    // TODO Auto-generated method stub
    runOnUiThread(new Runnable(){
        public void run()
        {
            dialog.dismiss();

        }

    });
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}


}
KUNAL
  • 45
  • 2
  • 5

1 Answers1

0

Here is another great option to improve your networking using "OkHttp" .

Try this link https://github.com/square/okhttp/wiki/Recipes for downloading files (example).

This is the better networking library over native HttpClient for very fast networking operations.just give it a try.

Thanks.

Deep Shah
  • 1,334
  • 3
  • 20
  • 41