hi friends!,
I am just trying to download image from url to internal storage http://github.com/google/fonts/blob/master/apache/roboto/Roboto-Regular.ttf?raw=true. I have created directory.
try
{
File folder = new File(getFilesDir() + "/"+"SS");
if (!folder.exists())
{
folder.mkdir();
Log.i("Directory","Created");
}
//URL connection
URL url = new URL(fonturl);
HttpURLConnection c = (HttpURLConnection)
url.openConnection();
c.connect();
File apkStorage=new File(getFilesDir().getPath());
Log.i("ApkStorage",""+apkStorage);
outputFile=new File(apkStorage.getAbsolutePath() +"/");
if(!outputFile.exists())
{
try {
outputFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Log.e("FIle", "File Created");
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
}
catch (Exception e) {
e.printStackTrace();
outputFile = null;
Log.e("Error", "Download Error Exception " + e.getMessage());
}
}
It just creating file name what I specified download.jpg not downloading file from url to internal storage.
Error: not downloading font in my directory showing error like this Download Error Exception /data/user/0/sdk.nfnlabs.in.customfonts/files (Is a directory). It should be download directly to my directory like roboto.tff without giving filename.
You can use following function
public void downloadFile(Context context){
public long enqueue;
public DownloadManager dm;
dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse("http://github.com/google/fonts/blob/master/apache/roboto/Roboto-Regular.ttf?raw=true"));
File direct = new File(Environment.getExternalStorageDirectory()
+ "/SS");
if (!direct.exists()) {
direct.mkdirs();
}
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false).setTitle("Downloading...")
.setDescription("Please wait. File is downloading...")
.setDestinationInExternalPublicDir("/SS","Roboto-Regular.ttf")
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
enqueue = dm.enqueue(request);
context.registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
Broadcast receiver class is used for know weather download completes or not.
public BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
File direct = new File(Environment.getExternalStorageDirectory()
+ "/SS");
Toast.makeText(context,"File saved at location : "+direct.getAbsolutePath(),Toast.LENGTH_SHORT).show();
context.unregisterReceiver(receiver);
Activity_Downloads.callDownloadWS(context);
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
}
}
}
}
};
And don't forget to add
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You can get filename from HttpUrlConnection like below
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.connect();
File apkStorage = new File(getFilesDir().getPath());
Log.i("ApkStorage",""+apkStorage);
String raw = c.getHeaderField("Content-Disposition");
// raw = "attachment; filename=Roboto-Regular.ttf"
String fileName;
if(raw != null && raw.indexOf("=") != -1) {
fileName = raw.split("=")[1]; //getting value after '='
} else {
// fall back to random generated file name?
fileName = "unknown_file";
}
outputFile = new File(apkStorage, fileName);
Hope it'll help.
Related
We are working on android application,in which mp3 files should be downloaded into internal storage in a background service. We have implemented this using with code snippet mentioned below inside an intent service,But when we try to play the mp3 we are getting an error,like player is not supporting this audio file. If any one has a solution for this issue,Please advise me for the same.
Code Snippet:
String urlPath = intent.getStringExtra(URL);
String fileName = intent.getStringExtra(FILENAME);
// String fileName = Environment.getExternalStorageDirectory().toString() + "/trail.mp3";
File output = new File(Environment.getExternalStorageDirectory(),
fileName);
File dir = new File(output.getAbsolutePath()
+ "/TRIALS/");
dir.mkdirs();
String path = dir + "/" +"trail" + ".mp3";
File f = new File(path);
if (f.exists()) {
f.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
//URL url = new URL(urlPath);
InputStream input = new BufferedInputStream(url.openStream());
stream = url.openConnection().getInputStream();
InputStreamReader reader = new InputStreamReader(stream);
fos = new FileOutputStream(f.getPath());
byte data[] = new byte[lenghtOfFile];
long total = 0;
int times = -1;
while ((times = reader.read()) != -1) {
fos.write(times);
}
// Successful finished
result = Activity.RESULT_OK;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
publishResults(output.getAbsolutePath(), result);
}
1.Check if urlPath is correct.You can open it by explorer and check if a .mp3 begins to be downloaded.
2.Compare size of the file that you get by explorer to the one that downloaded through your code.
3.If the sizes differ,that means download failure.Try to modify your code like this:
String urlPath = intent.getStringExtra(URL);
String fileName = intent.getStringExtra(FILENAME);
File output = new File(Environment.getExternalStorageDirectory(),
fileName);
File dir = new File(output.getAbsolutePath()
+ "/TRIALS/");
dir.mkdirs();
String path = dir + "/" +"trail" + ".mp3";
File f = new File(path);
if (f.exists()) {
f.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
URLConnection urlcon = url.openConnection();
stream = urlcon.getInputStream();
InputStreamReader reader = new InputStreamReader(stream);
fos = new FileOutputStream(f.getPath());
int times = -1;
while ((times = reader.read()) != -1) {
fos.write(times);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I remove some useless code and add fos.flush() before fos.close().
i m trying to download image and audio using jsonObject
but the problem is when i close my app in background it not work well
code
public class downloadData extends AsyncTask<JSONObject, Void, ArrayList<modelCBlips>> {
Context context;
String cId;
Utils utils;
private DownloadManager mgr = null;
public downloadData(Context context, String cId) {
this.context = context;
this.cId = cId;
utils = new Utils(context);
mgr = (DownloadManager) context.getSystemService(context.DOWNLOAD_SERVICE);
context.registerReceiver(onComplete,
new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
#Override
protected ArrayList<modelCBlips> doInBackground(JSONObject... params) {
ArrayList<modelCBlips> list = new ArrayList<>();
try {
JSONArray blipArray = params[0].getJSONArray("Blips");
for (int i = 0; i < blipArray.length(); i++) {
modelCBlips mcblips = new modelCBlips();
JSONObject jObjBlip = blipArray.getJSONObject(i);
String imagePath = jObjBlip.getString("imagePath");
String audioPath = jObjBlip.getString("audioPath");
mcblips.setImagePath(SaveFile(imagePath));
mcblips.setAudioPath(SaveFile(audioPath));
list.add(mcblips);
if (isCancelled())
System.out.println("istrue");
else
System.out.println("not");
}
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
#Override
protected void onPreExecute() {
utils.editor.putString("status" + cId, "Downloading...").commit();
}
#Override
protected void onPostExecute(ArrayList<modelCBlips> list) {
for (int i = 0; i < list.size(); i++) {
modelCBlips mcb = list.get(i);
utils.con.insertCBlips(mcb.getImagePath(), mcb.getAudioPath());
}
utils.editor.putString("status" + cId, "Downloaded").commit();
utils.editor.putBoolean("download" + cId, true).commit();
}
BroadcastReceiver onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
}
};
public String SaveFile(String path) {
String startdownloadurl = null;
try {
ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir("channel" + cId, Context.MODE_PRIVATE);
if (!directory.exists()) {
directory.mkdir();
}
DownloadManager mgr = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
/* Uri downloadUri = Uri.parse(path);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri);
String imgnm = path.substring(path.lastIndexOf("/") + 1);
startdownloadurl = directory + "/";
System.out.println(" directory " + startdownloadurl);
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false).setTitle("Demo")
.setDescription("Something useful. No, really.")
.setDestinationInExternalPublicDir(startdownloadurl, imgnm);
mgr.enqueue(request);
startdownloadurl = directory + "/" + imgnm;
*/
URL url = new URL(path);
String imgnm = path.substring(path.lastIndexOf("/") + 1);
URLConnection connection = url.openConnection();
connection.connect();
InputStream input = new BufferedInputStream(url.openStream(), 2048);
startdownloadurl = directory + "/" + imgnm;
FileOutputStream output = new FileOutputStream(startdownloadurl);
byte data[] = new byte[2048];
int bytesRead = 0;
while ((bytesRead = input.read(data, 0, data.length)) >= 0) {
output.write(data, 0, bytesRead);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
System.out.println("Exception " + e);
}
return startdownloadurl;
}
}
using this code i m try to download Image and audio file when all image and audio file downloaded successfully and then i ll try to insert in my database
Try to run it in a service as service runs even if app is closed
I am downloading a file from server on completion of download I have to open a file. Know the problem is the file could be of any type so I can't specify and Intent call to open a file with static name like we do to open a PDF file.
What I want is when a file is downloaded it will search if any app is available to open the file else it will show pop up.
I am doing all this inside fragment.
Here my code for downloading :
public class DownloadFile extends AsyncTask<String, Void, Integer> {
String file_name = "";
File sdcard = Environment.getExternalStorageDirectory();
#Override
protected Integer doInBackground(String... params) {
// TODO Auto-generated method stub
try {
HttpURLConnection url_conn = null;
byte[] bffr;
long totalSize = 0;
File directory = new File(
Environment.getExternalStorageDirectory()
+ "/xyz/download");
directory.mkdirs();
// 06-03 17:57:41.160: D/file name(6882):
file_name = "";
file_name = params[0];
Log.d("file name", file_name.toString());
url_conn = (HttpURLConnection) (new URL("http://example.com/uploads/" + file_name)).openConnection();
url_conn.setRequestMethod("GET");
url_conn.setDoOutput(true);
url_conn.connect();
if (url_conn.getContentLength() > 0) {
File imgFile = new File(sdcard + "/xyz/download/",file_name);
FileOutputStream fos = new FileOutputStream(imgFile);
InputStream is = url_conn.getInputStream();
totalSize = url_conn.getContentLength();
// Log.d("File Download Size ",totalSize+"");
long total = 0;
bffr = new byte[1024];
int bufferLength = 0;
while ((bufferLength = is.read(bffr)) > 0) {
total += bufferLength;
publishProgress("" + (int) ((total * 100) / totalSize));
fos.write(bffr, 0, bufferLength);
}
fos.close();
} else
Log.w(file_name.toString(), "FILE NOT FOUND");
return 0;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
private void publishProgress(String... process) {
// TODO Auto-generated method stub
mprogressDialog.setProgress(Integer.parseInt(process[0]));
}
protected void onPostExecute(Integer unused) {
Log.d("after downloading file ", "file downloaded ");
switch (unused) {
case 0:
mprogressDialog.dismiss();
Intent install = new Intent(Intent.ACTION_VIEW);
install.setDataAndType(Uri.fromFile(new File(sdcard + "/xyz/download/",file_name)),
"MIME-TYPE");
install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
app.getBaseContext().startActivity(install);
break;
}
}
}
In post execute I have tried to open it using Intent but that didn't worked.
Any Idea is appreciated
File file = new File(filePath);
MimeTypeMap map = MimeTypeMap.getSingleton();
String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName());
String type = map.getMimeTypeFromExtension(ext);
if (type == null)
type = "*/*";
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.fromFile(file);
intent.setDataAndType(data, type);
startActivity(intent);
install.setDataAndType(Uri.fromFile(new File(sdcard + "/xyz/download/",file_name)),
"MIME-TYPE");
You have to set MIME-TYPE according to file type and it will open it in available apps in the device
Refer this https://stackoverflow.com/a/24134677/3303075
i guess you have to pass valid mime-type to get app chooser popup.
you can get mimeType from file name or file instance.
String fileName = "/path/to/file";
MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
// only by file name
String mimeType = mimeTypesMap.getContentType(fileName);
source https://stackoverflow.com/a/1902146/942224
After download do this--
MimeTypeMap myMime = MimeTypeMap.getSingleton();
Intent newIntent = new Intent(Intent.ACTION_VIEW);
String mimeType = myMime.getMimeTypeFromExtension(fileExt(path).substring(1));
newIntent.setDataAndType(Uri.fromFile(new File(path)), mimeType);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
ReadMailActivity.this.startActivity(newIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(ReadMailActivity.this, "No handler for this type of file.", Toast.LENGTH_LONG).show();
}
try {
URL url = new URL("http://URL/Dragonfly.db");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String[] path = url.getPath().split("/");
String _file = path[path.length - 1];
int lengthOfFile = c.getContentLength();
if(lengthOfFile > 0){ // Copy file if Length > 0
String PATH = db.DB_PATH; ;//Environment.getExternalStorageDirectory()+
Log.v("", "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
String fileName = "Dragonfly.db";
File outputFile = new File(file , fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
}else{
TestAdapter mDbHelper = new TestAdapter(getBaseContext());
mDbHelper.createDatabase();
}
} catch (IOException e) {
e.printStackTrace();
}
I use this code to update database, downloading a new one. but if i dont have a file on server, it replace the database i have for a new empty one (0bytes).
How can i download the file just if it exist on server?
Try to do a status response check:
int responseCode = c.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
{
// update database replacing the old one with the new one
} else {
// continue to use old database
}
This is a code for saving images in SD card if and if not exist.
but i don't know how to read it.
Can anybody help me please.
This is the download file method:
public static String DownLoadFile(String netUrl, String name ) {
try {
//need uses permission WRITE_EXTERNAL_STORAGE
ByteArrayBuffer baf = null;
long startTime = 0;
//get to directory (a File object) from SD Card
File savePath=new File(Environment.getExternalStorageDirectory().getPath()+"/postImages/");
String ext="jpg";
URL url = new URL(netUrl);
//create your specific file for image storage:
File file = new File(savePath, name + "." + ext);
boolean success = true;
if (!savePath.exists()) {
success = savePath.mkdir();
}
if (success) {
if(file.createNewFile())
{
file.createNewFile();
//write the Bitmap
Log.i("file existence", "file does not exist!!!!!!!!!!!");
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
startTime = System.currentTimeMillis();
baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
return file.getAbsolutePath();
}//end of create file if not exists
}//end of if success
} catch (Exception exx) {
if (exx.getMessage() != null) {
} else {
}
}
return null;
}
Try this,
Uri uri = Uri.parse("file:///sdcard/temporary_file.jpg");
img.setImageURI(uri);
if u have image uri so get path from uri like
String Path = fileUri.getPath();
// read file from sdcard
public static byte[] readFromStream(String path) throws Exception { File
file = new File(path); InputStream inputStream = new
FileInputStream(file); ByteArrayOutputStream baos = new
ByteArrayOutputStream(); DataOutputStream dos = new
DataOutputStream(baos); byte[] data = new byte[(int) file.length()]; int
count = inputStream.read(data); while (count != -1) { dos.write(data, 0,
count); count = inputStream.read(data); } return baos.toByteArray(); }