I have a WebView that just displays an image from the external SD-card. This works well, however if the image is overwritten with new data, the WebView does not update the image.
This is even more curious because the WebView is created totally new in the onCreate method of the activity. Here is my code:
#Override
public void onCreate(Bundle savedInstanceState)
{
Log.d(TAG, "Creating Viewer");
super.onCreate(savedInstanceState);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String imagePath = extras.getString("imgFile");
shareImage(Uri.fromFile(new File(imagePath)));
setContentView(R.layout.viewer_test);
WebView viewer = (WebView) findViewById(R.id.imageViewer);
viewer.getSettings().setAllowFileAccess(true);
viewer.getSettings().setBuiltInZoomControls(false);
viewer.getSettings().setLoadWithOverviewMode(true);
viewer.getSettings().setUseWideViewPort(true);
viewer.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
String filename = "file://"+ imagePath;
String html = "<html><head></head><body bgcolor=\"#000000\"><center><img src=\""+ filename + "\"></center></body></html>";
viewer.loadDataWithBaseURL(null, html, "text/html","utf-8", null);
viewer.reload();
}
The image at the path that is saved in imagePath is overwritten by another activity before the path is sent to this activty. The WebView however still shows the old image data.
As you can see I already tried to set the cache mode and I tried to manually reload the WebView, with no luck unfortunately.
I also checked with a file manager and the image on the SD-card is overwritten with new data. I tried to overwrite the file multiple times, but that doesn't work either. Somehow the image data gets cached somewhere or something. How can I avoid this and load the new data every time?
(Obviously creating a new file with a different filename works fine, but I want to replace the old file.)
I'm not too familiar with Webview. but in ordinary websites you can use the querystring to emulate a unique adress, while still loading same image. this is often used on webpages on css files.
example: http://www.webpage.com/image.jpg?cachekey=23456456754
by randomizing the cachekey every time the image loaded, it is treated as a unique image and does not load from cache.
Put a randomized int or string in the end of your filename string
Random r = new Random();
int randInt = r.nextInt(8000000-1000000) + 1000000;
String query = "?cachekey=" + randInt ;
String html = "<html><head></head><body bgcolor=\"#000000\"><center><img src=\""+ filename + query "\"></center></body></html>";
I have not tested this yet. but it's an idea how to solve it.
Related
I need to save page from webview then open it in webview. I found method saveWebArchive and wrote code:
Timestamp tm = new Timestamp(new Date().getTime());
String fileName = String.format("web_file_%d.mht",tm.getTime());
String path = dir.toString() + File.separator + fileName;
view.getWebView().saveWebArchive(path);
then I load page where model.getContentPath() is path from code above
webView.loadUrl("file:///"+model.getContentPath());
and I got page without CSS styels etc...
Can you say how to save and load page which will be looks like original from web?
I'd like to load image which is on SDCARD in folder to imageView of my cell in listView. I've tried different solutions but each of them fails. When I load images normally as it is in every base tutorial everything works. I've observed that, my application slows down when it has to load many images. Images are taken from photo camera of device. I'd like to load each of them asynchronously to avoid UI slow reaction. I've tried to use Thread, Asynctask but each of them throws error: "Only the oryginal thread that created a view hierarchy can touch its views". How to load images to avoid speed problems? SDImageLoader is a class which is possible to get from GITHUB. What I've tried is a standard code but is slows:
In a getView method in ListAdapter:
File imageFile = new File(Options.PATH_TO_FOLDER_PHOTOS_OF_APP + "test.png");
String imageFileString = Options.PATH_TO_FOLDER_PHOTOS_OF_APP + "test.png";
// "test.png" is a test file. Each cell will have different name of file to load.
if(imageFile.exists())
{
Bitmap myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
image.setImageBitmap(myBitmap);
// final SDImageLoader loader = new SDImageLoader(context);
// new SDImageLoader().load(imageFileString, image);
//UrlImageViewHelper.setUrlDrawable(image, url);
}
else
{
final SDImageLoader loader = new SDImageLoader();
Resources resources = context.getResources();
int resurceId;
resurceId = resources.getIdentifier("bad", "drawable",context.getPackageName());
loader.load(imageFileString, image);
image.setImageResource(resurceId);
}
Have you tried to refresh your project after adding an external library to your project? It doesn't matter with the fragment. You send exact context to the List Adapter - which should be fragment.this.getActivity().
I have an application in which I can use the device's camera to take a picture. What I would like to do is to start the ACTION_IMAGE_CAPTURE intent without assigning an EXTRA_OUTPUT, and then move the file that is created in the default location to my own custom location using file.renameTo. My code is something like this:
/* Start camera activity without EXTRA_OUTPUT */
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, _REQUESTCODE_ATTACH_CAMERA);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch(requestCode) {
case _REQUESTCODE_ATTACH_CAMERA:
/* Get path to most recently added image */
final String[] imageColumns = { MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA };
final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
Cursor imageCursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns, null, null, imageOrderBy);
String fullPath = "";
if(imageCursor.moveToFirst()){
fullPath = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
imageCursor.close();
}
File f = Environment.getExternalStorageDirectory();
f = new File(f.getAbsolutePath() + File.separator + "DCIM" + File.separator + MY_APP_NAME;
if(!f.exists()) {
f.mkdirs();
}
/* Create new file based on name of most recently created image */
File oldFile = new File(fullPath);
String newPath = f.getAbsolutePath() + File.separator + oldFile.getName() ;
/* Move file with renameTo */
oldFile.renameTo(new File(newPath));
break;
...
}
}
}
All of this works quite well, however there is one strange thing that is occurring. In my app, I have another button that allows selecting an existing image from the phone's gallery. That code looks like this:
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
activity.startActivityForResult(galleryIntent, _REQUESTCODE_ATTACH_GALLERY);
This also works, but if I take a picture with the camera using the code posted above, and then try to select another image from the gallery, there will be blank "broken link" type items in the gallery that contain no content and are unselectable. These seem to correspond with photos taken and moved using renameTo; if I put in code in onActivityResult to post the filename to LogCat, the name that gets logged is the same as the name of the previously moved file that it corresponds to. Trying to create a File object or in any way access that filename, results in null objects and force closes.
The strange part is that there is no evidence of these "broken link" files in Eclipse DDMS, nor in the phone itself if I use Root Browser, and they disappear if I remount the SD Card.
The whole reason I am moving the images after capturing them with the camera is to avoid filling up the phone's gallery storage with unnecessary images. While these empty "broken link" type files don't appear to be taking up any storage space, they would still be very annoying to an end-user trying to browse through their gallery. Does anyone have any ideas on what is happening here or how to solve this problem?
EDIT:
Here is a photo showing what the gallery looks like with a "broken link" type image displayed. One of these will appear for every photo that is taken using my app, and they will all disappear if I remount the SD Card.
Thanks in part to this SO thread, I have discovered a solution. It actually makes sense that it would behave this way since there is a table kept for media content and so removing something without telling the table would definitely create a "broken link" type scenario.
The ultimate solution is to use contentResolver.delete to remove the reference to the file within the content resolver, but there are two different ways that I have found that will work.
/* Moving with renameTo */
//Use the same exact code as I had before (shortened for brevity) to move the file
oldFile.renameTo(newFile);
//Get URI from contentResolver using file Id from cursor
Uri oldUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media._ID)));
//Delete old file
getContentResolver().delete(oldUri, null, null);
Getting the URI in this way is necessary because it requires a reference to the image in the contentResolver rather than the path to its location in storage. This way might feel dirty to some since you are moving a file and then calling a delete function on that file in order to sort of trick the content resolver into removing the link to the file. If you would rather, you can do it without using renameTo so that the call to delete(...) actually does delete the image.
/* Moving with streams */
//Get streams
InputStream in = new FileInputStream(oldFile);
OutputStream out = new FileOutputStream(newFile);
byte[] buffer = new byte[1024];
int bytesRead = 0;
//Read old file into new file
while((bytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
//Get URI from contentResolver using file Id from cursor
Uri oldUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media._ID)));
//Delete old file
getContentResolver().delete(oldUri, null, null);
The call to contentResolver.delete is the same either way, I just wanted to point out that it will still work if the image has already been removed.
During this I discovered a solution to a problem that I didn't even realize that I had that I will post here as well in case anyone with this same problem comes across this in the future. In order to keep the image as selectable in the device gallery from the new location, you need to let the media scanner know that a change has been made. There are two ways that I found to do this:
/* This is the only way that I know of to handle multiple new files at once. I
really would use this sparingly, however, since it will rescan the entire
SD Card. Not only could this take a long time if the user has a lot of files
on their card, it will also show a notification so it is not exactly a
transparent operation. */
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
/* You *could* do multiple files with this by passing in the path for each one
in the array of Strings, however an instance of this will get called for each
one rather than it doing them all at once. Likewise, your onScanCompleted
(if you choose to include one) will get called once for each file in the list.
So really, while this is much better for a small number of files, if you plan
on scanning a very large amount then the full rescan above would probably be
a better option. */
MediaScannerConnection.scanFile(context, new String[]{ newFilePathAsString }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
//This executes when scanning is completed
}
}
);
I would like some help with saving pictures taken from my camera to a specific folder on the SD card. My camera opens up, takes the photos, and saves them; but it saves them to the standard folder. The code I have so for is:
public class Camera extends Activity {
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
String Path;
private Uri fileUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras=getIntent().getExtras();
Path= extras.getString("Path");
Log.d("camear","path: "+Path);
//File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyCameraApp");
Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
this.startActivity(intent);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
//mediaFile = new File(mediaStorageDir.getPath() + File.separator +"IMG_"+ timeStamp + ".jpg");
//fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
Uri outputFileUri= Uri.fromFile(new File(Path+"/camera/"+timeStamp+".jpg"));// create a file to save the image
intent.putExtra("output", outputFileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
The path is coming from another activity on the application, and it passes its values fine. In the previous activity, it creates the folders that I want to save the pictures into.
I have looked at the following answer, and tried to implement some of the suggestions: How to save images from Camera in Android to specific folder?. One thing I didnt try, was in the last suggestion on the OnActivityResult. Is that the key or is there somthing else I am missing? This page here mentions the ContentResolver The Camera Intent is simply not working, one thing is that both pages look like they want to do the same, but go about it in different ways.
I figured out what I was doing wrong. If you look at the code, I made two mistakes. The first mistake was with my path. I got the correct path from the previous activity, however I did not create a folder path here. This is the code that worked for me:
File Folder=new File(Path);
File picFile= new File(Folder.getPath()+"/"+timeStamp+".jpg");
The first line checks for the folder, the second line creates the file using the path to the folder. I didn't have either part. Without it finding the path, it was just saving were it wanted to.
Another issue that I had was with my Intent call, I used the: MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA. This without any #Overrides apparently acts like the actual camera saving in its folder. I changed this to:
MediaStore.ACTION_IMAGE_CAPTURE, which allows me a little more control.
Another issue that I Was having and figured out, was with the ACTION_IMAGE_CAPTURE, it would take and the close out. But if you implement onActivityResult using the result code returned from the camera application, you can either re-call the camera and make it run again, or you can close it out and go back to another activity. It was not part of the original question, but was an issue I was having.
In my current working code, I pass the reference of an image from a screen that shows some thumbnails. When the thumbnail is selected, the image id is stored and then used in a new activity. Now, when a thumbnail is selected, I want to store the image id and a reference to the associated video file.
When the thumbnail is selected, it opens a new activity that shows the full image with a play button. When the play button is selected, I want it to call a new activity that will play the video based on the reference saved on the thumbnail screen. I have everything working except getting the video to play using the reference. When I hard code the file name in, the video will play.
here's some snippets of my code.
From thumbnail class:
public void onClick(View v) {
Intent fullImage = new Intent(standard_main.this, full_image.class);
Intent playVideo = new Intent(standard_main.this, video.class);
switch(v.getId()){
case R.id.img_standard1:
fullImage.putExtra("Full", R.drawable.img_standard1);
playVideo.putExtra("VideoFile", R.raw.standard); // added to try to reference video for future use
startActivity(fullImage);
break;
From full_image class:
if (x >= leftPlayPoint && x < rightPlayPoint && y >= topPlayPoint && y < bottomPlayPoint){
startActivity(new Intent("com.example.PLAYVIDEO"));
From my video class:
VideoView vd = (VideoView) findViewById(R.id.VideoView);
int vidID = getIntent().getIntExtra("VideoFile",0);
Uri uri = Uri.parse("android.resource://com.example/"+ R.raw.standard);
I want to somehow use vidID to replace R.raw.standard.
If I'm understanding correctly, I cannot use vidID because it is an Int and Uri.parse wants a string. I tried converting the Int to a String using toString() but I suspect that only converted the actual number to a string and did bring in the actual file name. I also tried String.valueOf(vidID).
I'm thinking that Parcelabel might be used somewhere, but I'm not following how to use it. One other option I thought was to store all the video names in an array and somehow use this to dynamically create the file name on the video.java file.
I'll keep searching, but any help is much appreciated.
This is one way to do it. Perhaps there is an easier way, but none that I know of.
Some example code.
int myResourceId = getIntent().getIntExtra("AudioFile", 0);
StringBuilder sb = new StringBuilder();
// get full resource path, e.g. res/raw/audio.mp3
sb.append(getResources().getString(myResourceId));
// delete res folder
sb.delete(0, sb.indexOf("/"));
// delete file extension
sb.delete(sb.indexOf(".mp3"), sb.length());
// insert package at beginning
sb.insert(0, "android.resource://com.example");
Uri uri = Uri.parse(sb.toString());