Deleting photo saved in folder using room database in android - java

I am taking photo using default camera in mobile. After that saving the photo in specific path in folder which path have been created using File class. In Room database I have storing only the path of image. Now, I added delete method to delete specific photo. I am using following query to delete,
#Query("DELETE FROM record_table WHERE photo_path = photoPath")
int deletePhotoPath(String photoPath);
below methods are used for deleting photo(DataRepository.class)
public void deletePhotoPath(String photoPath){
new deletePhotoPathAsyncTask(RecordDao).execute(photoPath);
}
private class deletePhotoPathAsyncTask extends AsyncTask<String,Void,Void>{
public deletePhotoPathAsyncTask(RecordDao dao) {
RecordDao=dao;
}
#Override
protected Void doInBackground(final String... strings) {
int photoPathDeleted=RecordDao.deletePhotoPath(strings[0]);
Log.d("deletePhotoPath"," Photo Path"+photoPathDeleted+strings[0]);
return null;
}
}
I am calling delete method as below(MyActivity.class),
HolderData.deletePhotoPath(photopathArrayList.get(positionOfCurrentViewPhoto));
In HolderData class I have following method to call delete method from database(HolderData.class),
public static void deletePhotoPath(String photoPath){
Log.d(LOG_TAG, "deletPhotoPath:"+photoPath);
dataRepository.deletePhotoPath(photoPath);
}
But my photo is not getting deleted. Logcats inside delete method works fine.
Doesn't know to delete photo. And How do I reflect the change in my design.
Anybody help me to solve this..Already Surfed a lot but not able to find a solution.

Don`t forget to add the colon when you refer to the argument parameter in your query:
DELETE FROM record_table WHERE photo_path = :photoPath
Before deleting the link from Room extract it, create a File instance programmatically and call "delete" method on that instance:
File file = new File("path to your file");
file.delete();

Related

Vaadin - deleting temporary Files from Upload-Component

hope you can help me. I have a Spring-Boot vaadin-Project with a few Upload-Fields.
Everythings fine. if you click on the send button in the end everything is processed and tempfiles are deleted. Though when you upload a file and leave the site then the temp-directory stays untouched. Is there any way to programatically delete all temporary files when a new instance is called?
When I upload a file on a built-with-vaadin-website and leave the site then, my temp directory gets fuller and fuller. i just want to delete all files which were created in the actual Vaadin Session when starting a new one. Or is there a way to find all files created in a spring session periodically?
I would create a custom VaadinServiceInitListener class (annotated with #Component), I would make a deleting method and in the serviceInit method I would call the deleting method with the uploading path. Something like this:
#Component
public class ApplicationServiceInitListener
implements VaadinServiceInitListener {
#Override
public void serviceInit(ServiceInitEvent event) {
// Delete the upload directory's content
try {
deleteDirectory(new File("[your_upload_directory_path]"));
} catch (IOException e) {
throw new RuntimeException(e);
}
// ...
}
private boolean deleteDirectory(File directoryToBeDeleted) {
File[] allContents = directoryToBeDeleted.listFiles();
if (allContents != null) {
for (File file : allContents) {
deleteDirectory(file);
}
}
return directoryToBeDeleted.delete();
}
}
Service Init Listener Vaadin doc: https://vaadin.com/docs/latest/advanced/service-init-listener
Ps: Of course, you can also use a File Util class, e.g. from common-io.

How do I remove my listener after finishing what I started? (JAVA)

I'm creating a media player in JavaFX. In one of my methods, I've created a way to search for metadata in a Media-file and then display it in ImageView. Works fine first time, but as soon as I want to call it again using another Media object, the image doesn't show up. I'm a bit confused and inexperienced, but I think that perhaps I need to reset/stop the listener before going to next object in line?
So my question is! How do you remove the listener when "image" has been found, what do you type to make it happen?
If you think that there's another reason why my image wont display the second time, please let me know as well.
Thanks on purpose.
private void displayAlbumCover (){
// Will start to show a blank CD
File file = new File("src/sample/images/blank_cd.jpeg");
Image image = new Image(file.toURI().toString());
albumCoverView.setImage(image);
// However if an album cover is found in the meta-data it will be displayed
ObservableMap<String,Object> meta_data=me.getMetadata();
meta_data.addListener((MapChangeListener<String, Object>) ch -> {
if(ch.wasAdded()){
String key=ch.getKey();
Object value=ch.getValueAdded();
switch(key){
case "image":
albumCoverView.setImage((Image)value);
break;
}
}
});
}
ObservableMap has removeListner method. You can keep the listener instance to variable and then remove it later.
private MapChangeListener<String, Object> listener;
private void displayAlbumCover (){
// ...
this.listener = //...
meta_data.addListener(listener);
}
private void removeListener() {
me.getMetadata().removeListener(this.listener);
}
https://docs.oracle.com/javase/8/javafx/api/javafx/collections/ObservableMap.html#removeListener-javafx.collections.MapChangeListener-

1 of the 3 callback weakreferences goes to null in the asynctask (Android)

Intro to me and my application school project
Hi,
iam pretty new with android and for some school project iam building an application where users can configure regions to recieve alerts from. The app need also make it posible to recieve alerts around the current location of the app user.
The app gets its info from a xml feed and sorts the data by the configured regions. The workflow is 1. to get the alerts which are in the configured regions. 2. When gps alerts are enabled the app need to get the location and when it is known it needs to do the first step again but this time the gps region is included. (i need to optimize this proces LATER)
(questions bellow)
intro to my app and problem
I'm using a asynctask in my application to download some xml feed. When the asynctask is ready i need to call 3 places for do something with the result.
1 class saves the result in the local database (alertmanager)
2 fragments (in a tabview) needs to show the results (1 in a map an one in a listview)
Now i use weakreferences for giving the call back "references" to the asynctask. in the onPostExecute() i use theWeakReference.get().updateMethod(result); for updating the class/fragments.
The alertmanager (the class who needs to recieve the updates) also calls a gps manager in the same method where it calls the asynctask to get the gps location. When i comment out (in my case with a if) the line what calls the gps manager the weak reference of the alertmanager will go to null in the asynctask between the constructor (all references are filled) and the doInBackground (the alertmanager reference is null, the other 2 still filled) which results in a crashing app.
When i dont comment out the if the app works fine.....
Alertmanager information
This is the method in the alertmanager who calls the async task. The references are filled on this place.
public void GetAlerts(List<WeakReference<e_Alerts>> callbackReferences, Context context) {
//Update the alerts in the listview and mapview with the local alerts.
List<Alert> localAlerts = internalDc.GetAllAlerts();
try {
for (WeakReference<e_Alerts> callback : callbackReferences) {
callback.get().UpdateAlerts(localAlerts);
}
} catch (Exception e) {
Log.e("AlertManager", e.getMessage());
}
//If connected to the internet then update the local db and the views
if (isConnectingToInternet(context)) {
WeakReference<e_Alerts> wr = new WeakReference<e_Alerts>(this);
callbackReferences.add(wr);
// Update the alerts where no location is needed for so the user has a quick result
externalDc.getAlerts(callbackReferences, areaManager.GetActiveAreas(false));
// If gps region is enabled then find the phones location and update the alerts
if (areaManager.GetGpsArea().IsActive()) {
new GpsManager(this.context, this, callbackReferences);
}
}
}
The GpsManager extends the LocationListener:
public class GpsManager extends Service implements LocationListener {
The listener is implemented by the Alertmanager
// This method is caled by the GPS Manager when the GPS location is changed
#Override
public void OnLocationChanged(Location location, List<WeakReference<e_Alerts>> references) {Area gpsArea = areaManager.GetGpsArea();
gpsArea.SetLocation(location);
areaManager.SaveArea(gpsArea);
externalDc.getAlerts(references, areaManager.GetActiveAreas(true));
}
Asynctask information
This are the asynctask methods:
Asynctask constructor:
Here the list callbackReferences contains 3 weakrefrences and all of them are filled (2x fragment reference 1x alertmanager reference)
public At_allAlerts(List<WeakReference<e_Alerts>> callbackReferences, List<Area> areas) {
this.mCallbackReferences = callbackReferences;
this.mAreas = areas;
}
doInBackground code:
The XmlDownloader: Downloads an xml feed an parses the xml to objects with a library
The AlertConverter: converts the xml object to the object i use in my app
Both classes can work without the asynctask class and don't use the references.
#Override
protected String doInBackground(String... inputUrl) {
Log.i("At_allAlerts", "Asynctask for downloading and parsing mAlerts is started");
try {
//Downloads the alert XMLs from the internet and parses it to xmlAlerts
this.mAlerts = new XmlDownloader().DownloadAlerts(inputUrl);
// Filters the mXml mAlerts so only the mAlerts where the enduser is interessed in will remain
this.mAlerts = filterAlerts(this.mAlerts);
// Converts the remaining xmlAlerts to Alerts;
this.mResult = new AlertConverter().Convert(this.mAlerts);
}catch (Exception e) {
Log.e("At_allAlerts",e.getMessage());
}
return null;
}
The onPostExecute method:
When the programm comes in this method the this.references.get(2) reference (alertmanager reference) = null, the other 2 references are still filed
#Override
protected void onPostExecute(String xml){
for (WeakReference<e_Alerts> reference : activityWeakReferences)
{
reference.get().UpdateAlerts(this.result);
}
}
filterAlerts Method:
private List<Item> filterAlerts(List<Item> alerts) {
List<Item> filteredXmlAlerts = new ArrayList<>();
for (Item alert : alerts)
{
Location alertLocation = new Location("");
alertLocation.setLatitude(alert.getGeometries().get(0).getLocations().get(0).getLat());
alertLocation.setLongitude(alert.getGeometries().get(0).getLocations().get(0).getLng());
for(Area area : this.mAreas)
{
if (area.IsOrganization() && alert.getCountryCode().toLowerCase().equals(area.getOrganizationcode().toLowerCase())){
filteredXmlAlerts.add(alert);
break;
}
else if(!area.IsOrganization() && isAlertInRegion(alertLocation, area)) {
filteredXmlAlerts.add(alert);
break;
}
}
}
return filteredXmlAlerts;
}
My Question(s)
I think Weakreference are the right way for giving references to asynctask is this correct or do i need to give it as an other object? (class or object or whatever?).
Why goes my reference to null? and only one of the 3? and only when i dont use the gps location class? and how to solve this?
I read something about the garbage collector what can be the cause of this problem, is this true and when yes how can i solve this?
It would be fine when the answere are simple to understand since android is pretty new for me.

How to add new database row to Custom Parse class using Android

I uploaded a CSV file to import my database to Parse under a Custom class in Parse.
But for some reason, I can't make a new row via code on Android using the Parse APK.
For example, lets say the my custom class is called "newClass". I have many columns under this class and no new rows can be added. Here is the code I have so far:
//class was populated via CSV file
ParseObject database = new ParseObject("newClass");
database.put(firstColumn, val1);
database.put(secondColumn, val2);
database.put(thirdColumn, val3);
database.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
Toast.makeText(coolActivity.this, "Item added to database", Toast.LENGTH_LONG).show();
}
});
When I check parse.com to see if the item was added, I don't see anything updated and it is the same database as before.

How can i specify a different attachments path under play framework

I'm using play framework now, i already know we can specify the attachments path in application.conf:
# Store path for Blob content
attachments.path=data/attachments
My application have different kinds of pictures, i need to separate those pictures into different directories.
How can i implement my thought ?
Many thanks!
This is my controller code:
public static void uploadAvatar(Blob file){
if(request.isNew){
Long userId = Long.parseLong(session.get(Constants.USER_ID_IN_SESSION));
User user = User.findById(userId);
// Delete old picture
if (user.avatar.getFile() != null) {
user.avatar.getFile().delete();
}
user.avatar = file;
user.avatarFileName = file.getFile().getName();
user.save();
}
Users.settings();
}
I would make a class which extends the current blob.class (http://www.playframework.org/documentation/api/1.2.4/play/db/jpa/Blob.html), and reimplement the getStore() method to read a different property than attachments.path (ie avatar.path).
Good luck!

Categories