How to download image from a URL in android - java

I am showing an image in webview and add onclick listener on download button. When user clicks on the download button it get the address of webview (which in this case is www.realearnpak.com/test/1.jpg). Image is shown in webview, but download image function does not work.
Please help me I am new thanks in advance. I tried alternative functions to download image from url but the do not appear to work.
public class MainActivity extends Activity {
public void DownloadImageFromPath(String path){
InputStream in =null;
Bitmap bmp=null;
int responseCode = -1;
try{
URL url = new URL(path);//"http://192.xx.xx.xx/mypath/img1.jpg
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setDoInput(true);
con.connect();
responseCode = con.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK)
{
//download
in = con.getInputStream();
bmp = BitmapFactory.decodeStream(in);
in.close();
}
}
catch(Exception ex){
Log.e("Exception",ex.toString());
}
}
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WebView mWebView= (WebView) findViewById(R.id.webView1);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// Handle the error
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
mWebView.loadUrl("http://www.realearnpak.com/test/1.jpg");
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Reset...");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int which) {
// here you can add functions
}
});
final Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
String webUrl = mWebView.getUrl();
//alertDialog.setMessage(webUrl);
// alertDialog.show();
DownloadImageFromPath(webUrl);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

Here is one part of a code you can adapt for you need (but you would need to put it in a asynctask or the like) :
// Defines a handle for the byte download stream
InputStream inputStream = null;
FileOutputStream outputStream = null;
HttpEntity entity = null;
// Downloads the image and catches IO errors
try {
// Opens an HTTP connection to the image's URL
final String imageURL = URLEncoder.encode("http://my-path/to-my/beautiful-picture.jp", "UTF-8").replaceAll("\\+", "%20");
HttpGet httpRequest;
try {
httpRequest = new HttpGet(imageURL);
} catch (Exception e) {
Log.w(TAG, e);
throw new InterruptedException();
}
HttpResponse response = new DefaultHttpClient().execute(httpRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(TAG, "Error " + statusCode + " while retrieving bitmap from " + imageURL);
throw new InterruptedException();
}
// Gets the input stream containing the image
entity = response.getEntity();
inputStream = new BufferedHttpEntity(entity).getContent();
bitmap = BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
if (bitmap == null) {
Log.w(TAG, "Error while decoding bitmap from " + imageURL);
throw new IllegalStateException();
}
outputStream = getContext().openFileOutput("Beautiful-picture.jpg", Context.MODE_PRIVATE);
boolean ok = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
if (!ok) {
Log.w(TAG, "Error while compressing bitmap from " + imageURL);
throw new IllegalStateException();
}
// If an IO error occurs, returns immediately
} catch (IOException e) {
e.printStackTrace();
return;
/*
* If the input stream is still open, close it
*/
} finally {
try {
if (null != inputStream) {
inputStream.close();
}
if (null != outputStream) {
outputStream.close();
}
if (entity != null) {
entity.consumeContent();
}
} catch (Exception e) {
e.printStackTrace();
}
}
For the FlushedInputStream, I let you look by yourself :p

There is a great library for this (actually there are a few). I would suggest you use one of them, as this is a common activity (downloading an image from the Web) and this is NOT something that makes sense to do yourself.
I use Picasso (it is a common favorite), Universal Image Downloader is another option.

I prefer volley depends oon what you need it for.
http://www.bignerdranch.com/blog/solving-the-android-image-loading-problem-volley-vs-picasso/

Related

How to save image from URL into internal or external storage?

Here is my code, it says no such file or directory. Can anyone help me with this? I want to save image from URL into storage.
if (imageLoaded) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
if (imageBitmap == null) {
Toast.makeText(getActivity(), "Looks like images didn't load.", Toast.LENGTH_SHORT).show();
} else {
imageBitmap.compress(Bitmap.CompressFormat.JPEG,100,bytes);
File directory = null;
if (Environment.getExternalStorageDirectory().equals(Environment.MEDIA_MOUNTED)) {
directory = new File(Environment.getExternalStorageDirectory(),"COC");
if (!directory.isDirectory()) {
directory.mkdirs();
}
}
File f = new File(directory,ImageName+".jpg");
try {
f.createNewFile();
FileOutputStream fo = null;
fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
Toast.makeText(getActivity(),"saved",Toast.LENGTH_SHORT).show();
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
For this sort of situation choosing a network library like Retrofit would be good . Otherwise you have to create a HTTP url connection , download the image as bitmap and then save it to file . All work needs to be done off the main thread . So lots of thread pooling is needed . So lets solve the problem with retrofit
first add retrofit as dependency to your app level gradle file
compile 'com.squareup.retrofit:retrofit:2.0.0'
compile 'com.squareup.retrofit:converter-gson:2.0.0'
then create a demo layout file with a image view in it , in this image view we are going to show the downloaded image
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageViewId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="1420px"
android:maxHeight="700px"
android:scaleType="fitCenter" />
</RelativeLayout>
after that lets create a network API interface like this
public interface RetrofitImageAPI {
#GET("retrofit/images/uploads/android.jpg")
Call<ResponseBody> getImageDetails();
}
This is a good practice using retrofit as sigleton pattern (see this)
But for demonstration purpose I am showing everything in a single activity
public class MainActivity extends AppCompatActivity {
String url = "http://www.delaroystudios.com/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button ButtonArray= (Button) findViewById(R.id.RetrofitImage);
ButtonArray.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View VisibleImage = findViewById(R.id.RetrofitImage);
VisibleImage.setVisibility(View.GONE);
getRetrofitImage();
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
void getRetrofitImage() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitImageAPI service = retrofit.create(RetrofitImageAPI.class);
Call<ResponseBody> call = service.getImageDetails();
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
try {
Log.d("onResponse", "Response came from server");
boolean FileDownloaded = DownloadImage(response.body());
Log.d("onResponse", "Image is downloaded and saved ? " + FileDownloaded);
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
Log.d("onFailure", t.toString());
}
});
}
private boolean DownloadImage(ResponseBody body) {
try {
Log.d("DownloadImage", "Reading and writing file");
InputStream in = null;
FileOutputStream out = null;
try {
in = body.byteStream();
out = new FileOutputStream(getExternalFilesDir(null) + File.separator + "Android.jpg");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}
catch (IOException e) {
Log.d("DownloadImage",e.toString());
return false;
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
int width, height;
ImageView image = (ImageView) findViewById(R.id.imageViewId);
Bitmap bMap = BitmapFactory.decodeFile(getExternalFilesDir(null) + File.separator + "Android.jpg");
width = 2*bMap.getWidth();
height = 3*bMap.getHeight();
Bitmap bMap2 = Bitmap.createScaledBitmap(bMap, width, height, false);
image.setImageBitmap(bMap2);
return true;
} catch (IOException e) {
Log.d("DownloadImage",e.toString());
return false;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item)
}
}
if it helps please don't forget to like and click the accept button . it means a lot to the person who answers .
have a good day
using Picasso:
Picasso.with(mContext)
.load(ImageUrl)
.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) {
}
}
);
Very simple code to save bitmap to file of your choice of directory:
final File myImageFile = new File(FILE_DIRECTORY, IMAGE_NAME); // Create image file
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myImageFile);
IMAGE_BITMAP.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.i("image", "image saved to >>>" + Uri.parse("file://" + myImageFile.toString()).toString());
If you want to use volley then you can do following:
ImageRequest ir = new ImageRequest(url,
new Response.Listener<Bitmap>() {
#Override
public void onResponse(Bitmap response) {
final File myImageFile = new File(fileDirectory, imageName); // Create image file
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myImageFile);
response.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.i("image", "image saved to >>>" + Uri.parse("file://" + myImageFile.toString()).toString()); downloadedFileUris.add(FileProvider.getUriForFile(ViewReportsActivity.this.getBaseContext(), BuildConfig.APPLICATION_ID + ".provider", myImageFile));
}
}, 0, 0, null, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
You complain that a file can not be created. But you try to write a file in a directory that does not exist. After mkdirs() you do not check if the directory is indeed created. Well it is not.
From Android 6 you should at runtime ask the user to confirm the permissions you requested in manifest.
Google for runtime permissions.

Endless RecyclerView with ProgressBar in Search activity

I am new at android. I have a search activity which searches for a query using async task, i want to implement endless/infinite scrolling when user reaches bottom. I want to add a parameter startrow to async task which will then be passed on to the server telling which row to begin.
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVFish;
private AdapterFish mAdapter;
private LinearLayoutManager mLayoutManager;
private String searchQuery;
SearchView searchView = null;
private String query;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// adds item to action bar
getMenuInflater().inflate(R.menu.search_main, menu);
// Get Search item from action bar and Get Search service
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) MainActivity.this.getSystemService(Context.SEARCH_SERVICE);
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName()));
searchView.setIconified(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
Every time when you press search button on keypad an Activity is recreated which in turn calls this function
#Override
protected void onNewIntent(Intent intent) {
// Get search query and create object of class AsyncFetch
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
query = intent.getStringExtra(SearchManager.QUERY);
if (searchView != null) {
searchView.clearFocus();
}
new AsyncFetch(query).execute();
}
}
class AsyncFetch which will fetch data from the server
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
HttpURLConnection conn;
URL url = null;
String searchQuery;
public AsyncFetch(String searchQuery){
this.searchQuery=searchQuery;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// URL address wherephp file resides
url = new URL("http://someurl/json/search.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput to true as we send and recieve data
conn.setDoInput(true);
conn.setDoOutput(true);
// add parameter to our above url
Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return("Connection error");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<DataFish> data=new ArrayList<>();
pdLoading.dismiss();
if(result.equals("no rows")) {
Toast.makeText(MainActivity.this, "No Results found for entered query", Toast.LENGTH_LONG).show();
}else{
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataFish fishData = new DataFish();
try {
fishData.fileName = URLDecoder.decode(json_data.getString("file"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
fishData.linkName = json_data.getString("link");
fishData.reg_date = json_data.getString("reg_date");
fishData.fileSize = json_data.getString("filesize");
data.add(fishData);
}
// Setup and Handover data to recyclerview
mRVFish = (RecyclerView) findViewById(R.id.fishPriceList);
mAdapter = new AdapterFish(MainActivity.this, data);
// mRVFish.setLayoutManager(new LinearLayoutManager(MainActivity.this));
mLayoutManager = new LinearLayoutManager(MainActivity.this);
mRVFish.setLayoutManager(mLayoutManager);
mRVFish.setAdapter(mAdapter);
} catch (JSONException e) {
// You to understand what actually error is and handle it appropriately
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
Add EndlessScrollListener to recyclerView from link:
https://gist.github.com/zfdang/38ae655a4fc401c99789#file-endlessrecycleronscrolllistener-java
override onLoadMore method and call your AsyncFetch Task.

Getting bitmap null while converting url to bitmap

I want to download the image from server and convert it to bitmap. I tried to download the image and convert it to bitmap but it returns null. I get bitmap as null.
To convert image to bitmap I have created one asyncTask.
Passing url to Async task :
String url = ServiceUrl.getBaseUrl() + ServiceUrl.getImageUserUrl() + profileImage;
Log.e("url", url);
new ImageUserTask(mContext, url, profileImage).execute();
ImageUserAsync Task:
public class ImageUserTask extends AsyncTask<Void, Void, Bitmap> {
String imageprofile;
private String url;
private Bitmap mBitmap;
private Context mContext;
public ImageUserTask(Context context, String url, String imageprofile) {
this.url = url;
this.imageprofile = imageprofile;
this.mContext = context;
}
#Override
protected Bitmap doInBackground(Void... params) {
try {
//Url
URL urlConnection = new URL(url);
//Conntecting httpUrlConnection
HttpURLConnection connection = (HttpURLConnection) urlConnection.openConnection();
connection.setDoInput(true);
//Connected to server
connection.connect();
//downloading image
InputStream input = connection.getInputStream();
//converting image to bitmap
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (result != null) {
result = mBitmap;
new ImageServer(mContext).save(result);
}
}
}
EDIT :
Tried to use picasso :
#Override
protected void onPostExecute(JSONObject response) {
super.onPostExecute(response);
count=0;
if (response.has("message")) {
JSONObject userJson = null;
String message = null;
count++;
try {
if (response.getString("message").equalsIgnoreCase(KEY_SUCCESS)) {
Toast.makeText(mContext, "user authenticated successfully", Toast.LENGTH_LONG).show();
userJson = response.getJSONObject("user");
String userId = userJson.getString("user_id");
String userName = userJson.getString("user_name");
String profileImage = userJson.getString("profile_image");
String mobileNo = userJson.getString("mobile_no");
String url = ServiceUrl.getBaseUrl() + ServiceUrl.getImageUserUrl() + profileImage;
Log.e("url", url);
User user = new User();
user.setmUserId(userId);
user.setmUserName(userName);
user.setmProfileImage(profileImage);
user.setmMobileNo(mobileNo);
SharedPreferences.Editor editor = mContext.getSharedPreferences("username",mContext.MODE_PRIVATE).edit();
editor.putString("UserUsername",userName);
editor.commit();
Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
try {
File f = new File(mContext.getCacheDir(), "Profile");
f.createNewFile();
//Convert bitmap to byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
Log.e("File",String.valueOf(f));
}
catch (IOException e)
{
}
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
Picasso.with(mContext).load(url).into(target);
Toast.makeText(mContext, "user authenticated successfully", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
mContext.startActivity(intent);
Picasso.with(mContext).cancelRequest(target);
}
}
What's going wrong?
Try this I am getting image by this method.
URL url1l = new URL("<Image url>");
URLConnection connection = url1l.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream is = new BufferedInputStream(connection.getInputStream());
bitmap = BitmapFactory.decodeStream(is);
The most likely reason is that you are getting an error from the server or that the data you are getting back cannot be decoded. First of all, check the response code after the connection is opened:
connection.connect();
int respCode = connection.getResponseCode();
Log.d("resp code", "response code " + respCode);
If you get anything other than 200, then something is wrong with retrieving data (wrong url, auth, or server error). If you do get 200, then the issue is with the data you are receiving. Read the data into a byte array and dump it into a file to examine.
First check with image is really exists or not as #aman grover said
if available use Picasso Lib to download image and from url.
here is sample code
private Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
//Note : here you can get Bitmap
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
private void someMethod() {
Picasso.with(this).load("url").into(target);
}
#Override
public void onDestroy() { // could be in onPause or onStop
Picasso.with(this).cancelRequest(target);
super.onDestroy();
}

Call Function on Menu Click Android

I am beginner android developer and trying to implement one function for overflow menu.
My menu code is like this
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id==android.R.id.home) {
finish();
}else if (id == R.id.image) {
takeScreenshot(); // getting error like The method takeScreenshot(Context, View) in the type QuoteViewActivity is not applicable for the arguments ()
return true;
}
and
function code is like
public static void takeScreenshot(Context context, View view) {
String path = Environment.getExternalStorageDirectory().toString()
+ "/" + "test.png";
View v = view.findViewById(android.R.id.content).getRootView();
v.setDrawingCacheEnabled(true);
v.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
OutputStream out = null;
File imageFile = new File(path);
try {
out = new FileOutputStream(imageFile);
// choose JPEG format
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
} catch (FileNotFoundException e) {
// manage exception
} catch (IOException e) {
// manage exception
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception exc) {
}
}
// onPauseVideo();
Intent share = new Intent(Intent.ACTION_SEND);
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imageFile));
share.setType("image/png");
((Activity) context).startActivityForResult(
Intent.createChooser(share, "Share Drawing"), 111);
}
How can I call it on menu click ?
Sorry for stupid question for developer
Thanks
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
}
don't forget this
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
The way you handle the click on a Menu Item is like this:
First, setup your Options Menu:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mnuInflater = getSupportMenuInflater();
mnuInflater.inflate(R.menu.your_menu_xml, menu);
return true;
}
Handle the clicks here:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
// EITHER CALL THE METHOD HERE OR DO THE FUNCTION DIRECTLY
yourMethod();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
And do the function in the yourMethod() here:
private void yourMethod() {
// TODO Auto-generated method stub
}
From what I see, it should be the following:
takeScreenshot(this, findViewById(R.id.your_root_layout));
However, you can call takeScreenshot(); if takeScreenshot is not static and inside your activity.

How to download multiple images and have one progressBar using AsynTask (Android)

I want my program to download many images (around 500) from the internet and store them in my external storage. Currently when I download a single image, it shows a progressBar and downloads the image properly. However when I am trying to replicate w/ two images, it gives the Toast for "Download complete" for both images being downloaded, however no progressBar for either image is shown and only the first image is properly downloaded.
Here is the code for my onCreate method for activity.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Remove Title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//force portrait orientation. (No landscape orientation).
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_quran);
//Instantiate ProgressDialog (Used for downloading quran pages).
myProgressDialog = new ProgressDialog(QuranActivity.this);
myProgressDialog.setMessage("Downloading Quran");
myProgressDialog.setIndeterminate(true);
myProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
myProgressDialog.setCancelable(true);
//execute when the downloader must be fired.
final DownloadTask downloadTask = new DownloadTask(QuranActivity.this);
DownloadTask second = new DownloadTask(getApplicationContext());
myHTTPURL = "https://ia601608.us.archive.org/BookReader/BookReaderImages.php?zip=/10/items/05Quran15LineWhitePageWithVioletBorderWww.Momeen.blogspot.com/05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_jp2.zip&file=05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_jp2/05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_0001.jp2&scale=1&rotate=0";
myHTTPURL2 = "https://ia601608.us.archive.org/BookReader/BookReaderImages.php?zip=/10/items/05Quran15LineWhitePageWithVioletBorderWww.Momeen.blogspot.com/05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_jp2.zip&file=05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_jp2/05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_0002.jp2&scale=1&rotate=0";
//First check if the file has already been created. (Only need to download 1ce, or
//in the case where the user deleted the files, we reinstall them again).
if (isExternalStorageWritable()) {
File makeDirectory = getQuranStorageDir(QuranActivity.this, "Quran_Pages");
for (int i = 0; i < 2; i++) {
Bundle myBundle = new Bundle();
myBundle.putInt("i", i);
if (i == 0) {
downloadTask.execute(myHTTPURL);
try {
downloadTask.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
myProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true);
}
});
} else {
/*if (downloadTask.getStatus() == AsyncTask.Status.FINISHED) {
downloadTask.execute(myHTTPURL2);
} else if (downloadTask.getStatus() == AsyncTask.Status.RUNNING) {
try {
downloadTask.execute(myHTTPURL2).wait(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} */
second.execute(myHTTPURL2);
try {
second.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
// downloadTask.execute(myHTTPURL2);
}
}
}
and this is the code for my AsynTask Class.
#TargetApi(Build.VERSION_CODES.FROYO)
private class DownloadTask extends AsyncTask {
private Context context;
private PowerManager.WakeLock myWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("GET");
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
//Display download percentage.
int fileLength = connection.getContentLength();
//create folder to place the downloaded file in.
// File Path:E:\Android\data\com.syedabdullah.syed.quran_memorization_application
// \files\Quran Memorization Application\Quran_Pictures
//So first create a root folder Quran Memorization Application then inside that
//folder we create another folder named Quran Pictures.
/* File rootFolder = new File(getExternalFilesDir("Quran Memorization Application"),
"Quran_Pages"); */
//Here we insert inside the Quran_Pictures folder the quran_pages.
//String myFileName = "quran_01.jpg";
Bundle y = new Bundle();
int retrievePos = y.getInt("i");
String quranFilePageName = "_" + retrievePos + ".jpg";
// String fileName = "justwork.jpg";
File sup = new File(getExternalFilesDir("Quran Memorization Application"), "Quran_Pages");
File myFile = new File(sup, quranFilePageName);
myFile.createNewFile();
//downlaod the file.
input = connection.getInputStream();
output = new FileOutputStream(myFile);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
//allow cancel with back button.
if (isCancelled()) {
input.close();
return null;
}
total += count;
//publish the progress.
if (fileLength > 0) {
publishProgress((int) (total * 100 / fileLength));
}
output.write(data, 0, count);
}
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(myFile));
QuranActivity.this.sendBroadcast(intent);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (output != null) {
output.close();
}
if (input != null) {
input.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (connection != null) {
connection.disconnect();
}
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//Take CPU lock to prevent CPU from going off if the user presses the power button.
//during download.
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
myWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
myWakeLock.acquire();
myProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
//If we get here length is known, so setIndertimante to false.
myProgressDialog.setIndeterminate(false);
myProgressDialog.setMax(100);
myProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
myWakeLock.release();
myProgressDialog.dismiss();
if (result != null) {
Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Download Complete", Toast.LENGTH_SHORT).show();
}
}
} }
I was hoping to have a for loop that would create hundreds of downloadTasks and download all the images I need, and then I would call the get method. However in order for that to work, I first need too know why when I try for 2 images only the first one gets downloaded and why no progressbar shows up. Also if possible if I could get a hint as to how I can make my progressBar update for all the images and not be designed for just 1. Thanks in advance. (Note all URLs are currect.)
Thank you so much! figured out that my loops were suppose to go inside doInBackground. Also to anyone else having a similar issue. To download multiple files and display a decent progressBar, here is a very great tutorial: http://theopentutorials.com/tutorials/android/dialog/android-download-multiple-files-showing-progress-bar/

Categories

Resources