hello i'm trying to save pictures taken from url on my application, but when i try to access the memory to place the data, an error comes out
unable to decode stream java.io.FileNotFoundException /storage/emulated/0 open failed:ENOENT(No such file or directory)
this is my DownloadManager Class
public static ArrayList<String> urls = new ArrayList<String>();
public static OnDownloadCompleteListener downloadCompleteListener;
public static void copyFile(String sourceFile, String destinationFile) {
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = new FileInputStream(sourceFile);
outputStream = new FileOutputStream(destinationFile);
byte[] buffer = new byte[G.DOWNLOAD_BUFFER_SIZE];
int len;
while ((len = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.flush();
outputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void initialize() {
downloadCompleteListener = new OnDownloadCompleteListener() {
#Override
public void onDownloadComplete(String url, String localPath) {
Log.i("LOG", "Image Download Complete, Original URL: " + url + ", Save Path: " + localPath);
String newPath = localPath.replace("/temp/", "/final/");
copyFile(localPath, newPath);
String filename = HelperString.getFileName(localPath);
new File(localPath).delete();
Set<ImageView> imageViews = AdapterSerials.imageMap.keySet();
for (ImageView imageView: imageViews) {
if (AdapterSerials.imageMap.get(imageView).equals(filename)) {
if (imageView != null) {
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 8;
Bitmap bitmap = BitmapFactory.decodeFile(newPath, options);
imageView.setImageBitmap(bitmap);
}
}
}
}
};
}
public static void addToDownloadList(String url, ImageView imgLogo) {
String filename = HelperString.getFileName(url);
AdapterSerials.imageMap.put(imgLogo, filename);
if (urls.contains(url)) {
return;
}
if (new File(G.DIR_FINAL + "/" + filename).exists()) {
return;
}
urls.add(url);
DownloadRequest downloadRequest = new DownloadRequest()
.downloadPath("http://87.236.215.180/mazi/" + url)
.filepath(G.DIR_TEMP + "/" + filename)
.listener(downloadCompleteListener)
.download();
}
this is my DownloadRequest Class :
public class DownloadRequest {
private int downloadedSize;
private int totalSize;
private int percent;
public int getDownloadedSize() {
return downloadedSize;
}
public int getTotalSize() {
return totalSize;
}
public int getPercent() {
return percent;
}
public DownloadRequest download() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL(downloadPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
totalSize = connection.getContentLength();
File file = new File(filepath);
if (file.exists()) {
file.delete();
}
FileOutputStream outputStream = new FileOutputStream(filepath);
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[G.DOWNLOAD_BUFFER_SIZE];
int len = 0;
while ((len = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
downloadedSize += len;
percent = (int) (100.0f * (float) downloadedSize / totalSize);
if (percent == 100 && listener != null) {
G.HANDLER.post(new Runnable() {
#Override
public void run() {
listener.onDownloadComplete(downloadPath, filepath);
}
});
}
if (simulate) {
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
outputStream.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
return this;
}
private String downloadPath;
private String filepath;
private OnDownloadCompleteListener listener;
private boolean simulate;
public DownloadRequest downloadPath(String value) {
downloadPath = value;
return this;
}
public DownloadRequest filepath(String value) {
filepath = value;
return this;
}
public DownloadRequest listener(OnDownloadCompleteListener value) {
listener = value;
return this;
}
public DownloadRequest simulate(boolean value) {
simulate = value;
return this;
}
And this is my G class :
public class G extends Application {
public static Context context;
public static final String SDCARD = Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String DIR_APP = SDCARD + "/serial";
public static final String DIR_CACHE = DIR_APP + "/cache";
public static LayoutInflater inflater;
public static final Handler HANDLER = new Handler();
public static Activity currentActivity;
public static StructSerials selectedSerials;
public static StructFavSerials selectedFavSerials;
public static ArrayList<StructComment> rates = new ArrayList<StructComment>();
public static final int DOWNLOAD_BUFFER_SIZE = 8 * 1024;
public static final String DIR_FINAL = DIR_APP + "/final";
public static final String DIR_TEMP = DIR_APP + "/temp";
public static String android_id;
public static SharedPreferences preferences;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
preferences = PreferenceManager.getDefaultSharedPreferences(context);
initImageLoader(getApplicationContext());
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
android_id = Secure.getString(context.getContentResolver(),
Secure.ANDROID_ID);
new File(DIR_APP).mkdirs();
new File(DIR_CACHE).mkdirs();
new File(DIR_TEMP).mkdirs();
new File(DIR_FINAL).mkdirs();
DownloadManager.initialize();
}
remember add this permission into your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Related
This question already has answers here:
How to download and save an image in Android
(10 answers)
Closed 3 years ago.
I want to download an image from url. if the url does not have an image format at the end of the link? Example of url:
https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=1937530436393797&height=200&width=200&ext=1579152762&hash=AeQEq164H_oXIMjx
Try this code :
Create LocalImageSaver.java :
public class LocalImageSaver extends AsyncTask<Void, String, Boolean> {
private final SaveCompletionInterface saveCompletionInterface;
private final String originalImageUrl;
private final Context context;
private String savedImagePath;
private String fUrl;
public LocalImageSaver(Context context, String originalImageUrl, SaveCompletionInterface saveCompletionInterface) {
this.context = context;
this.saveCompletionInterface = saveCompletionInterface;
this.originalImageUrl = originalImageUrl;
}
/**
* Downloading file in background thread
*/
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
protected Boolean doInBackground(Void... f_url) {
this.fUrl = originalImageUrl;
FileOutputStream output = null;
InputStream is = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(fUrl);
HttpContext context = new BasicHttpContext();
HttpResponse response = client.execute(get, context);
is = response.getEntity().getContent();
int status = response.getStatusLine().getStatusCode();
if (status == 200 && is != null) {
String imageNameToSave;
String extension = originalImageUrl.substring(originalImageUrl.lastIndexOf(".") + 1); // Without dot jpg, png
if (extension.contains("mp4")) {
extension = "mp4";
}
String fileName = "";//originalImageUrl.substring(originalImageUrl.lastIndexOf("/") + 1); // Without dot jpg, png
fileName = "05Media_" + Calendar.getInstance().getTimeInMillis() + "." + extension;
imageNameToSave = fileName;
Uri savedImagePathUri = CommonImageUtil.createImageFile(imageNameToSave);
savedImagePath = savedImagePathUri.getPath();
// Output stream to write file
output = new FileOutputStream(savedImagePathUri.getPath());
int read = 0;
byte[] buffer = new byte[32768];
while ((read = is.read(buffer)) > 0) {
output.write(buffer, 0, read);
}
// flushing output
output.flush();
// closing streams
output.close();
is.close();
return true;
}
} catch (ClientProtocolException e) {
Lg.printStackTrace(e);
} catch (IOException e) {
Lg.printStackTrace(e);
} catch (Exception e) {
Lg.printStackTrace(e);
} finally {
// flushing output
try {
if (output != null) {
output.flush();
}
} catch (IOException e) {
Lg.printStackTrace(e);
}
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
Lg.printStackTrace(e);
}
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
Lg.printStackTrace(e);
}
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
saveCompletionInterface.onSaved(result, savedImagePath);
}
public interface SaveCompletionInterface {
public void onSaved(boolean result, String imageNameToSave);
}
}
and call this :
LocalImageSaver localImageSaver = new LocalImageSaver(getActivity(), url, new LocalImageSaver.SaveCompletionInterface() {
#Override
public void onSaved(boolean result, String savedImagePath) {
if (result) {
//showToast(getActivity(), (R.string.image_save_succesfull));
// refresh gallery
try {
MediaScannerConnection.scanFile(getActivity(), new String[]{savedImagePath}, null, new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
}
});
} catch (Exception e) {
}
} else {
//showToast(getActivity(), (R.string.error_saving_image));
}
}
});
localImageSaver.execute();
I have an android application which downloads and play mp3 files. But I want to encrypt audio files while downloading and then decrypt to play it. I have already checked everywhere in the internet but did not find any solution. Could anyone please help me how to encrypt audio files while downloading and then decrypt during playing
Here is my code to download the files
private void download() {
if (Constant.arrayList_play.size() > 0) {
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Myapp/cache");
if (!root.exists()) {
root.mkdirs();
}
File file = new File(root, Constant.arrayList_play.get(viewpager.getCurrentItem()).getMp3Name() + ".mp3");
if (!file.exists()) {
String url = Constant.arrayList_play.get(viewpager.getCurrentItem()).getMp3Url();
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription(getResources().getString(R.string.downloading) + " - " + Constant.arrayList_play.get(viewpager.getCurrentItem()).getMp3Name());
request.setTitle(Constant.arrayList_play.get(viewpager.getCurrentItem()).getMp3Name());
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationUri(Uri.parse("file://" + Environment.getExternalStorageDirectory().getAbsolutePath() + "/Myapp/cache/" + Constant.arrayList_play.get(viewpager.getCurrentItem()).getMp3Name() + ".mp3"));
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
new AsyncTask<String, String, String>() {
#Override
protected String doInBackground(String... strings) {
String json = JsonUtils.getJSONString(Constant.URL_DOWNLOAD_COUNT + Constant.arrayList_play.get(viewpager.getCurrentItem()).getId());
Log.e("aaa - ", json);
return null;
}
}.execute();
Toast.makeText(MainActivity.this, getResources().getString(R.string.downloading), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, getResources().getString(R.string.already_download), Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, getResources().getString(R.string.no_song_selected), Toast.LENGTH_SHORT).show();
}
}
So could you please help me with a code.
I have found a solution to my question and have been using it in my app since many days without any problem so I think it is good to answer my own question also as many users had asked for solution in comments. So just follow the below codes-
//Downloading and encrypting the audio
AesCipherDataSink encryptingDataSink = new AesCipherDataSink(
Util.getUtf8Bytes("4J95qN8RxBP8hTpk"),
new DataSink() {
private FileOutputStream fileOutputStream;
#Override
public void open(DataSpec dataSpec) throws IOException {
fileOutputStream = new FileOutputStream(file);
}
#Override
public void write(byte[] buffer, int offset, int length) throws IOException {
fileOutputStream.write(buffer, offset, length);
}
#Override
public void close() throws IOException {
fileOutputStream.close();
}
});
// Push the data through the sink, and close everything.
encryptingDataSink.open(new DataSpec(Uri.fromFile(file)));
URL downloadURL = new URL(strings[0]);
HttpURLConnection connection = (HttpURLConnection) downloadURL.openConnection();
connection.setChunkedStreamingMode(0);
connection.setDoInput(true);
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server error";
}
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[1024];
int newLength;
while ((newLength = inputStream.read(buffer)) > 0) {
encryptingDataSink.write(buffer, 0, newLength);
}
encryptingDataSink.close();
inputStream.close();
//decrypting and playing the audio
DataSource.Factory factory =
new CustomDataSourceFactory(
context,
new OkHttpDataSourceFactory(new OkHttpClient(), Util.getUserAgent(context,
context.getResources().getString(R.string.app_name)))
);
MediaSource videoSource =
new ProgressiveMediaSource.Factory(factory)
.createMediaSource(Uri.parse(tempFile.getAbsolutePath()));
exoPlayer.addMediaSource(videoSource);
//CustomDataSourceFactoryClass
public class CustomDataSourceFactory implements DataSource.Factory {
private final Context context;
private final DataSource.Factory baseDataSourceFactory;
public CustomDataSourceFactory(Context context, DataSource.Factory baseDataSourceFactory) {
this.context = context.getApplicationContext();
this.baseDataSourceFactory = baseDataSourceFactory;
}
#Override
public DataSource createDataSource() {
return new CryptedDefaultDataSource(context, baseDataSourceFactory.createDataSource());
}
}
//CryptedDafaultDataSource
public class CryptedDefaultDataSource implements DataSource {
private final List<TransferListener> transferListeners;
private final DataSource baseDataSource;
private #Nullable
DataSource fileDataSource,aesCipherDataSource,dataSource;
private Context context;
CryptedDefaultDataSource(Context context, DataSource baseDataSource) {
this.context=context;
this.baseDataSource = Assertions.checkNotNull(baseDataSource);
transferListeners = new ArrayList<>();
}
#Override
public void addTransferListener(TransferListener transferListener) {
baseDataSource.addTransferListener(transferListener);
transferListeners.add(transferListener);
maybeAddListenerToDataSource(fileDataSource, transferListener);
maybeAddListenerToDataSource(aesCipherDataSource, transferListener);
}
#Override
public long open(DataSpec dataSpec) throws IOException {
Assertions.checkState(dataSource == null);
if (Util.isLocalFileUri(dataSpec.uri)) {
dataSource = getCryptedDataSource(getFileDataSource());
} else {
dataSource = getCryptedDataSource(baseDataSource);
}
return dataSource.open(dataSpec);
}
#Override
public int read(byte[] buffer, int offset, int readLength) throws IOException {
return Assertions.checkNotNull(dataSource).read(buffer, offset, readLength);
}
#Nullable
#Override
public Uri getUri() {
return dataSource == null ? null : dataSource.getUri();
}
#Override
public Map<String, List<String>> getResponseHeaders() {
return dataSource == null
? DataSource.super.getResponseHeaders()
: dataSource.getResponseHeaders();
}
#Override
public void close() throws IOException {
if (dataSource != null) {
try {
dataSource.close();
} finally {
dataSource = null;
}
}
}
private DataSource getFileDataSource() {
if (fileDataSource == null) {
fileDataSource = new FileDataSource();
addListenersToDataSource(fileDataSource);
}
return fileDataSource;
}
private DataSource getCryptedDataSource(DataSource upstreamDataSource) {
if (aesCipherDataSource == null) {
aesCipherDataSource = new AesCipherDataSource("4J95qN8RxBP8hTpk".getBytes(),upstreamDataSource);
addListenersToDataSource(aesCipherDataSource);
}
return aesCipherDataSource;
}
private void addListenersToDataSource(DataSource dataSource) {
for (int i = 0; i < transferListeners.size(); i++) {
dataSource.addTransferListener(transferListeners.get(i));
}
}
private void maybeAddListenerToDataSource(
#Nullable DataSource dataSource, TransferListener listener) {
if (dataSource != null) {
dataSource.addTransferListener(listener);
}
}
}
I have created a ImageLoading class which downloads and saves data to local storage. I am also calling it from multiple activities. After saving I need to update collection of class from which the instance of asyncTask is created. I don't want to use if statements in task to handle this and I don't want to inherit this task to other activities. Please Suggest me how to do this. I am sharing my code here.
public class LoadImageTask extends AsyncTask<Void, Void, Bitmap> {
private String url;
private ImageView imageView;
private long ID;
private Context context;
private SQLiteHandler sqLiteHandler;
private String imageType;
private int position;
public LoadImageTask(String url, ImageView imageView, long ID, Context context, String imageType, int position) {
this.url = url;
this.imageView = imageView;
this.ID = ID;
this.context = context;
this.imageType = imageType;
this.position = position;
sqLiteHandler = new SQLiteHandler(context);
}
String getRandomString(int length)
{
String data = "";
Random rand = new Random();
for (int i = 1 ; i <= length ; i++) {
int n = rand.nextInt(26) + 97;
data += String.valueOf((char)n);
}
return data;
}
private File getOutputMediaFile(){
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ context.getPackageName()
+ "/Files");
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmssSSS").format(new Date());
timeStamp = String.format("%s_%s", timeStamp, getRandomString(10));
File mediaFile;
String mImageName="Image_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d("Error:","Error creating media file, check storage permissions: ");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
ImageDownload imageDownload = new ImageDownload(ID,pictureFile.getAbsolutePath());
if(imageType.equals(Constants.ImageType.PROFILE)) {
sqLiteHandler.UpdateUserImagePath(imageDownload,Constants.ImageType.PROFILE);
}
else if(imageType.equals(Constants.ImageType.BANNER)) {
sqLiteHandler.UpdateUserImagePath(imageDownload,Constants.ImageType.BANNER);
}
else if(imageType.equals(Constants.ImageType.SUBJECT)) {
if(sqLiteHandler.UpdateUserImagePath(imageDownload,Constants.ImageType.SUBJECT)){
((MainActivity) context).subjectsItems.get(position).Image = imageDownload.ImagePath;
//((MainActivity) context).subjectsItems.get(position).Image = imageDownload.ImagePath;
//((MessageList) context).messageDataItems.get(position).SubjectImage = imageDownload.ImagePath;
}
}
} catch (FileNotFoundException e) {
Log.d("Error:", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("Error:", "Error accessing file: " + e.getMessage());
}
}
#Override
protected Bitmap doInBackground(Void... params) {
try {
URL urlConnection = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
Drawable d = new BitmapDrawable(imageView.getResources(), result);
imageView.setBackground(d);
storeImage(result);
//imageView.setImageBitmap(result);
}
}
Simply just do it like this :
((AppCompatActivity) context).subjectsItems.get(position).Image = imageDownload.ImagePath;
I'm trying to take a screenshot before I perform an action in Android using espresso.
protected T performAction(ViewAction viewAction) {
ViewAction screenShotAction = new ScreenShotAction();
viewInteraction.perform(screenShotAction);
viewInteraction.perform(viewAction);
return returnGeneric();
}
For example if in my test I perform a click() then I would take a screenshot of the device before I performed the click().
This is the code for taking the screenshot in the ScreenShotAction class
#Override
public void perform(UiController uiController, View view) {
View rootView = view.getRootView();
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)) {
File picDir = new File(Environment.getExternalStorageDirectory() + "app_" + "test");
if (!picDir.exists()) {
picDir.mkdir();
}
rootView.setDrawingCacheEnabled(true);
rootView.buildDrawingCache(true);
Bitmap bitmap = rootView.getDrawingCache();
String fileName = "test.jpg";
File picFile = new File(picDir + "/" + fileName);
try {
picFile.createNewFile();
FileOutputStream picOut = new FileOutputStream(picFile);
bitmap = Bitmap.createBitmap(rootView.getWidth(), rootView.getHeight(), Bitmap.Config.ARGB_8888);
boolean saved = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, picOut);
if (saved) {
// good
} else {
// error
throw new Exception("Image not saved");
}
picOut.flush();
picOut.close();
} catch (Exception e) {
e.printStackTrace();
}
rootView.destroyDrawingCache();
}
}
I do not see any image files in the phone's Pictures directory or any other directory. I believe the screenshot method is solid but am unsure if I am calling the method correctly.
Is viewInteraction.perform(screenShotAction) the corret way to call my custom view action?
Please help and thank you in advance.
You can do the following:
public class CaptureImage {
#SuppressWarnings("unused")
private static final String TAG = CaptureImage.class.getSimpleName();
private static final String NAME_SEPARATOR = "_";
private static final String EXTENSION = ".png";
private static final Object LOCK = new Object();
private static boolean outputNeedsClear = true;
private static final Pattern NAME_VALIDATION = Pattern.compile("[a-zA-Z0-9_-]+");
public static void takeScreenshot(View currentView, String className,
String methodName, #Nullable String prefix) {
methodName = methodName.replaceAll("[\\[\\](){}]", "");
if (!NAME_VALIDATION.matcher(methodName).matches()) {
throw new IllegalArgumentException(
"Name must match " + NAME_VALIDATION.pattern() +
" and " + methodName + " was received.");
}
Context context = InstrumentationRegistry.getTargetContext();
MyRunnable myRunnable = new MyRunnable(context, currentView, className, methodName, prefix);
Activity activity =
((Application)context.getApplicationContext()).getCurrentActivity();
activity.runOnUiThread(myRunnable);
}
private static class MyRunnable implements Runnable {
private View mView;
private Context mContext;
private String mClassName;
private String mMethodName;
private String mPrefix;
MyRunnable(Context context, View view, String className, String methodName, String prefix) {
mContext = context;
mView = view;
mClassName = className;
mMethodName = methodName;
mPrefix = prefix;
}
#TargetApi(VERSION_CODES.JELLY_BEAN_MR2)
public void run() {
UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
if (uiAutomation == null) {
return;
}
OutputStream out = null;
Bitmap bitmap = null;
try {
String timestamp = new SimpleDateFormat("MM_dd_HH_mm_ss", Locale.ENGLISH)
.format(new Date());
File screenshotDirectory = getScreenshotFolder();
int statusBarHeight = getStatusBarHeightOnDevice();
bitmap = uiAutomation.takeScreenshot();
Bitmap screenshot = Bitmap.createBitmap(bitmap, 0, statusBarHeight,
mView.getWidth(), mView.getHeight() - statusBarHeight);
String screenshotName = mMethodName + NAME_SEPARATOR +
(mPrefix != null ? (mPrefix + NAME_SEPARATOR) : "") +
timestamp + EXTENSION;
Log.d("YOUR_TAG", "Screenshot name: " + screenshotName);
File imageFile = new File(screenshotDirectory, screenshotName);
out = new FileOutputStream(imageFile);
screenshot.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
} catch (Throwable t) {
Log.e("YOUR_LOG", "Unable to capture screenshot.", t);
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception ignored) {
}
if (bitmap != null) {
bitmap.recycle();
}
}
}
private int getStatusBarHeightOnDevice() {
int _StatusBarHeight = 0;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
mView.setDrawingCacheEnabled(true);
Bitmap screenShot = Bitmap.createBitmap(mView.getDrawingCache());
mView.setDrawingCacheEnabled(false);
if (screenShot != null) {
int StatusColor = screenShot.getPixel(0, 0);
for (int y = 1; y < (screenShot.getHeight() / 4); y++) {
if (screenShot.getPixel(0, y) != StatusColor) {
_StatusBarHeight = y - 1;
break;
}
}
}
if (_StatusBarHeight == 0) {
_StatusBarHeight = 50; // Set a default in case we don't find a difference
}
Log.d("YOUR_TAG", "Status Bar was measure at "
+ _StatusBarHeight + " pixels");
return _StatusBarHeight;
}
private File getScreenshotFolder() throws IllegalAccessException {
File screenshotsDir;
if (Build.VERSION.SDK_INT >= 21) {
// Use external storage.
screenshotsDir = new File(getExternalStorageDirectory(),
"screenshots");
} else {
// Use internal storage.
screenshotsDir = new File(mContext.getApplicationContext().getFilesDir(),
"screenshots");
}
synchronized (LOCK) {
if (outputNeedsClear) {
deletePath(screenshotsDir);
outputNeedsClear = false;
}
}
File dirClass = new File(screenshotsDir, mClassName);
File dirMethod = new File(dirClass, mMethodName);
createDir(dirMethod);
return dirMethod;
}
private void createDir(File dir) throws IllegalAccessException {
File parent = dir.getParentFile();
if (!parent.exists()) {
createDir(parent);
}
if (!dir.exists() && !dir.mkdirs()) {
throw new IllegalAccessException(
"Unable to create output dir: " + dir.getAbsolutePath());
}
}
private void deletePath(File path) {
if (path.isDirectory() && path.exists()) {
File[] children = path.listFiles();
if (children != null) {
for (File child : children) {
Log.d("YOUR_TAG", "Deleting " + child.getPath());
deletePath(child);
}
}
}
if (!path.delete()) {
// log message here
}
}
}
Then you can call it from a ViewAction or from the test case class directly:
View Action Class:
class ScreenshotViewAction implements ViewAction {
private final String mClassName;
private final String mMethodName;
private final int mViewId;
private final String mPrefix;
protected ScreenshotViewAction(final int viewId, final String className,
final String methodName, #Nullable final String prefix) {
mViewId = viewId;
mClassName = className;
mMethodName = methodName;
mPrefix = prefix;
}
#Override
public Matcher<View> getConstraints() {
return ViewMatchers.isDisplayed();
}
#Override
public String getDescription() {
return "Taking a screenshot.";
}
#Override
public void perform(final UiController aUiController, final View aView) {
aUiController.loopMainThreadUntilIdle();
final long startTime = System.currentTimeMillis();
final long endTime = startTime + 2000;
final Matcher<View> viewMatcher = ViewMatchers.withId(mViewId);
do {
for (View child : TreeIterables.breadthFirstViewTraversal(aView)) {
// found view with required ID
if (viewMatcher.matches(child)) {
CaptureImage.takeScreenshot(aView.getRootView(), mClassName,
mMethodName, mPrefix);
return;
}
}
aUiController.loopMainThreadForAtLeast(50);
}
while (System.currentTimeMillis() < endTime);
}
}
Now from your test case class, create the following static methods:
public static void takeScreenshot(int prefix) {
View currentView = ((ViewGroup)mActivity
.getWindow().getDecorView().findViewById(android.R.id.content)).getChildAt(0);
String fullClassName = Thread.currentThread().getStackTrace()[3].getClassName();
String testClassName = fullClassName.substring(fullClassName.lastIndexOf(".") + 1);
String testMethodName = Thread.currentThread().getStackTrace()[3].getMethodName();
CaptureImage.takeScreenshot(currentView, testClassName, testMethodName,
String.valueOf(prefix));
}
public static ViewAction takeScreenshot(#Nullable String prefix) {
String fullClassName = Thread.currentThread().getStackTrace()[3].getClassName();
String className = fullClassName.substring(fullClassName.lastIndexOf(".") + 1);
String methodName = Thread.currentThread().getStackTrace()[3].getMethodName();
return new ScreenshotViewAction(getDecorView().getId(), className, methodName, prefix);
}
Or you can invoke it from the perform view action:
takeScreenshot(0);
onView(withContentDescription(sContext
.getString(R.string.abc_action_bar_up_description)))
.perform(
ScreenshotViewAction.takeScreenshot(String.valueOf(1)),
click()
);
i am trying to implement a pdf reader via a pdf library from git hub https://github.com/jblough/Android-Pdf-Viewer-Library but when i implement the code.. all i am getting is a blank page.. the url is correct the pdf has content and this is similar to this q .. Example of code to implement a PDF reader
my code consist of multiple methods, the main method is used to select the which pdf should be chosen to display. then the pdf name is passed on to method "copyreadassets"
public void CopyReadAssets(String url) {
AssetManager assetManager = getApplicationContext().getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getApplicationContext().getFilesDir(), url);
try {
in = assetManager.open(url);
out = getApplicationContext().openFileOutput(file.getName(),
Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
String path = "file://" + getApplicationContext().getFilesDir() + "/"+url;
openPdfIntent(path); }
the openpdfintentmethod is used to open the values
private void openPdfIntent(String path) {
// TODO Auto-generated method stub
try {
final Intent intent = new Intent(Question_Point_Main.this, Pdf.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
pdf.class contains the following..
public class Pdf extends Activity{
public int getPreviousPageImageResource() {
return R.drawable.left_arrow; }
public int getNextPageImageResource() {
return R.drawable.right_arrow; }
public int getZoomInImageResource() {
return R.drawable.zoom_in; }
public int getZoomOutImageResource() {
return R.drawable.zoom_out; }
public int getPdfPasswordLayoutResource() {
return R.layout.pdf_file_password; }
public int getPdfPageNumberResource() {
return R.layout.dialog_pagenumber; }
public int getPdfPasswordEditField() {
return R.id.etPassword; }
public int getPdfPasswordOkButton() {
return R.id.btOK; }
public int getPdfPasswordExitButton() {
return R.id.btExit; }
public int getPdfPageNumberEditField() {
return R.id.pagenum_edit; }
}
In your AndroidManifest.xml file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<activity android:name="com.example.readassetpdf.myPDFActivity"></activity>
in your case activity is pdf class
<activity android:name="com.example.readassetpdf.pdf"></activity>
and use following method
public void CopyReadAssets(String url) {
AssetManager assetManager = getApplicationContext().getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getApplicationContext().getFilesDir(), url);
try {
in = assetManager.open(url);
//out = getApplicationContext().openFileOutput(file.getName(),
//Context.MODE_WORLD_READABLE);
out=new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+"/mypdf.pdf");
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/mypdf.pdf";
openPdfIntent(path);
}
and call it as below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
CopyReadAssets("mypdf.pdf");
}
And the function copyfile is as below
private void copyFile(InputStream in, OutputStream out) throws IOException{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
The replacement is
out = getApplicationContext().openFileOutput(file.getName(),
Context.MODE_WORLD_READABLE);
to
out=new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+"/mypdf.pdf");