Actually It is changing but into Blank!
In my App, i going to get my Images-Path from Database and show them in main activity. this process achieves by selecting thumbnails of images in DialogFragment and sending their Record ID to main Activity withing an Interface for Communicating between Fragment-Activity.
at this point i am going to use an Asynctask inner class to get FilePath of selected Image and Show it to ImageView.
everythings works perfectly EXCEPT that the ImageView does not show it properly and it just show blank!
P.S.: the FilePath is Correct, i used it in onActivityResult on some place in app.
Thank you.
Main Activity code:
public class AnnotateDiagramActivity extends Activity implements Communicator {
#Override
public void respond(String data , int requestCode) {
//Passing Project ID from CPDialogFragment or PLDialogFragment
switch(requestCode) {
case OPEN_PROJECTID:
PROJECTID = Integer.valueOf(data);
loadProject(PROJECTID);
ToastShort(data);
break;
default:
break;
}
}
public class loadMainImage extends AsyncTask<Project,Integer,String>
{
#Override
protected String doInBackground(Project... params) {
return project.GetFilePath();
}
protected void onPostExecute( String result) {
//here is my main issue:
fragmentView.setImageBitmap(new ImageDecoder().decodeFile(new File(project.GetFilePath())));
fragmentView.postInvalidate();
}
}
public void loadProject(int ID)
{
project = new Project();
project= expertDbHelper.getProject(ID);
SharedPreferences openedProject = getSharedPreferences("openedProject", 0);
SharedPreferences.Editor projectEditor = openedProject.edit();
projectEditor.putInt("id",project.GetID());
projectEditor.putString("filePath",project.GetFilePath());
projectEditor.commit();
new loadMainImage().execute(project);
}
}
EDIT For Verifying on Returning Image From File Path:
protected void onPostExecute( String result) {
ImageDecoder imageDecoder = new ImageDecoder();
Bitmap bmp = null;
File file =new File(result);
if(file.isFile()) {
bmp=imageDecoder.decodeFile(file,500);
fragmentView.setImageBitmap(bmp);
fragmentView.postInvalidate();
}
else
{ Log.e("Async Task Is File: " ,String.valueOf(file.isFile()));}
}
I've found that my Image does not set properly due to some criteria that calculated from previous loaded image, so i check my code and find (layout boolean parameter) in my code that needs to be reset.
protected void onPostExecute( String result) {
ImageDecoder imageDecoder = new ImageDecoder();
Bitmap bmp = null;
File file =new File(result);
Log.e("Async Task Result: " ,result);
if(file.isFile()) {
bmp=imageDecoder.decodeFile(file,500);
fragmentView.reset();
fragmentView.recycle();
fragmentView.layout= false;
fragmentView.setImageBitmap(bmp);
}
else
{
Log.e("Async Task Is File: " ,String.valueOf(file.isFile()));
}
}
Related
I'm trying to take a png in my drawable folder, retrieve it, and upload it to my server as a drawable using the Backendless api. However, it does not like this, telling me that it cannot update the object without any properties.
I/System.out: fault!
I/System.out: BackendlessFault{ code: '1001', message: 'Cannot update object without any properties: image' }
The Code:
try {
Event ne = new Event();
ne.title = "title of event";
ne.desc = "short desc";
ne.extDesc = "long desc";
ne.image = getDrawable(R.drawable.palestra);
System.out.println((ne.image != null ? "does" : "does not ") + "work");
Backendless.Persistence.save(ne, new AsyncCallback<Event>() {
#Override
public void handleResponse(Event event) {
System.out.println("successfull!");
}
#Override
public void handleFault(BackendlessFault backendlessFault) {
System.out.println("fault!");
System.out.println(backendlessFault.toString());
}
});
} catch (Exception e) {
System.out.println("caught exception! " + e.toString());
}
The purpose of this is to post an example event to the server so that when I pull the Event, with the properties title, desc, extDesc, and image, I can update my onscreen events accordingly. However, I can't seem to take an image I have locally and upload it as a Drawable.
Thanks for any help.
One solution would be to get the image Bitmap and save it to a file in backendless:
//The outer Backendless call saves the photo in the file and the inner Backendless
//call saves the object to the table and gives ne.image a String reference
//to the file path. the column type should be File Reference, saving the path
//as a String willw ork
Backendless.Files.Android.upload(mBitmap,
Bitmap.CompressFormat.JPEG, //compression type
100, //quality of image
"mImageName", //What you want to call your file, eg timestamp + "app_image"
"/my_images", //The path of the file in Backendless
new AsyncCallback<BackendlessFile>() {
#Override
public void handleResponse(BackendlessFile response) {
ne.title = "title of event";
ne.desc = "short desc";
ne.extDesc = "long desc";
ne.image = (response.getFileURL());
Backendless.Persistence.of(Ids.class).save(ne, new AsyncCallback<Ids>() {
#Override
public void handleResponse(Ids response) {
}//end handleResponse
#Override
public void handleFault(BackendlessFault fault) {
}//end handleFault
});
}//end handleResponse
#Override
public void handleFault(BackendlessFault fault) {
}//end handleFault
});
To retrieve the image fromt he url you have saved it to, you have to use an AsyncTask to get the image from the url.
You could create the following class:
public class MyAsyncTask extends AsyncTask<String, Integer, Bitmap> {
ImageView ivMyImage;
private Bitmap myImage;
public MyAsyncTask(ImageView ivMyImage) {
this.ivMyImage = ivMyImage;
}//end constructor
#Override
protected Bitmap doInBackground(String... urlString) {
try {
URL myImageUrl = new URL(urlString[0]);
myImage = BitmapFactory.decodeStream(myImageUrl.openConnection().getInputStream());
} //end try
catch (Exception e) {
e.printStackTrace();
}//end catch
return myImage;
}//end doInBackground
#Override
protected void onPostExecute(Bitmap bitmap) {
ivMyImage.setImageBitmap(myImage);
}//end onPostExecute
}//end class
And call the Async task wherever you want to use it with the following code:
MyAsyncTask myAsyncTask = new MyAsyncTask(ivMyImage);
myAsyncTask.execute(ne.getImage());//ne.getImage() should retrieve the image url you saved
Hope this helps
I'm currently downloading and save some pictures in my Android app.
Here is the class which do the work :
public class BitmapPersist extends AsyncTask<String, Void, Boolean> {
private ArrayList<String> photosNotDownloaded;
private File pointDir;
private KickstartrGeolocPoint point;
private OnBitmapPersistedListener onBitmapPersistedListener;
public BitmapPersist(ArrayList<String> photosNotDownloaded, File pointDir, KickstartrGeolocPoint point, OnBitmapPersistedListener onBitmapPersistedListener) {
this.photosNotDownloaded=photosNotDownloaded;
this.pointDir=pointDir;
this.point=point;
this.onBitmapPersistedListener=onBitmapPersistedListener;
}
#Override
protected Boolean doInBackground(String... params) {
Bitmap bmp;
FileOutputStream out = null;
for(String url : photosNotDownloaded) {
//download the picture synchronously
bmp = ImageLoader.getInstance().loadImageSync(url);
try {
out = new FileOutputStream(pointDir.getPath() + File.separator + FileUtils.getPointPhotoPrefix(point) + FileUtils.getFileNameFromUrl(url));
bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (Throwable ignore) {
}
}
//send notification to the UI in order to scan again the directory and update the carousel
publishProgress();
}
return true;
}
#Override
protected void onPostExecute(Boolean success) {
if (success)
onBitmapPersistedListener.persistedSuccessfully(this.point, this.pointDir);
else
onBitmapPersistedListener.errorInPersistance();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
onBitmapPersistedListener.onProgress();
}
}
This class take an ArrayList of urls in parameter, and for each photo, it download it and save it.
Each time a photo is persisted, a notification is sent to the view to update a carousel (thanks to publishProgress(); )
The problem is that publishProgress() does not work, and every photos are displayed at the same time when every photos are downloaded.
Here is the call of my asynctask :
private void persistImageforPoint(ArrayList<String> photosNotDownloaded, KickstartrGeolocPoint point, File pointDir) {
// Create a subfolder for each point with its id
if (!pointDir.exists()) {
if (!pointDir.mkdirs()) {
LogWrapper.debug(FileUtils.class, "Failed to create directory");
return;
}
}
//save the file. Asynchronous task --> do not block the UI
new BitmapPersist(photosNotDownloaded, pointDir, point, new OnBitmapPersistedListener() {
#Override
public void persistedSuccessfully(KickstartrGeolocPoint point, File pointDir) {
if(currentPoint!=null) {
File pointDirectory = FileUtils.getPointPhotoDir(getActivity(), currentPoint);
loadCarousel(currentPoint, pointDirectory);
}
}
#Override
public void errorInPersistance() {
LogWrapper.error(getClass(),"Error persisting image");
}
#Override
public void onProgress() {
if(currentPoint!=null) {
final File pointDir = FileUtils.getPointPhotoDir(getActivity(), currentPoint);
loadCarousel(currentPoint, pointDir);
}
}
}).execute();
}
I don't have any errors in my logcat.
Thanks for your help ;)
I am creating an app to fetch XKCD comics (just for learning purpose). I am using JSoup to fetch comic title and url of the image and Universal Image Loader to post the image in ImageView. However I'm facing some problems. Here is my main activity.
public class MainActivity extends Activity {
private static final String TAG = "MyApp";
ImageView xkcdImgIV;
TextView titleTV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
xkcdImgIV=(ImageView) findViewById(R.id.xkcdImgIV);
titleTV=(TextView) findViewById(R.id.titleTV);
try{
new AsyncImg().execute(new String[]{"http://www.xkcd.com/"});
} catch(NullPointerException e){
Log.d(TAG,"Null pointer exception")
}
}
private class AsyncImg extends AsyncTask<String,Void,Void>{
Document doc;
Elements elXkcdTitle;
Elements elXkcdImgUrl;
#Override
protected Void doInBackground(String... arg) {
try {
doc = Jsoup.connect(arg[0]).timeout(0).get();
elXkcdTitle=doc.select("#ctitle");
elXkcdImgUrl=doc.select("#comic img");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
titleTV.setText(elXkcdTitle.first().text());
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init( ImageLoaderConfiguration.createDefault(getApplicationContext() ));
imageLoader.displayImage(elXkcdImgUrl.first().attr("src"), xkcdImgIV);
}
}
}
There is no network activity. I've given the Internet access permission to the app. Moreover Logcat doesn't show any error. Both Jsoup and Universal Image Loader JARS have been included in build path. Feel free to ask for additional info.
I have some problem with AsyncTask in my application.
There is AsyncTask which takes File from sd card and makes operations with it.
It is actually giving me a proper result, but while doing the task there are a black screen and a blocked user interface about 3 seconds that obviously would make a user annoyed. I'm wondering how to get rid of this problem.
So here is the code:
ParseXMLTask.java:
public ParseXMLTask(Context context, IPostParse iPostParse, ProgressBar progressBar) {
this.context = context;
this.iPostParse = iPostParse;
this.progressBar = progressBar;
}
#Override
protected Intent doInBackground(File... params) {
File file = params[0];
Intent pack = new Intent(context, PackActivity.class);
/* some heavy parsing task */
return pack;
}
#Override
protected void onPreExecute() {
progressBar.setIndeterminate(true);
}
#Override
protected void onPostExecute(Intent result) {
iPostParse.postParse(result);
}
LoadingActivity.java:
The executing task code:
private void parseXML() {
File file = new File(PATH + fileName + ".xml");
ParseXMLTask parseTask = new ParseXMLTask(this, this, loadingBar);
parseTask.execute(file);
}
And the implemented method of the interface, nothing special:
public void postParse(Intent result) {
result.putExtra("name", packName);
result.putExtra("author", packAuthor);
result.putExtra("date", packDate);
result.putExtra("file", fileName);
result.putExtra("votes", votes);
startActivity(result);
}
Hope you help me to solve this problem, thanks!
This can happen if you are putting too much data into your Intent's extras.
My application loads images using url. I tried using the library UrlImageViewHelper. It works. But I want to add a spinning progressbar. So i tried modifying a portion for the progressbar.
The problem is that when i tried to run my application, only at some images the progressbar will appear, then disappear when the iamge is already loaded. at some image, it continued to display..Is this the right place to add my progressbar control?
final Runnable completion = new Runnable() {
#Override
public void run() {
assert (Looper.myLooper().equals(Looper.getMainLooper()));
Bitmap bitmap = loader.result;
Drawable usableResult = null;
if (bitmap != null) {
usableResult = new ZombieDrawable(url, mResources, bitmap);
}
if (usableResult == null) {
clog("No usable result, defaulting " + url);
usableResult = defaultDrawable;
mLiveCache.put(url, usableResult);
}
mPendingDownloads.remove(url);
// mLiveCache.put(url, usableResult);
if (callback != null && imageView == null)
callback.onLoaded(null, loader.result, url, false);
int waitingCount = 0;
for (final ImageView iv: downloads) {
// validate the url it is waiting for
final String pendingUrl = mPendingViews.get(iv);
if (!url.equals(pendingUrl)) {
clog("Ignoring out of date request to update view for " + url + " " + pendingUrl + " " + iv);
continue;
}
waitingCount++;
mPendingViews.remove(iv);
if (usableResult != null) {
// System.out.println(String.format("imageView: %dx%d, %dx%d", imageView.getMeasuredWidth(), imageView.getMeasuredHeight(), imageView.getWidth(), imageView.getHeight()));
iv.setImageDrawable(usableResult);
// System.out.println(String.format("imageView: %dx%d, %dx%d", imageView.getMeasuredWidth(), imageView.getMeasuredHeight(), imageView.getWidth(), imageView.getHeight()));
// onLoaded is called with the loader's result (not what is actually used). null indicates failure.
}
if (callback != null && iv == imageView)
callback.onLoaded(iv, loader.result, url, false);
}
clog("Populated: " + waitingCount);
// if(imageView.isShown())
// if(progressBar != null) progressBar.setVisibility(View.GONE);
}
};
if (file.exists()) {
try {
if (checkCacheDuration(file, cacheDurationMs)) {
clog("File Cache hit on: " + url + ". " + (System.currentTimeMillis() - file.lastModified()) + "ms old.");
final AsyncTask<Void, Void, Void> fileloader = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(final Void... params) {
loader.onDownloadComplete(null, null, filename);
return null;
}
#Override
protected void onPostExecute(final Void result) {
completion.run();
}
};
executeTask(fileloader);
return;
}
else {
clog("File cache has expired. Refreshing.");
}
}
catch (final Exception ex) {
}
}
for (UrlDownloader downloader: mDownloaders) {
if (downloader.canDownloadUrl(url)) {
downloader.download(context, url, filename, loader, completion);
return;
}
}
imageView.setImageDrawable(defaultDrawable);
// if(imageView.isShown())
// if(progressBar != null) progressBar.setVisibility(View.GONE);
}
If someone familiar with this library, can you help achieve my objective? Thanks
In this situation I would be inclined to use an ASyncTask rather than Runnable. The ASyncTask was designed specifically for this purpose and contains methods which are run directly on the UI thread (onProgressUpdate(), onPreExecute() and onPostExecute()). These methods are ideal for showing, hiding and updating a progress bar as required.
This tutorial should provide you with a fairly good starting point.
ASyncTask is what you are looking for, whenever there is Resource Fetching or rendering like UI components and images and etc ASYNCTask is the answer but when you are looking for Data Fetching always use Runnable Threads.
class ImageFetch extends AsyncTask {
private final ProgressDialog dialog = new ProgressDialog(this.context);
#Override
protected void onPreExecute() {
this.dialog.setMessage("Fecthing Image");
this.dialog.setTitle("Please Wait");
this.dialog.setIcon(R.drawable."Any Image here");
this.dialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
// Put your Image Fetching code here
}
#Override
protected void onPostExecute(Void aVoid) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
and after that in the Activity code do it like this new ImageFetch().execute();
you are done.