Android image file not created - android

I created this AsyncTask to download an image and save it to the phone. If the image already exists is should just skip the code that downloads the image, yet every time it gets to f.exists() it's false even when the image has already been saved previously. Why would this be?
private class fanartDownloader extends AsyncTask<String, Integer, String> {
//First argument is image url and the second is the show id
#Override
protected String doInBackground(String... args) {
String fanartUrl = args[0];
fanartUrl = fanartUrl.substring(0, fanartUrl.length() - 4);
//Add proper end for small image
fanartUrl += SMALL_FANART_URL_END;
try {
String path = getApplicationContext().getFilesDir().toString();
path = path + "/" + args[1] + "/";
File f = new File(path, "fanart.jpg");
if (f.exists()) {
}
else {
f.mkdir();
URL url_value = new URL(fanartUrl);
Bitmap fanart = BitmapFactory.decodeStream(url_value.openConnection().getInputStream());
FileOutputStream out = new FileOutputStream(path);
fanart.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
}
Now I've solved the issue with this slightly different iteration:
private class fanartDownloader extends AsyncTask<String, Integer, String> {
//First argument is image url and the second is the show id
#Override
protected String doInBackground(String... args) {
String fanartUrl = args[0];
fanartUrl = fanartUrl.substring(0, fanartUrl.length() - 4);
//Add proper end for small image
fanartUrl += SMALL_FANART_URL_END;
try {
String file = args[1] + "_" + "fanart.jpg";
String path = getApplicationContext().getFilesDir().toString();
path = path + "/" + file;
File f = new File(path);
if (f.exists()) {
}
else {
URL url_value = new URL(fanartUrl);
Bitmap fanart = BitmapFactory.decodeStream(url_value.openConnection().getInputStream());
FileOutputStream out = getApplicationContext().openFileOutput(file, MODE_PRIVATE);
fanart.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
}
Does anyone know why the first AsyncTask wouldn't work?

Related

Not able to downloade multiple images at same time

In my program i am downloading a Json array file contating data of notices. Each notice contain an address field from where senders image is to be downloaded. So I run another async task to download the images for each json array object. But only 1st image is downloaded no matter how many element json array has. I even tried executeOnExecutor but only folders were created and no images were downloaded.
The onpostexecute method is as below
#Override
protected void onPostExecute(JSONObject jsonObject) {
// TODO Auto-generated method stub
super.onPostExecute(jsonObject);
try {
if (jsonObject.getString("status").equalsIgnoreCase("true")) {
// refining the notices sent by server
JSONArray jsonArray = jsonObject.optJSONArray("notices");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonArrayChild = jsonArray.getJSONObject(i);
// Retrieving data for each notice item
String name = jsonArrayChild.optString("name");
String heading = jsonArrayChild.optString("heading");
String date = jsonArrayChild.optString("date");
String noticeContent = jsonArrayChild
.optString("content");
imageaddress = jsonArrayChild.optString("image");
imageName = imageaddress.substring(
imageaddress.lastIndexOf("/") + 1,
imageaddress.length());
// first we need to download the image from location
// specified in string imageaddress
new ProcessDownloadNoticeSenderImage()
.execute(imageaddress);
// now inserting the overall data into database
// storing the local address of downloaded image in
// database
File file = new File(
Environment.getExternalStorageDirectory()
+ "/veda/images/" + imageName);
String localImageAddress = file.getAbsolutePath();
// storing data in database
noticeMainDatabase.insertNotice(name, heading, date,
noticeContent, localImageAddress);
// first we need to download the image from location
// specified in string imageaddress
}
}
}
and ProcessDownloadNoticeSenderImage is as below
private class ProcessDownloadNoticeSenderImage extends
AsyncTask<String, Integer, Bitmap> {
Bitmap bitmap = null;
#Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
File folder = new File(Environment.getExternalStorageDirectory()
+ "/veda/images");
boolean success = false;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
Toast.makeText(
getApplicationContext(),
"veda/images folder is successfully created to store the images",
Toast.LENGTH_SHORT).show();
}
// saving the downloaded image into folder
File f = new File(Environment.getExternalStorageDirectory(),
"/veda/images/" + imageName);
if (f.exists()) {
FileOutputStream out = null;
try {
out = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (Throwable ignore) {
}
}
} else if (!f.exists()) {
FileOutputStream out = null;
try {
out = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (Throwable ignore) {
}
}
}
try {
bitmap = downloadImageFromServer(params[0]);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
}
help me in how to download multiple images so that i can show them in list.

Storing a file to internal storage and reading it

What I am trying to do is store a JSON file as a string in internal storage to access it later. The reasoning behind this is to not have to access the server on every request, as this data is constant. Once it is stored once, it doesn't have to be retrieved again unless there is some sort of update. File storage isn't something I've done before, and I was hoping someone could give me a hand. My current code is throwing a null pointer exception at this line:
File file = new File(getFilesDir(), fileName);
My code:
protected String doInBackground(String[] runeId) {
String url = "https://prod.api.pvp.net/api/lol/static-data/" + region + "/v1.2/rune/" + runeId[0] + "?api_key=" + api_key;
JSONParser jsonParser = new JSONParser();
JSONObject runeInfo = jsonParser.getJSONFromUrl(url);
String jsonString = runeInfo.toString();
String fileName = "runeInfo";
File file = new File(getFilesDir(), fileName);
String readJson = null;
if(!runesCached) {
Log.d("Cache", "Caching File");
try {
FileOutputStream os = new FileOutputStream(file);
os.write(jsonString.getBytes());
os.close();
Log.d("Cache", "Cache Complete");
runesCached = true;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String name = null;
try {
FileInputStream fis;
File storedRuneInfo = new File(getFilesDir(), fileName);
fis = new FileInputStream(storedRuneInfo);
fis.read(readJson.getBytes());
JSONObject storedJson = new JSONObject(readJson);
try {
name = storedJson.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return name;
}
}
Try this, instead:
File file = new File(getFilesDir().toString(), fileName);
getFilesDir() returns a File, not a String, which the File class constructor takes as a parameter.
getFilesDir()toString() should return something like /data/data/com.your.app/
EDIT:
This gives the same error. How about:
try {
FileWriter fstream;
BufferedWriter out;
fstream = new FileWriter(getFilesDir() + "/" + "filename");
out = new BufferedWriter(fstream);
out.write(jsonString.getBytes());
out.close();
} catch (Exception e){}

Does base64 decoding disable search in pdf files?

There is Arabic encoded pdf file that is received from a server via a web service in my Android application, then I decode it and save it to be cashed to open it anytime,this is the file I download_which also is encoded_ the problem is the file became not searchable anymore, this is the code I use to decode the file:
protected Void doInBackground(String... myLink) {
if (conDetector.isConnectingToInternet()) {
File myDir = getFilesDir();
String fileName = PDFCACHE;
File cachedFile = new File(myDir, fileName);
// to check if the cached file in the memory or not
if (cachedFile.exists()) {
try {
readPDFFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (!cachedFile.exists()) {
try {
URL url = new URL(myLink[0]);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
file_size = urlConnection.getContentLength();
source = new BufferedInputStream(url.openStream(), 8192);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
buffer = new byte[1024];
long total = 0;
int count = 0;
// buffer=new
// Scanner(source).useDelimiter("\\A").next().getBytes();*/
// buffer = Base64.decode(buffer, 0);
for (int i; (i = source.read(buffer)) != -1;) {
total += i;
bos.write(buffer, 0, i); // no doubt here is 0
publishProgress(""
+ (int) ((total * 100) / file_size));
}
if (flag == false) {
bytes = bos.toByteArray();
bytes = Base64.decode(bytes, Base64.DEFAULT);
String decodedString = new String(bytes);
if (bytes != null) {
openBuffer(bytes);
if (manipulateCache())
try {
savePDFFile(bytes);
// source.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
core = openFile(decodedString);
}
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// when there is no internet connection "offline mode"
} else if (!(conDetector.isConnectingToInternet())) {
if (!PDFCACHE.equals(null)) {
try {
readPDFFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
} }
The file you received is not searchable, the font objects contain ToUnicode maps claiming most of the glyphs used are numbers, symbols, or Latin characters which does not match their appearance as Arabic characters.
Thus, no standard PDF viewer can be used to search the files.

Concatenate two audio files and play resulting file

I am really facing problem from last couple of days but I am not able to find the exact solution please help me.
I want to merge two .mp3 or any audio file and play final single one mp3 file. But when I am combine two file the final file size is ok but when I am trying to play it just play first file, I have tried this with SequenceInputStream or byte array but I am not able to get exact result please help me.
My code is the following:
public class MerginFileHere extends Activity {
public ArrayList<String> audNames;
byte fileContent[];
byte fileContent1[];
FileInputStream ins,ins1;
FileOutputStream fos = null;
String combined_file_stored_path = Environment
.getExternalStorageDirectory().getPath()
+ "/AudioRecorder/final.mp3";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audNames = new ArrayList<String>();
String file1 = Environment.getExternalStorageDirectory().getPath()
+ "/AudioRecorder/one.mp3";
String file2 = Environment.getExternalStorageDirectory().getPath()
+ "/AudioRecorder/two.mp3";
File file = new File(Environment.getExternalStorageDirectory()
.getPath() + "/AudioRecorder/" + "final.mp3");
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
audNames.add(file1);
audNames.add(file2);
Button btn = (Button) findViewById(R.id.clickme);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
createCombineRecFile();
}
});
}
public void createCombineRecFile() {
// String combined_file_stored_path = // File path in String to store
// recorded audio
try {
fos = new FileOutputStream(combined_file_stored_path, true);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
File f = new File(audNames.get(0));
File f1 = new File(audNames.get(1));
Log.i("Record Message", "File Length=========>>>" + f.length()+"------------->"+f1.length());
fileContent = new byte[(int) f.length()];
ins = new FileInputStream(audNames.get(0));
int r = ins.read(fileContent);// Reads the file content as byte
fileContent1 = new byte[(int) f1.length()];
ins1 = new FileInputStream(audNames.get(1));
int r1 = ins1.read(fileContent1);// Reads the file content as byte
// from the list.
Log.i("Record Message", "Number Of Bytes Readed=====>>>" + r);
//fos.write(fileContent1);// Write the byte into the combine file.
byte[] combined = new byte[fileContent.length + fileContent1.length];
for (int i = 0; i < combined.length; ++i)
{
combined[i] = i < fileContent.length ? fileContent[i] : fileContent1[i - fileContent.length];
}
fos.write(combined);
//fos.write(fileContent1);*
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.close();
Log.v("Record Message", "===== Combine File Closed =====");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I already published an app with this function... try my method using SequenceInputStream, in my app I just merge 17 MP3 files in one and play it using the JNI Library MPG123, but I tested the file using MediaPlayer without problems.
This code isn't the best, but it works...
private void mergeSongs(File mergedFile,File...mp3Files){
FileInputStream fisToFinal = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mergedFile);
fisToFinal = new FileInputStream(mergedFile);
for(File mp3File:mp3Files){
if(!mp3File.exists())
continue;
FileInputStream fisSong = new FileInputStream(mp3File);
SequenceInputStream sis = new SequenceInputStream(fisToFinal, fisSong);
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fisSong.read(buf)) != -1;)
fos.write(buf, 0, readNum);
} finally {
if(fisSong!=null){
fisSong.close();
}
if(sis!=null){
sis.close();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(fos!=null){
fos.flush();
fos.close();
}
if(fisToFinal!=null){
fisToFinal.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Mp3 files are some frames.
You can concatenate these files by appending the streams to each other if and only if the bit rate and sample rate of your files are same.
If not, the first file plays because it has truly true encoding but the second file can not decode to an true mp3 file.
Suggestion: convert your files with some specific bit rate and sample rate, then use your function.

How to download file/image from url to your android app

I need my android app to make request to url to download an image from this url
so I have built this class to help me, BUT it didn't work ???
public class MyAsnyc extends AsyncTask<Void, Void, Void> {
public static File file;
InputStream is;
protected void doInBackground() throws IOException {
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
file = new File(path, "DemoPicture.jpg");
try{
// Make sure the Pictures directory exists.
path.mkdirs();
URL url = new URL("http://androidsaveitem.appspot.com/downloadjpg");
// Open a connection to that URL.
URLConnection ucon = url.openConnection();
// Define InputStreams to read from the URLConnection.
is = ucon.getInputStream();
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
#Override
protected Void doInBackground(Void... params) {
try {
doInBackground();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute() {
try {
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(
null,
new String[] { file.toString() },
null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
}
);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And I have, in the Activity class on onclick(), this function:
public void down(View v) {
// ImageManager ob=new ImageManager();
// ob.DownloadFromUrl("");
new MyAsnyc().execute();
}
Although I have written the permissions in the manfiest.xml
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
try this
public class MyAsnyc extends AsyncTask<Void, Void, Void> {
public static File file;
InputStream is;
protected void doInBackground() throws IOException {
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
file = new File(path, "DemoPicture.jpg");
try {
// Make sure the Pictures directory exists.
path.mkdirs();
URL url = new URL("http://androidsaveitem.appspot.com/downloadjpg");
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
is = ucon.getInputStream();
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
doInBackground();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute() {
try {
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(null,
new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Define these on the top side
Button BtnDownload;
DownloadManager downloadManager;
After, You should write on create inside :
BtnDownload = (Button)findViewById(R.id.button1);
Later, You should write to the button's click event
downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse("your url");
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = downloadManager.enqueue(request);
Finally, you need to add this onto the application tag to the manifest.xml :
<uses-permission android:name="android.permission.INTERNET"/>
new DownloadImageFromUrlTask().execute(imagePath);
//add glide dependency in app gradle file
compile 'com.github.bumptech.glide:glide:3.7.0'
public class DownloadImageFromUrlTask extends AsyncTask<String, Void, Bitmap> {
String downloadPath = "";
#Override
protected Bitmap doInBackground(String... args) {
try {
downloadPath = args[0];
return BitmapFactory.decodeStream((InputStream) new URL(downloadPath).getContent());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
String photoFileName = downloadPath.substring(downloadPath.lastIndexOf('/') + 1);
String root_Path = Environment.getExternalStorageDirectory().toString();
String saveImagePath = root_Path + "/" + photoFileName;
saveBitmapToJPEGFile(MainActivity.this, bitmap, new File(saveImagePath), 900);
loadImageWithGlide(MainActivity.this, myImageView, saveImagePath);
} else {
myImageView.setImageResource(R.drawable.default_photo);
}
}
}
public static Boolean saveBitmapToJPEGFile(Context ctx, Bitmap theTempBitmap, File theTargetFile, int i) {
Boolean result = true;
if (theTempBitmap != null) {
FileOutputStream out = null;
try {
out = new FileOutputStream(theTargetFile);
theTempBitmap.compress(Bitmap.CompressFormat.JPEG, CommonUtils.JPEG_COMPRESION_RATIO_DEFAULT, out); //kdfsJpegCompressionRatio
} catch (FileNotFoundException e) {
result = false;
e.printStackTrace();
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
result = false;
}
return result;
}
public static void loadImageWithGlide(Context theCtx, ImageView theImageView, String theUrl) {
Glide.with(theCtx)
.load(theUrl)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(theImageView);
}
The problem with your code is you have not read the InputStream.
You should try this
Bitmap bitmap = BitmapFactory.decodeStream(is);
return bitmap;
and make the Asynctask return type as Bitmap.
Or,
As you have used that is in postExecute() your doInBackground() should return that InputStream object is. But you are returning void.
Okey.Try this edited Asynctask.
private class MyAsnyc extends AsyncTask <Void,Void,File> {
File file;
#Override
protected File doInBackground( Void... params ) {
InputStream is = null;
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
file = new File( path , "Demo Picture.jpg" ) ;
try { // Make sure the Pictures directory exists.path.mkdirs() ; URL url = new URL ( "http: / /androidsaveitem .appspot.com/download.jpg") ; URLConnection ucon = url.openConnection ( ) ;
path.mkdirs();
OutputStream os = new FileOutputStream(file) ;
byte [ ] data = new byte [ is.available ( ) ] ;
is.read ( data ) ; os.write (data );is.close ( ) ; os.close ( ) ;
return file;
}
catch (Exception e){
Log .d ( "ImageManager " , " Error: " + e ) ;
}
return null;
}
protected void onPostExecute (File file) {
try{
MediaScannerConnection.scanFile( null , new String [] {file.toString( ) } , null , new MediaScannerConnection.OnScanCompletedListener ( ) { public void onScanCompleted (String path, Uri uri) {
Log.i ( " External Storage" , " Scanned " + path + " : " ) ; Log.i ( " E x t e r n a l S t o r a g e " , " - > u r i = " + uri ) ; } } ) ;
}catch (Exception e) {
// TODO: handle exception
}
}}

Categories

Resources