I want to share the image and text on twitter using my App. I user Fabric SDK and follow the guidelines on their official website. Problem is my image is not stored in phone storage and its a URL link. so when I pass that URL its not showing like FB sharing.
Below I have posted the Tried code for now.
private void shareViaTwitt() {
final String myUrlStr = "http://i.stack.imgur.com/2FCsj.png";
URL url;
Uri uri = null;
try {
url = new URL(myUrlStr);
uri = Uri.parse(url.toURI().toString());
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
TweetComposer.Builder builder = new TweetComposer.Builder(getContext())
.text("Hi this is Sample twitter sharing")
.image(uri);
builder.show();
}
Thank you.
/*In their official site has said need put file type uri that stored in
phone/SD storage. So Here I just save it and get that uri and then pass it to
fabric builder.*/
private void shareViaTwitt() {
final String myUrlStr = "http://i.stack.imgur.com/2FCsj.png";
TweetComposer.Builder builder = null;
try {
Bitmap bm = getBitmapFromURL(myUrlStr);
Uri uri = getImageUri(getContext(), bm);
builder = new TweetComposer.Builder(getContext())
.text("Sample Text")
.image(uri)
.url(new URL(""https://www.newurl.....));
builder.show();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public static Bitmap getBitmapFromURL(String src) {
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Related
Good morning,
I have following code to download bitmpa from server
/*SAVE IMAGE++++++++++++++++++++*/
public void saveImage(Context context, Bitmap b, String imageName) {
FileOutputStream foStream;
try {
foStream = context.openFileOutput(imageName, Context.MODE_PRIVATE);
b.compress(Bitmap.CompressFormat.JPEG, 100, foStream);
foStream.close();
UPDTV_FOTO.setBackgroundColor(Color.GREEN);
image.setImageBitmap(loadImageBitmap(getApplicationContext(), Giocatore));
UPDTV_FOTO.setText("Download "+Giocatore+ " Complete");
}
catch (FileNotFoundException e) {
Log.d("saveImage", "file not found");
e.printStackTrace();
// UPDTV_FOTO.setText("FILE NOT FOUND");
}
catch (IOException e) {
Log.d("saveImage", "io exception");
e.printStackTrace();
// UPDTV_FOTO.setText("SAVE IMAGE ERROR");
}
}
/*SAVE IMAGE+++++++++++++++++++++++++*/
/*DOWNLOAD IMAGE++++++++++++++++++++++*/
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
private String TAG = "DownloadImage";
private Bitmap downloadImageBitmap(String sUrl) {
Bitmap bitmap = null;
try {
InputStream inputStream = new URL(sUrl).openStream(); // Download Image from URL
bitmap = BitmapFactory.decodeStream(inputStream); // Decode Bitmap
inputStream.close();
} catch (Exception e) {
Log.d(TAG, "Exception 1, Something went wrong!");
e.printStackTrace();
// UPDTV_FOTO.setText("DOWNLOAD ERROR");
}
return bitmap;
}
#Override
protected Bitmap doInBackground(String... params) {
return downloadImageBitmap(params[0]);
}
protected void onPostExecute(Bitmap result) {
saveImage(getApplicationContext(), result, Giocatore);
}
}
/*DOWNLOAD IMAGE++++++++++++++++++++++*/
/*LOAD IMAGE*+++++++++++++++++++++++++++++++++++++*/
public Bitmap loadImageBitmap(Context context, String imageName) {
Bitmap bitmap = null;
FileInputStream fiStream;
try {
fiStream = context.openFileInput(imageName);
bitmap = BitmapFactory.decodeStream(fiStream);
fiStream.close();
} catch (Exception e) {
Log.d("saveImage", "Exception 3, Something went wrong!");
e.printStackTrace();
// UPDTV_FOTO.setText("LOAD ERROR");
}
return bitmap;
}
/*LOAD IMAGE+++++++++++++++++++++++++++*/
if the bitmap I try to download is available on server all works fine with
new DownloadImage().execute(myurl);
else if is not available, my app crashes.
So I would like to check if bitmap is available on servere before starting download.
I try
if (URLUtil.isValidUrl(URL+FotoGiocatore)==true);
and also
How can I programmatically test an HTTP connection?
Check if file exists on remote server using its URL
You can also use below code to check if the image is present
URL url = new URL("YOUR URL");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
`int status = urlConnection.getResponseCode();`
and only start download if status==200
i am using this method to get images from url and i am downloading more than one image the varable below called "name" is an array of names of the images .i want to be able to store all images whos name is in the array thats why i kept the url like that.it seems to work well but i have having problem selecting only one picture out or them.
this is the code to save images
String fileName="code";
try {
URL url = new URL("http://10.0.2.2/picure/"+name+".jpg");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
Bitmap bm = BitmapFactory.decodeStream(is);
FileOutputStream fos = getActivity().openFileOutput(fileName, Context.MODE_PRIVATE);
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
byte[] byteArray = outstream.toByteArray();
fos.write(byteArray);
fos.close();
Toast.makeText(getActivity()," connected", Toast.LENGTH_LONG).show();
} catch(Exception e) {
}
this is the code to collect images
String path = mContext.getFilesDir().toString();
String fileName = "code";
if (fileName != null && !fileName.equals("")) {
Bitmap bMap = BitmapFactory.decodeFile(path + "/" + fileName);
if (bMap != null) {
category_logo.setImageBitmap(bMap);
}
}
i know the names of the images i saved so how do i select that one specifically
For get all images use a Asynctask, this code can download images in cache directory of the app:
class ImageDownloader extends AsyncTask<String, Void, File> {
String imageurl;
String name;
Context ctx;
public ImageDownloader(Context context, String url, String fileName) {
this.imageurl = url;
this.name = fileName;
this.ctx = context;
}
#Override
protected File doInBackground(String... urls) {
Bitmap mIcon;
File cacheDir = ctx.getCacheDir();
File f = new File(cacheDir, name);
try {
InputStream in = new java.net.URL(imageurl).openStream();
mIcon = BitmapFactory.decodeStream(in);
try {
FileOutputStream out = new FileOutputStream(
f);
mIcon.compress(
Bitmap.CompressFormat.JPEG,
100, out);
out.flush();
out.close();
return f;
} catch (FileNotFoundException e) {
return null;
} catch (IOException e) {
return null;
}
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(File result) {
super.onPostExecute(result);
Toast.makeText(ctx," connected " + name, Toast.LENGTH_LONG).show();
}
}
}
For call the asynctask, you need use a FOR for get all names and url of the image:
new ImageDownloader(getBaseContext(),url[i],name[i]).execute();
You can edit the doInBackground with your code, but the HTTPConnection that you use is deprecated in API 22, please use the example above, you can change the directory.
And sorry for the code, you can reformat later.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CODE_MULTIPLE_IMG_GALLERY && resultCode==RESULT_OK){
ClipData clipData = data.getClipData();
if (clipData!=null){
File folderPath = new File(getIntent().getStringExtra("folderpath"));
for (int i = 0;i< clipData.getItemCount();i++){
ClipData.Item item = clipData.getItemAt(i);
Uri uri = item.getUri();
Bitmap selectedImage = loadFromUri(uri);
File imagePath = new File(folderPath,System.currentTimeMillis()+".jpg");
try {
outputStream = new FileOutputStream(imagePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
selectedImage.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
Log.d("uri",uri.toString());
imageModelList.add(new ImageModel(uri.toString()));
}
imagesAdapter.notifyDataSetChanged();
Toast.makeText(ImageDetailActivity.this, "Added Successfully!", Toast.LENGTH_SHORT).show();
}
}
}
public Bitmap loadFromUri(Uri photoUri) {
Bitmap image = null;
try {
// check version of Android on device
if(Build.VERSION.SDK_INT > 27){
// on newer versions of Android, use the new decodeBitmap method
ImageDecoder.Source source = ImageDecoder.createSource(this.getContentResolver(), photoUri);
image = ImageDecoder.decodeBitmap(source);
} else {
// support older versions of Android by using getBitmap
image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoUri);
}
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
I am new in Android.
I am downloading images from the internet in the ListView .I getting the url in the file object but when I send it into the Bitmap object the bitmap object is return null means image is not loaded into the bitmap object.please reply me. the code is here:
private Bitmap getBitmap(String url) {
String filename = String.valueOf(url.hashCode());
File f = new File(cacheDir, filename);
// here in f i getting image url
// here in bitmap the url is not loaded & get null
Bitmap bitmap = BitmapFactory.decodeFile(f.getPath());
if(bitmap != null) return bitmap;
// Nope, have to download it
try {
bitmap =
BitmapFactory.decodeStream(new URL(url).openConnection().getInputStream());
// save bitmap to cache for later
writeFile(bitmap, f);
return bitmap;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
private void writeFile(Bitmap bmp, File f) {
FileOutputStream out = null;
try {
out = new FileOutputStream(f);
bmp.compress(Bitmap.CompressFormat.PNG, 80, out);
} catch (Exception e) {
e.printStackTrace();
}
finally {
try { if (out != null ) out.close(); }
catch(Exception ex) {}
}
}
I do not think you are downloading properly the bitmap.
CODE
This is a function I created that will take a url from you and it will return a drawable!
It will save it to a file and get it if it exists
If not, it will download it and return the drawable.
You can easily edit it to save file to your folder instead.
/**
* Pass in an image url to get a drawable object
*
* #return a drawable object
*/
private static Drawable getDrawableFromUrl(final String url) {
String filename = url;
filename = filename.replace("/", "+");
filename = filename.replace(":", "+");
filename = filename.replace("~", "s");
final File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + filename);
boolean exists = file.exists();
if (!exists) {
try {
URL myFileUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
final Bitmap result = BitmapFactory.decodeStream(is);
is.close();
new Thread() {
public void run() {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
result.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
try {
if (file.createNewFile()){
//
}
else{
//
}
FileOutputStream fo;
fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.flush();
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
BitmapDrawable returnResult = new BitmapDrawable(result);
return returnResult;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
else {
return new BitmapDrawable(BitmapFactory.decodeFile(file.toString()));
}
}
Only thing I can think of here is that you're missing INTERNET permission in your manifest.
Try adding <uses-permission android:name="android.permission.INTERNET" /> in your AndroidManifest.xml if it's not there yet
In my activity, I am downloading images from url. I want these images to be downloaded only for the first time. Later on when I visit this page, it should take the image from the sdcard. How can I do that? Can anyone help?
In manifest I have set permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
The method which I use for downloading is:
public static Bitmap downloadFileFromUrl(String fileUrl){
URL myFileUrl =null;
Bitmap imageBitmap = null;
try {
myFileUrl= new URL(fileUrl);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection connection= (HttpURLConnection)myFileUrl.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream is = connection.getInputStream();
imageBitmap = BitmapFactory.decodeStream(is);
//Below two lines I just tried out for saving to sd card.
FileOutputStream out = new FileOutputStream(fileUrl);
imageBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
}
catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
return imageBitmap;
}
Try this method
public void DownloadImage(String imageUrl)
{
InputStream is = null;
if((imageUrl == null) || (imageUrl.length() == 0) || (imageUrl == " "))
{
System.out.println("No need to download images now");
}
else
{
System.gc();
String[] items;
String ImageName = null;
URL myFileUrl =null;
Bitmap bmImg = null;
String path = IMAGE_DOWNLOAD_PATH;
FileOutputStream outStream = null;
File file = new File(path);
if(!file.exists())
{
file.mkdirs();
}
File outputFile;
BufferedOutputStream bos;
try {
myFileUrl= new URL(imageUrl.trim());
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setConnectTimeout(20000);
conn.connect();
is = conn.getInputStream();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ImageName = getImageName(imageUrl);
try {
outputFile = new File(file, ImageName);
if(outputFile.exists())
{
System.out.println("No need to download image it already exist");
outputFile.delete();
}
outputFile.createNewFile();
outStream = new FileOutputStream(outputFile);
//bos = new BufferedOutputStream(outStream);
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1)
{
baf.append((byte) current);
}
outStream.write(baf.toByteArray());
outStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and then to retrieve image from sdcard,
File extStore = Environment.getExternalStorageDirectory();
String file_path = "/(folder name)/"+"(image name)".trim()+".extension".trim();
String mypath = extStore + file_path;
Bitmap bmp=BitmapFactory.decodeFile(mypath);
ImageView image = (ImageView) v.findViewById(R.id.image);
image.setImageBitmap(bmp);
You should store somewhere what you've got in cache.
Or if your filename are unique you've to check than the file exist or not.
You have to write the data got from InputStream to specified SD card location ..
I am trying to get images from facebook using following method. I'm getting an error "SSL denied". I got the image urls from the facebook API. The image urls are of facebook profile pictures.
ImageView image=(ImageView)view.findViewById(R.id.iView);
String imageurl=https://graph.facebook.com/100000685876576/picture;
Drawable drawable=LoadImageFromWebOperations(imageurl);
image.setImageDrawable(drawable);
private Drawable LoadImageFromWebOperations(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
//Log.e("DEMO ADAPTER",e.toString());
return null;
}
}
can anyone help me out...
Thanks.
try this
public static Bitmap downloadfile(String fileurl)
{
Bitmap bmImg = null;
URL myfileurl =null;
try
{
myfileurl= new URL(fileurl);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
try
{
HttpURLConnection conn=
(HttpURLConnection)myfileurl.openConnection();
conn.setDoInput(true);
conn.connect();
int length = conn.getContentLength();
if(length>0)
{
int[] bitmapData =new int[length];
byte[] bitmapData2 =new byte[length];
InputStream is = conn.getInputStream();
BitmapFactory.Options options = new
BitmapFactory.Options();
options.inSampleSize = 1;
bmImg = BitmapFactory.decodeStream(is,null,options);
}
else
{
}
}
catch(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return bmImg;
}