I want to download an audio from the server - android

private void doFileDownload() throws Exception {
BufferedInputStream in = null;
BufferedOutputStream out = null;
String url = "http://www.jimsonmok.com/server/uploads/"; //input
String file = "/sdcard/Shek Kip Mei MTR Station Exit A.3gp"; //output
try{
url += URLEncoder.encode("Shek Kip Mei MTR Station Exit A.3gp");
URL download = new URL(url);
URLConnection downloadConnection = download.openConnection(); //set up connection
in = new BufferedInputStream(downloadConnection.getInputStream());
out = new BufferedOutputStream(new FileOutputStream(file));
int contentlength = downloadConnection.getContentLength(); //getting the length of the file
for(int counter=0;counter < contentlength;counter++) //storing the binary I/O file
out.write(in.read());
}catch(IOException e){
}
in.close();
out.close();
}
I am trying to download an audio from the server using an android phone.
The code above I am using does not work in android.
Does anyone know the reasons?
Thanks a lot!

Related

FileNotFoundExcption on connection.getInputStream(); line on API level less than 23

I am downloading HTML file from server using URLConnection but I am getting FileNotFoundException. My path is correct. Using same code same file is downloaded on android of API level 25 but on API level less than it is not downloading. Also connection.getContentLength(); is giving 311 value always. I am not getting any answer to solve this. I am hereby adding my code.
My class file code is
String HomeScreenResourcefilename = WebHomescreenResObj.getString("FileName");
int ProductTargetID = WebHomescreenResObj.getInt("ProductTargetID");
String WebURL_Part1 = context.getResources().getString(R.string.FileDownloadRootPath)+"/ExhibitorData/";
String WebURL_Part2 = GlobalVariables.tradeShowName+" - "+GlobalVariables.exhibitorName+"/HTMLHomeScreen/"+ProductTargetID +"/"+HomeScreenResourcefilename;
String WebURL = WebURL_Part1 + WebURL_Part2;
try {
URL url = new URL(WebURL);
File file = new File(context.getFilesDir(), HomeScreenResourcefilename);
URLConnection connection = url.openConnection();
connection.connect();
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (Exception e1) {
e1.printStackTrace();
LogE("error in 14 :"+e1);
}
Use HttpURLConnection and then connection.getResponseCode() to get the status code. If it is greater than 400, that might be the reason.
Update: Use url encoding.

Get files from web service

I have a URL(http://xxx.xxx/api/getFiles) which is returning a JSON response. According to the developer of the API, this link also return files (images, pdf, word, excel, video, etc) that we're going to download to our Android device.
This link returns a file path (e.g. "/File Folder/") and file name (e.g. "Penguins.jpg") that will be used to link the file to the web server but I don't have an idea how to do it.
Are there ways to download it using this API?
JSON response:
{
   "status":"success",
   "count":1,
   "files":[
      {
         "file_code":"2",
         "file_name":"Penguins.jpg",
         "file_type":".jpg",
         "file_path”:”\/File Folder\/“
      }
   ]
}
To download file from url following peice of code can help you:
This code will create connection with url server and download it to specified path:
int downloadedSize = 0;
int totalSize = 0;
try {
URL url = new URL("download file url");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//connect
urlConnection.connect();
//set the path where we want to save the file
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, to save the downloaded file
File file = new File(SDCardRoot, "DownloadFileNameWithExtension"); // like test.png
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file which we are downloading
totalSize = urlConnection.getContentLength();
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
}
//close the output stream when complete //
fileOutput.close();
} catch (final MalformedURLException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
} catch (final Exception e) {
e.printStackTrace();
}
Don't forget to add Internet permission in your manifest:D

Printing PDF with Android

I'm trying to print a PDF from within my android application. But everytime i try to print my printed page contains weird data like:
java.io.FileInputStream#418479b0
I assume that my pdf isn't being rendered in the correct way...
Does anybody now how i can correctly convert my pdf to my outputstream?
I already tried the code from this question(Printing pdf in android), but then i get following output on my printed page:
Filter/FlateDecode/Length 69 >>stream
Can anybody help me? :)
This is my code:
Socket socket = new Socket();
String sIP = "192.168.0.250";
String sPort = "9100";
InetSocketAddress socketAddress = new InetSocketAddress(sIP, Integer.parseInt(sPort));
DataOutputStream outputStream;
try{
//file init
File pdfFile = new File(file);
byte[] byteArray=null;
InputStream inputStream = new FileInputStream(pdfFile);
String inputStreamToString = inputStream.toString();
byteArray = inputStreamToString.getBytes();
inputStream.close();
//Socket init
socket.connect(socketAddress, 3000);
outputStream = new DataOutputStream(socket.getOutputStream());
outputStream.write(byteArray);
outputStream.close();
socket.close();
}catch(Exception e){
e.printStackTrace();
}
You could try something like this to get the byteArray:
//file init
File pdfFile = new File(file);
byte[] byteArray = new byte[(int) pdfFile.length()];
FileInputStream fis = new FileInputStream(pdfFile);
fis.read(byteArray);
fis.close();

Android downloading files - Issues with Stream that is not complete yet

Im downloading files from a server, some big, some small.
protected Long doInBackground(Object... params) {
Context context = (Context) params[0];
String name = (String) params[1];
String urlString = (String) params[2];
File mediadir = context.getDir("tvr", Context.MODE_PRIVATE);
try {
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
connection.connect();
int lenghtOfFile = connection.getContentLength();
InputStream is = url.openStream();
Log.d("DOWNLOAD NAME",name);
File new_file = new File(mediadir, name);
FileOutputStream fos = new FileOutputStream(new_file.getPath());
byte data[] = new byte[1024];
int count = 0;
long total = 0;
int progress = 0;
while ((count=is.read(data)) != -1){
total += count;
int progress_temp = (int)total*100/lenghtOfFile;
if(progress_temp%10 == 0 && progress != progress_temp){
progress = progress_temp;
}
fos.write(data, 0, count);
}
is.close();
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e("DOWNLOAD ERROR", e.toString());
}
return null;
}
As I now understand it, Im downloading the file via a stream and streaming the data into a file. So in effect the file is created since the first byte of data.
Now, on the other end of things Im playing files from my internal directory by looking for files in a directory and then playing them:
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setDisplay(holder);
FileInputStream fileInputStream = new FileInputStream(path);
mediaPlayer.setDataSource(fileInputStream.getFD());
fileInputStream.close();
mediaPlayer.prepare();
mediaPlayer.start();
Now this issue is that the file will be played even though its not fully downloaded!
Is this true? If so, how must I check if the file is complete before trying to play it?
Yes, this is a valid scenario, as in many cases your download speed will be slower than the reading and playing speed of the MediaPlayer.
Seeing as you're using an AsyncTask, you can fix this problem by calling the playing code in the onPostExecute() method, as that only runs after all work in the doInBackground() method has completed.

Clear data present in files folder of the app

In my app, I am downloading some files. It gets automatically saved in data/data/project/files folder. Below code is used for that purpose.
URL url = new URL(audioUrl);
URLConnection urlConnection = url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[inputStream.available()];
FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
int j;
while((j = inputStream.read(buffer))!=-1)
{
fos.write(buffer, 0, j);
}
fos.close();
What I require is: before adding anything to this folder i want to clear all files if any are present. How can I do that? Please reply. Thanks in advance.
I got it done by giving:
String[] allFiles = fileList();
for(int k = 0 ; k < allFiles.length; k++) {
deleteFile(allFiles[k]);
}

Categories

Resources