Picasso fail to load image locally - java

i am try to download a image and save it locally. Everything runs trough i didnt get any exceptions, but the file dont appear in my location
i searched for an solution but didnt find any.
Heres my code:
private void saveImages() {
try{
final File thumbsPath = new File(getExternalFilesDir(null), "thumbs");
if (!thumbsPath.exists())
thumbsPath.mkdirs();
Target target = new Target(){
#Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
new Thread(new Runnable() {
#Override
public void run() {
File file = new File(thumbsPath.getAbsolutePath() + "/file.jpeg"); //folder exists
try {
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, ostream);
ostream.flush();
ostream.close();
} catch (Exception e) {
Log.e("ERROR", e.getMessage());
}
}
}).start();
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
Log.e("ERROR", "");
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
Log.e("ERROR", "");
}
};
Picasso.with(getApplicationContext())
.load(myurltodownloadfrom)
.into(target);
}
catch (Exception e){
Log.e("ERROR",e.getMessage());
}
}

Never store Files that way.
It is all covered here: https://developer.android.com/training/basics/data-storage/files.html

Related

how to show progress bar update for FTP DOWNLOAD in android

I am trying to download an apk file to update my application and apk is placed in ftp server and I am downloading that apk using FTP Client.
Even though I call mProgress.setProgress(percent);
the ProgressBar is not getting updated from the function where I download the apk file by ftp
public class UpdateAppByFTP extends AsyncTask<String,Void,Void> {
private Context context;
CopyStreamAdapter streamListener;
public void setContext(Context mContext){
context = mContext;
}
private ProgressDialog mProgress;
#Override
protected void onPreExecute(){
super.onPreExecute();
mProgress = new ProgressDialog(this.context);
mProgress.setMessage("Downloading new apk .. Please wait...");
mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//mProgress.setIndeterminate(true);
mProgress.show();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mProgress.dismiss(); //Dismiss the above Dialogue
}
#Override
protected Void doInBackground(String... arg0) {
try {
String serverName = arg0[0];
String userName = arg0[1];
String password = arg0[2];
String serverFilePath = arg0[3];
String localFilePath = arg0[4]; if(getFileByFTP(serverName,userName,password,serverFilePath,localFilePath)){
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(localFilePath)), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
context.startActivity(intent);
}else{
//Do nothing could not download
}
String apkLocation="/download/"+"SmartPOS.apk";
Intent intent1 = new Intent(Intent.ACTION_VIEW);
intent1.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() +apkLocation)), "application/vnd.android.package-archive");
intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
context.startActivity(intent1);
} catch (Exception e) {
}
return null;
}
//Below code to download using FTP
public boolean getFileByFTP(String serverName, String userName,
String password, String serverFilePath, String localFilePath)
throws Exception {
FTPClient ftp = new FTPClient();
try {
ftp.connect(serverName);
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return false;
}
} catch (IOException e) {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException f) {
throw e;
}
}
throw e;
} catch (Exception e) {
throw e;
}
try {
if (!ftp.login(userName, password)) {
ftp.logout();
}
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
final int lenghtOfFile =(int)getFileSize(ftp,serverFilePath);
OutputStream output = new FileOutputStream(localFilePath);
CountingOutputStream cos = new CountingOutputStream(output) {
protected void beforeWrite(int n) {
super.beforeWrite(n);
int percent = Math.round((getCount() * 100) / lenghtOfFile);
Log.d("FTP_DOWNLOAD", "bytesTransferred /downloaded"+percent);
System.err.println("Downloaded "+getCount() + "/" + percent);
mProgress.setProgress(percent);
}
};
ftp.setBufferSize(2024*2048);//To increase the download speed
ftp.retrieveFile(serverFilePath, output);
output.close();
ftp.noop(); // check that control connection is working OK
ftp.logout();
return true;
}
catch (FTPConnectionClosedException e) {
Log.d("FTP_DOWNLOAD", "ERROR FTPConnectionClosedException:"+e.toString());
throw e;
} catch (IOException e) {
Log.d("FTP_DOWNLOAD", "ERROR IOException:"+e.toString());
throw e;
} catch (Exception e) {
Log.d("FTP_DOWNLOAD", "ERROR Exception:"+e.toString());
throw e;
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException f) {
throw f;
}
}
}
}
private static long getFileSize(FTPClient ftp, String filePath) throws Exception {
long fileSize = 0;
FTPFile[] files = ftp.listFiles(filePath);
if (files.length == 1 && files[0].isFile()) {
fileSize = files[0].getSize();
}
Log.d("FTP_DOWNLOAD", "File size = " + fileSize);
return fileSize;
}
}
Basically, the UI Does not get updated, also I am not sure whether the CountingOutputStream is the correct method to find the downloaded size of the file.
Thanks in advance.
I changed this retrieveFile section of the code and it is fine now
ftp.retrieveFile(serverFilePath, cos);
I tried your solution, it worked fine for me for file sizes up to 30 MB from FTP, going above, the download crashed every time. So I assumed the getCount() method as it is being called every time would result in some issue.
I even tried running the getCount() on separate thread, but still no use.
So finally I changed percent (for progress) variable to fraction of FileSize of local/FTP file size. So in above case it will be:
int percent = Math.round(output.length() * 100) / lenghtOfFile);
Works fine.

how to fix saved image with Zero byte android java

I have an Image in web server and load it to Image View using Picasso perfectly then save it to a folder in internal storage memory every thing is OK but the problem is the saved image size is 0 byte
here is my code
File newDir=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"km");
if (!newDir.exists()) {
if (!newDir.mkdirs()) {
Toast.makeText(this, "can not create directory", Toast.LENGTH_SHORT).show();
}
}
Picasso.with(this).load("http://192.168.1.101/cima/1.jpg").into(img);
File file = new File(new File("/storage/sdcard0/Download/km/"), "1.jpg");
img.buildDrawingCache();
Bitmap bmap = img.getDrawingCache();
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
bmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
any help for this issue ??
Try to below code
Picasso.with(getActivity())
.load(url)
.into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
try {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/yourDirectory");
if (!myDir.exists()) {
myDir.mkdirs();
}
String name = new Date().toString() + ".jpg";
myDir = new File(myDir, name);
FileOutputStream out = new FileOutputStream(myDir);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch(Exception e){
// some action
}
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
);

Unable to open an image from activity folder?

I am able to save an image from camera in my package folder of my app but this is what happens, when I try to open the image from that folder, I get the message: "Can't open".
I have tried moving the image to pictures folder and it opened just fine. So, what could be the problem. This is what I tried so far.
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mFile = new File(getActivity().getExternalFilesDir(null), "pic.jpg");
}
private static class ImageSaver implements Runnable {
/**
* The JPEG image
*/
private final Image mImage;
/**
* The file we save the image into.
*/
private final File mFile;
ImageSaver(Image image, File file) {
mImage = image;
mFile = file;
}
#Override
public void run() {
ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
FileOutputStream output = null;
try {
output = new FileOutputStream(mFile);
output.write(bytes);
} catch (IOException e) {
e.printStackTrace();
} finally {
mImage.close();
if (null != output) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
/**
*/
Reading the image
public class SingleMediaScanner implements MediaScannerConnection.MediaScannerConnectionClient {
private MediaScannerConnection mMs;
private File mFile;
public SingleMediaScanner(Context context, File f) {
mFile = f;
mMs = new MediaScannerConnection(context, this);
mMs.connect();
}
public void onMediaScannerConnected() {
mMs.scanFile(mFile.getAbsolutePath(), null);
}
public void onScanCompleted(String path, Uri uri) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
mMs.disconnect();
}
}
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new SingleMediaScanner(getActivity(), allFiles[0]);
}
});
Manifest
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.FLASHLIGHT"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-feature android:name="android.hardware.camera2.full"/>
If you want to save on internal folder
public File getImage(Context context) {
try {
String nameFile = "sample.jpg";
File folder = context.getFilesDir();
File fileCreated = new File(folder, nameFile);
return fileCreated;
} catch (Exception ex) {
throw ex;
}
}
And then you pass this file to your ImageSaver

Android Picasso: Method call should happen from the main thread

I am trying to get info from a server, including photos. I have created a class called ServerManager, which allows me to download the desired information. However, I cannot download images with Picasso because I get a java.lang.IllegalStateException: Method call should happen from the main thread..
This is what I am doing in ServerManager:
// Check if the photo is already downloaded
if (!checkInternalPhoto(member)) {
final String outputURL = context.getFilesDir().getAbsolutePath() + "/" + member.photoPath;
String photoURL = rootURL + "photos/" + member.photoPath;
Picasso.with(context)
.load(photoURL)
.into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
File file = new File(outputURL);
try {
file.createNewFile();
FileOutputStream outputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG,100,outputStream);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
Log.e("IOException",e.getLocalizedMessage());
}
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
What can I do?
Edit: I tried to use the code in my MainActivity and I am getting the same error message...
public void downloadPhotos(List<Member> memberList){
String rootInURL = serverManager.getRootURL();
String rootOutURL = serverManager.getOutputURL();
for(int i = 0; i < memberList.size(); i++){
if(!serverManager.checkInternalPhoto(memberList.get(i))){
final String outputURL = rootOutURL + memberList.get(i).photoPath;
String photoURL = rootInURL + "photos/" + memberList.get(i).photoPath;
Picasso.with(this)
.load(photoURL)
.into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
File file = new File(outputURL);
try{
file.createNewFile();
FileOutputStream outputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG,100,outputStream);
outputStream.flush();
outputStream.close();
Toast.makeText(context, "YEpa: " ,Toast.LENGTH_LONG).show();
} catch (IOException e){
Toast.makeText(context, "Error: " + e.toString(),Toast.LENGTH_LONG).show();
}
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
}
}
Try this and your error should disappear. This problem always happens when you use it in Unit Android test
kotlin code
Handler(Looper.getMainLooper()).post {
}
java code
new Handler(Looper.getMainLooper()).post(() -> {
});
You can't update an ui element from a different thread than the one which created that ui element. On Android that almost always means the main thread.
What you need to do is send back the photoUrl String to your activity or fragment on the main thread. The traditional way of doing it is by using a Handler. You can read about this more here: https://developer.android.com/training/multiple-threads/communicate-ui.html

Parse file saveing error,""Unable to encode an unsaved parsefile"

I am getting error while uploading image on Parse.Please Help me about this. I tried some Stack overflow question but its nothing, So please help me,Thank in advance.
When i press Submit button then i am getting following error.
error is
java.lag.illegalStateException: Unable to encode an unsaved parsefile
and my code is
bitmapLogo=BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapLogo.compress(Bitmap.CompressFormat.PNG,0, stream);
byte[] image = stream.toByteArray();
String filename=etUser.getText().toString()+".png";
ParseFile file = new ParseFile(filename, image);
System.out.println("PARSE FILE NAME : "+picturePath);
file.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e!=null){
btSignup.setText(e.getMessage());
}
}
},new ProgressCallback() {
#Override
public void done(Integer integer) {
btSignup.setText(""+integer);
}
});
String spin= String.valueOf(spinBCat.getSelectedItem());
ParseUser user = new ParseUser();
user.setUsername(etUser.getText().toString());
user.setPassword(etPass.getText().toString());
user.setEmail(etEmail.getText().toString());
user.put("logoname",etUser.getText().toString());
user.put("blogo",file);
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
Toast.makeText(AddBusinessActivity.this,"You are Successfully Signed Up",Toast.LENGTH_LONG).show();
signUpSucess();
} else {
Toast.makeText(AddBusinessActivity.this,""+e.getMessage(),Toast.LENGTH_LONG).show();
// Sign up didn't succeed. Look at the ParseException
// to figure out what went wrong
}
}
});
Finally I solve this answer. Just add code in ProgressCallback method
Code is
bitmapLogo=BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapLogo.compress(Bitmap.CompressFormat.PNG,0, stream);
byte[] image = stream.toByteArray();
String filename=etUser.getText().toString()+".png";
ParseFile file = new ParseFile(filename, image);
System.out.println("PARSE FILE NAME : "+picturePath);
file.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e!=null){
btSignup.setText(e.getMessage());
}
}
},new ProgressCallback() {
#Override
public void done(Integer integer) {
String spin= String.valueOf(spinBCat.getSelectedItem());
ParseUser user = new ParseUser();
user.setUsername(etUser.getText().toString());
user.setPassword(etPass.getText().toString());
user.setEmail(etEmail.getText().toString());
user.put("logoname",etUser.getText().toString());
user.put("blogo",file);
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
Toast.makeText(AddBusinessActivity.this,"You are Successfully Signed Up",Toast.LENGTH_LONG).show();
signUpSucess();
} else {
Toast.makeText(AddBusinessActivity.this,""+e.getMessage(),Toast.LENGTH_LONG).show();
// Sign up didn't succeed. Look at the ParseException
// to figure out what went wrong
}
}
});
}
});

Categories