i want save my picture in a folder that i choose; i have the following code that save in default folder images of my dispositive; how can i modify this code for my app?
PictureCallback myPictureCallback_JPG = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
Uri uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(FotoActivity.this,
"Image saved: " + uriTarget.toString(),
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
camera.startPreview();
}};
add this code to your onPictureTaken
Date now = new Date();
long nowLong = now.getTime() / 9000;
String fname = getPhotoDirectory(MyclassName.this)+"/"+nowLong+".jpg";
String why = "";
try {
File ld = new File(getPhotoDirectory(MyclassName.this));
if (ld.exists()) {
if (!ld.isDirectory()){
MyclassName.this.finish();
}
} else {
ld.mkdir();
}
Log.d(TAG, "open output stream "+fname +" : " +data.length);
OutputStream os = new FileOutputStream(fname);
os.write(data,0,data.length);
os.close();
} catch (FileNotFoundException ex0) {
why = ex0.toString();
ex0.printStackTrace();
} catch (IOException ex1) {
why = ex1.toString();
ex1.printStackTrace();
}
add this method in your class
public static String getPhotoDirectory(Context context)
{
//return Environment.getExternalStorageDirectory().getPath() +"/cbo-up";
return context.getExternalFilesDir(null).getPath() +"/cbo-up";
}
Related
I couldn't find the solution for my issue. My MainActivity creates a pdf file, the user adds some text via EditText and closes it, no problem with that. Then I have a secondary activity that is calling the MediaStore.ACTION_IMAGE_CAPTURE to take pictures. Once a picture is taken, I'd like to know how I can get this just-captured image into that pdf.
I know I have to reopen the pdf, that is no problem, since I have the pdf file name saved in a variable. The major problem that I see is that I don't know how to programmatically get the file name of the picture, once it is automatically named after "yyyyMMdd_hhMMss.jpg". So how to get the file name from a picture taken by my secondary activity?
*EDIT - Showing code:
From MainActivity:
public class MainActivity extends Activity {
public String FILE = Environment.getExternalStorageDirectory() + "/CoManut/sample.pdf";
public static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
public static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL, BaseColor.RED);
public static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16, Font.BOLD);
public static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
EditText estRep;
EditText sensRep;
EditText cabRep;
String estais;
String sensores;
String cabos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
estRep = (EditText)findViewById(R.id.estaisRep);
sensRep = (EditText)findViewById(R.id.sensoresRep);
cabRep = (EditText)findViewById(R.id.cabosRep);
}
public void gerarPDF(View view) {
estais = estRep.getText().toString();
sensores = sensRep.getText().toString();
cabos = cabRep.getText().toString();
try {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(FILE));
document.open();
addMetaData(document);
addTitlePage(document);
addContent(document);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("CoManut");
alertDialog.setMessage("Picture?");
alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MainActivity.this, PhotoActivity.class);
startActivity(intent);
}
});
alertDialog.setButton2("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Thanks for using this app!", Toast.LENGTH_LONG).show();
MainActivity.this.finish();
}
});
alertDialog.setIcon(R.mipmap.ic_launcher);
alertDialog.show();
}
private static void addMetaData(Document document) {
document.addTitle("Image and text to PDF");
document.addSubject("Using iText");
document.addKeywords("Java, PDF, iText");
document.addAuthor("Ricardo Gramowski");
document.addCreator("Ricardo Gramowski");
}
private static void addTitlePage(Document document)
throws DocumentException {
Paragraph preface = new Paragraph();
addEmptyLine(preface, 1);
preface.add(new Paragraph("Maintenance report", catFont));
addEmptyLine(preface, 1);
preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(),
smallBold));
addEmptyLine(preface, 3);
preface.add(new Paragraph("This doc is important", smallBold));
addEmptyLine(preface, 8);
preface.add(new Paragraph("This doc has been generated by Gramowski.",
redFont));
document.add(preface);
// Start a new page
document.newPage();
}
private void addContent(Document document) throws DocumentException {
Anchor anchor = new Anchor("Chapter 1", catFont);
anchor.setName("Chapter 1");
Chapter catPart = new Chapter(new Paragraph(anchor), 1);
Paragraph subPara = new Paragraph("Results", subFont);
Section subCatPart = catPart.addSection(subPara);
addEmptyLine(subPara, 1);
createTable(subCatPart);
document.add(catPart);
}
private void createTable(Section subCatPart)
throws BadElementException {
PdfPTable table = new PdfPTable(2);
PdfPCell c1 = new PdfPCell(new Phrase("Item"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Is that good? (OK/Not OK)"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
table.setHeaderRows(1);
table.addCell("Estais da Torrre ");
table.addCell(estais);
table.addCell("Sensores ");
table.addCell(sensores);
table.addCell("Cabos ");
table.addCell(cabos);
subCatPart.add(table);
}
private static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}
}
And my PhotoActivity:
public class PhotoActivity extends ActionBarActivity {
Button b1;
ImageView iv;
Bitmap bp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
b1 = (Button) findViewById(R.id.button1);
iv = (ImageView) findViewById(R.id.imageView);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap mImageBitmap = (Bitmap) extras.get("data");
iv.setImageBitmap(mImageBitmap);
String fpath = Environment.getExternalStorageDirectory() + "/CoManut/sample.pdf";
File file = new File(fpath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream(fpath));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (DocumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
document.open();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
mImageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
Image myImg = null;
try {
myImg = Image.getInstance(stream.toByteArray());
} catch (BadElementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myImg.setAlignment(Image.MIDDLE);
try {
document.add(myImg);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
document.close();
}
}
// Button to go back to the MainActivity
public void onclickButton2(View view) {
PhotoActivity.this.finish();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
Override your onActivitResult() method in your Main Activity
Here you will get the image bitmap from (Intent Data)
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap mImageBitmap = (Bitmap) extras.get("data");
}
}
Now you have the bitmap. You can add bitmap image like below using the iText Library
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
mImageBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); // Try with Bitmap.CompressFormat.JPG also
Image image = Image.getInstance(stream.toByteArray());
document.add(image);
}catch(IOException ex){
ex.printStackTrace();
}
Update1
Your onActivityResult() should look like this.
Note Make sure you have WRITE_EXTERNAL_STORAGE permissions in your menifest.xml file.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap mImageBitmap = (Bitmap) extras.get("data");
img.setImageBitmap(mImageBitmap);
String fpath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/sample.pdf";
File file = new File(fpath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream(fpath));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (DocumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
document.open();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
mImageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
Image myImg = null;
try {
myImg = Image.getInstance(stream.toByteArray());
} catch (BadElementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myImg.setAlignment(Image.MIDDLE);
try {
document.add(myImg);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
document.close();
}
}
This will create a sample.pdf file in your sdcard and add Image bitmap into it.
Hope this helps.
I tested it here its working. :)
I can rake pictures from this code but i am not able to save the pictures into custom directory Uri uriTarget = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
and i think this is probably the line where i have to change my code
want to make a custom directory and save my image there
Camera.ShutterCallback myShutterCallback = new Camera.ShutterCallback(){
#Override
public void onShutter() {
// TODO Auto-generated method stub
}};
Camera.PictureCallback myPictureCallback_RAW = new Camera.PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
}};
Camera.PictureCallback myPictureCallback_JPG = new Camera.PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
Uri uriTarget = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(MainActivity.this,
"waH kiAa selfie hAi :D ",
//+ uriTarget.toString(),
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
camera.startPreview();
}};
Try this approach...
private void saveImage(byte[] arg0) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "YOUR_CUSTOM_FOLDER";
File myDir = new File(root);
myDir.mkdirs();
String fname = "YOUR_IMAGE_NAME" + ".jpg";
file = new File(myDir, fname);
if (file.exists()) {
file.delete();
}
Bitmap bitmap1 = BitmapFactory.decodeByteArray(arg0, 0, arg0.length);
FileOutputStream out;
try {
out = new FileOutputStream(file);
bitmap1.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
MediaStore.Images.Media.insertImage(activity.getContentResolver(), bitmap1, "", "");
}
i have a imageview , i am trying to save bitmap from imageview by this method
bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
the rgb of saved image is not like that it looks in running app,so i am wondering if there is any way to save image view directly to a sd card rather getting the bitmap and then save it to sd card.
please help me i have tried everything.
You can read and write object using below code :
public static void witeObjectToFile(Context context, Object object, String filename)
{
ObjectOutputStream objectOut = null;
try
{
FileOutputStream fileOut = context.openFileOutput(filename, Activity.MODE_PRIVATE);
objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(object);
fileOut.getFD().sync();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
if (objectOut != null)
{
try
{
objectOut.close();
} catch (IOException e)
{
// do nowt
}
}
}
}
public static Object readObjectFromFile(Context context, String filename)
{
ObjectInputStream objectIn = null;
Object object = null;
try
{
FileInputStream fileIn = context.getApplicationContext().openFileInput(filename);
objectIn = new ObjectInputStream(fileIn);
object = objectIn.readObject();
} catch (FileNotFoundException e)
{
// Do nothing
} catch (IOException e)
{
e.printStackTrace();
} catch (ClassNotFoundException e)
{
e.printStackTrace();
} finally
{
if (objectIn != null)
{
try
{
objectIn.close();
} catch (IOException e)
{
// do nowt
}
}
}
return object;
}
For example ArrayList can be saved as :
ImageView abcImage = (ImageView) readObjectFromFile(context, AppConstants.FILE_PATH_TO_DATA);
and write as :
witeObjectToFile(context, abcImage, AppConstants.FILE_PATH_TO_DATA);
Try to use this
public void onClick(View v) {
if (v.getId() == R.id.btnSaveImage) {
imageView.setDrawingCacheEnabled(true);
Bitmap bm = imageView.getDrawingCache();
storeImage(bm);
}
}
private boolean storeImage(Bitmap imageData) {
// get path to external storage (SD card)
String iconsStoragePath = Environment.getExternalStorageDirectory() + "/yourappname/";
File sdIconStorageDir = new File(iconsStoragePath);
// create storage directories, if they don't exist
sdIconStorageDir.mkdirs();
try {
File file = new File(sdIconStorageDir.toString() + File.separator + "fileName");
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
imageData.compress(CompressFormat.PNG, 100, bos);
bos.flush();
bos.close();
MediaScannerConnection.scanFile(this, new String[] { file.getPath() },
new String[] { "image/jpeg" }, null);
Toast.makeText(this, "Snapshot Saved to " + file, Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
}
return true;
}
here is the code :
my mission is to serialize an my object(Person) , save it in a file in android(privately), read the file later,(i will get a byte array), and deserialize the byta array.
public void setup()
{
byte[] data = SerializationUtils.serialize(f);
WriteByteToFile(data,filename);
}
Person p =null ;
public void draw()
{
File te = new File(filename);
FileInputStream fin = null;
try {
fin=new FileInputStream(te);
byte filecon[]=new byte[(int)te.length()];
fin.read(filecon);
String s = new String(filecon);
System.out.println("File content: " + s);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
text(p.a,150,150);
}
and my function :
public void WriteByteToFile(byte[] mybytes, String filename){
try {
FileOutputStream FOS = openFileOutput(filename, MODE_PRIVATE);
FOS.write(mybytes);
FOS.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("done");
}
it is returning a filenotfoundexception .
(i am new at this, so please be patient and understanding)
EDIT ::this is how i am (trying to ) read, (for cerntainly)
ObjectInputStream input = null;
String filename = "testFilemost.srl";
try {
input = new ObjectInputStream(new FileInputStream(new File(new File(getFilesDir(),"")+File.separator+filename)));
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Person myPersonObject = (Person) input.readObject();
text(myPersonObject.a,150,150);
} catch (OptionalDataException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and for reading :::
if(mousePressed)
{
Person myPersonObject = new Person();
myPersonObject.a=432;
String filename = "testFilemost.srl";
ObjectOutput out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(new File(getFilesDir(),"")+File.separator+filename));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.writeObject(myPersonObject);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You don't need to use the 'byte array' approach. There is an easy way to (de)serialize objects.
EDIT: here's the long version of code
Read:
public void read(){
ObjectInputStream input;
String filename = "testFilemost.srl";
try {
input = new ObjectInputStream(new FileInputStream(new File(new File(getFilesDir(),"")+File.separator+filename)));
Person myPersonObject = (Person) input.readObject();
Log.v("serialization","Person a="+myPersonObject.getA());
input.close();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
Write:
public void write(){
Person myPersonObject = new Person();
myPersonObject.setA(432);
String filename = "testFilemost.srl";
ObjectOutput out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(new File(getFilesDir(),"")+File.separator+filename));
out.writeObject(myPersonObject);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Person class:
public class Person implements Serializable {
private static final long serialVersionUID = -29238982928391L;
int a;
public int getA(){
return a;
}
public void setA(int newA){
a = newA;
}
}
FileNotFoundException when creating a new FileOutputStream means that one of the intermediate directories didn't exist. Try
file.getParentFile().mkdirs();
before creating the FileOutputStream.
Add this code to manifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
Go to phone setting/applications/your_app/permissions/ allow files and media permission. You can ask permission via by code and when user enter app program will ask permission. If you want I can give you code.
All writen and readen objects must be serializable.(Must implements Serializable interface) If A class extends B class, to set B class serializable is enough.
And add this code to writen and readen class:
private static final long serialVersionUID = 1L;
Write to external memory:
public static void writeToExternal(Serializable object, String filename) {
try {
//File root = new File(Environment.getExternalStorageDirectory(), "MyApp");
//or
File root = new File("/storage/emulated/0/MyApp/");
if (!root.exists()) {
root.mkdirs();
}
File file = new File(root, filename);
FileOutputStream fos = new FileOutputStream(file);
ObjectOutput out = new ObjectOutputStream(fos);
out.writeObject(object);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
If you want to write to internal memory(This memory is not visible and doesn't need permission. This is your app stored in. For this, you can use getFilesDir() instead of getExternalStorageDirectory(). More about https://developer.android.com/reference/android/content/ContextWrapper#getFilesDir%28%29
https://developer.android.com/reference/android/os/Environment.html#getDataDirectory%28%29
https://gist.github.com/granoeste/5574148
https://source.android.com/docs/core/storage
public static void writeToInternal(Context context, Serializable object, String filename){
try {
//File root1 = new File(context.getFilesDir(), "MyApp");
//or
File root = new File("/data/user/0/com.example.myapplication/files/MyApp/");
if (!root.exists()) {
root.mkdirs();
}
File file = new File(root, filename);
FileOutputStream fos = new FileOutputStream(file);
ObjectOutput out = new ObjectOutputStream(fos);
out.writeObject(object);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Read an object:
public static Object read(String filename) {
try {
File file = new File("/storage/emulated/0/MyApp/" + filename);
FileInputStream fis = new FileInputStream(file);
ObjectInputStream input = new ObjectInputStream(fis);
Object data = (Object) input.readObject();
input.close();
return data;
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
When you call read method you must cast to your readen and writen class.(For example Person p = (Person)read("file.txt");
Import all classes and run.
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?