Loading photos with basic auth - java

I have a code like this:
public class MainActivity extends AppCompatActivity {
ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = findViewById(R.id.img1);
}
public void onClick(View v) {
new DownloadImageTask((ImageView) findViewById(R.id.img1))
.execute("http://view:view#178.217.49.11:5022/tmpfs/snap.jpg\"");
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
It loads the photo fine from this link: http://92.63.192.191/d/SCP-1017.png, but it doesn't load the photo from here: http://view:view#178.217.49.11:5022/tmpfs/snap.jpg
UPDATE
I realized that I need to use basic auth, but I don't know how to do it.
UPDATE2
I did it! Here's my resulting class:
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
URL url = new URL(urls[0]);
URLConnection uc = url.openConnection();
String userpass = USERNAME + ":" + PASSWORD;
String basicAuth = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
}
uc.setRequestProperty ("Authorization", basicAuth);
InputStream in = uc.getInputStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
URL url = new URL(urls[0]);
URLConnection uc = url.openConnection();
String userpass = USERNAME + ":" + PASSWORD;
String basicAuth = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
}
uc.setRequestProperty ("Authorization", basicAuth);
InputStream in = uc.getInputStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}

Related

BitmapFactory.decodeStream leads to : D/skia: --- Failed to create image decoder with message 'unimplemented'

I'm trying to download an image from a URL by creating a Bitmap using
bitmapFactory.decodeStream(InputStream) and then imageView.setImageBitmap(bitmap) but I am always getting this error:
D/skia: --- Failed to create image decoder with message
'unimplemented'. package com.example.flickrapp;
Here is my code:
import statements will go here ...
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
Button b = (Button)findViewById(R.id.getanimage);
b.setOnClickListener(new GetImageOnClickListener() {
#Override
public void onClick(View v) {
super.onClick(v);
}
});
}
public class GetImageOnClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
AsyncFlickrJSONData imagesData = new AsyncFlickrJSONData();
imagesData.execute("https://www.flickr.com/services/feeds/photos_public.gne?tags=trees&format=json");
}
}
public class AsyncFlickrJSONData extends AsyncTask<String, Void, JSONObject> {
#Override
protected JSONObject doInBackground(String... strings) {
String flickrUrl = strings[0];
JSONObject jsonFlickr = null;
URL url = null;
try {
url = new URL(flickrUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
String s1 = readStream(in);
int lengthS = s1.length();
String s = (String) s1.subSequence(15, lengthS-1);
jsonFlickr = new JSONObject(s);
} finally {
urlConnection.disconnect();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return jsonFlickr;
}
#Override
protected void onPostExecute(JSONObject jsonFlickr) {
super.onPostExecute(jsonFlickr);
try {
String firstUrl = jsonFlickr.getJSONArray("items").getJSONObject(0).getString("link");
AsyncBitmapDownloader firstAsyncImage = new AsyncBitmapDownloader();
firstAsyncImage.execute(firstUrl);
Log.i("JFL", firstUrl);
} catch (JSONException e) {
e.printStackTrace();
}
}
private String readStream(InputStream in) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
Log.e(TAG, "IOException", e);
} finally {
try {
in.close();
} catch (IOException e) {
Log.e(TAG, "IOException", e);
}
}
return sb.toString();
}
}
public class AsyncBitmapDownloader extends AsyncTask<String, Void, Bitmap> {
ImageView firstImage = (ImageView) findViewById(R.id.image);
#Override
protected Bitmap doInBackground(String... strings) {
String imageUrl = strings[0];
Bitmap bm = null;
URL url = null;
try {
url = new URL(imageUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
bm = BitmapFactory.decodeStream(in);
} finally {
urlConnection.disconnect();
}
} catch(IOException e){
e.printStackTrace();
}
return bm;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
firstImage.setImageBitmap(bitmap);
}
}
}
Any Suggestions or Ideas are welcomed :)

Display to the image view on list view click

I am making this news application in which I m finding difficulties. here I am using list view.here I am performing background task also and even in this I am able to fetch all the news. The only thing which is not working is when I click on list item its respective image is not showing.
How can I take the image from url and when clicked on the item, the image of that respective list is opened?
public class MainActivity extends AppCompatActivity
{
ListView aboutNews;
Bitmap myImage;
ImageView newnewImage;
ArrayAdapter<String> myArrayAdapter;
ArrayList<String> newscontent , urlImageContent;
String finalUrl;
public void DisplayNews(String title, String urlToImage) {
myArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, newscontent); //i will not put this on oncreate because it will slow down my app.
aboutNews.setAdapter(myArrayAdapter);
newscontent.add(title);
urlImageContent.add(urlToImage);
}
public class downloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
String news = jsonObject.getString("articles");
JSONArray arr = new JSONArray(news);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
String title = jsonPart.getString("title");
String description = jsonPart.getString("description");
String urlToImage = jsonPart.getString("urlToImage");
String publish = jsonPart.getString("publishedAt");
String content = jsonPart.getString("content");
DisplayNews(title , urlToImage);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) { //we have renamed strings to url
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream in = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(in); //it adds everything to the bitmap.
return myBitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
newscontent = new ArrayList<String>();
urlImageContent = new ArrayList<String>();
aboutNews = findViewById(R.id.aboutNews);
//.........................................................................
aboutNews.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
finalUrl = urlImageContent.get(i);
ImageDownloader task1 = new ImageDownloader();
try {
myImage = task1.execute(finalUrl).get();
newnewImage.setImageBitmap(myImage);
} catch (Exception e) {
e.printStackTrace();
}
}
});
//.........................................................................
downloadTask task = new downloadTask();
try {
task.execute("https://newsapi.org/v2/top-headlines?country=in&apiKey=API_KEY");
} catch (Exception e) {
e.printStackTrace();
}
}
}

How to create image from webService, Android

So, I have this app that is connected to a WebService and I am already retrieving data from there, now I want to retrieve a image link and make that the imageView gets that image trough the link. Is that even possible? Appreciate any help :D
#Override
protected Void doInBackground(Void... params) {
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from URL: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray array = new JSONArray(jsonStr);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
JSONArray paises = jsonObject.optJSONArray("paises");
if (paises != null) {
for (int j = 0; j < paises.length(); j++) {
JSONObject jsonObject1 = paises.getJSONObject(j);
System.out.println(jsonObject1.optString("Designacao"));
String K_PAIS = jsonObject1.getString("K_PAIS");
String Designacao = jsonObject1.getString("Designacao");
String URL_IMAGE_SMALL = jsonObject1.getString("URL_IMAGE_SMALL");
String URL_IMAGEM = "http://something.something.pt" + URL_IMAGE_SMALL;
new DownloadImage(imageView6).execute(URL_IMAGEM);
HashMap<String, String> pais = new HashMap<>();
pais.put("K_PAIS", K_PAIS);
pais.put("Designacao", Designacao);
pais.put("URL_IMAGE_SMALL", URL_IMAGE_SMALL);
pais.put("URL_IMAGEM", URL_IMAGEM);
listaPaises.add(pais);
}
}
System.out.println(jsonObject.optString("Designacao"));
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Json parsin error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errpr!", Toast.LENGTH_LONG).show();
}
});
}
return null;
}
{...}
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = (ImageView) bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("Error", e.getStackTrace().toString());
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
You can use Picasso, a wonderful image library.
Example:
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
Add dependency via Gradle:
compile 'com.squareup.picasso:picasso:2.5.2'
you can use any third party library
example use Glide library
this library will help you to fetch and display image on ImageView from url.
example:
Glide.with(context).load(image_url).into(your_image_view);
here is link for that library : https://github.com/bumptech/glide
You have to set your ImageView inside your XML as you normally do. Then you can use any third party library like Picasso or Glide that will load the image from the url and set it to your ImageView in your activity/fragment.
In your app build.gradle add
compile 'com.github.bumptech.glide:glide:3.7.0'
use this code to load image from url
Glide.with(getApplicationContext()).load("image_url").into(ImageView);
try this if you dont want to use third party library
new DownloadImage(imamgeview).execute(url);
create a Async Task
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
CircleImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = (CircleImageView) bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("Error", e.getStackTrace().toString());
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
i hope you it will work in your case
step 1: create class named DownloadImage
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
CircleImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = (CircleImageView) bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("Error", e.getStackTrace().toString());
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
Step 2: execute AsyncTask
new DownloadImage(imgUserProfile).execute(userProfileUrl);
**Json Url like this: ** https://graph.facebook.com/1220130444748799/picture?height=400&width=400&migration_overrides=%7Boctober_2012%3Atrue%7D

how to fetch data without button click

how to fetch first image without click fetch image button
click to view image
this code work fine but on click fetch image button but i want fetch image with out click fetch images button i want to remove this button
Public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
private String imagesJSON;
private static final String JSON_ARRAY ="result";
private static final String IMAGE_URL = "url";
private JSONArray arrayImages= null;
private int TRACK = 0;
private static final String IMAGES_URL = "http://www.simplifiedcoding.16mb.com/ImageUpload/getAllImages.php";
private Button buttonFetchImages;
private Button buttonMoveNext;
private Button buttonMovePrevious;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
buttonFetchImages = (Button) findViewById(R.id.buttonFetchImages);
buttonMoveNext = (Button) findViewById(R.id.buttonNext);
buttonMovePrevious = (Button) findViewById(R.id.buttonPrev);
buttonFetchImages.setOnClickListener(this);
buttonMoveNext.setOnClickListener(this);
buttonMovePrevious.setOnClickListener(this);
}
private void extractJSON(){
try {
JSONObject jsonObject = new JSONObject(imagesJSON);
arrayImages = jsonObject.getJSONArray(JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showImage(){
try {
JSONObject jsonObject = arrayImages.getJSONObject(TRACK);
getImage(jsonObject.getString(IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
}
private void moveNext(){
if(TRACK < arrayImages.length()){
TRACK++;
showImage();
}
}
private void movePrevious(){
if(TRACK>0){
TRACK--;
showImage();
}
}
private void getAllImages() {
class GetAllImages extends AsyncTask<String,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Fetching Data...","Please Wait...",true,true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
imagesJSON = s;
extractJSON();
showImage();
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
return sb.toString().trim();
}catch(Exception e){
return null;
}
}
}
GetAllImages gai = new GetAllImages();
gai.execute(IMAGES_URL);
}
private void getImage(String urlToImage){
class GetImage extends AsyncTask<String,Void,Bitmap>{
ProgressDialog loading;
#Override
protected Bitmap doInBackground(String... params) {
URL url = null;
Bitmap image = null;
String urlToImage = params[0];
try {
url = new URL(urlToImage);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this,"Downloading Image...","Please wait...",true,true);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
loading.dismiss();
imageView.setImageBitmap(bitmap);
}
}
GetImage gi = new GetImage();
gi.execute(urlToImage);
}
#Override
public void onClick(View v) {
if(v == buttonFetchImages) {
getAllImages();
}
if(v == buttonMoveNext){
moveNext();
}
if(v== buttonMovePrevious){
movePrevious();
}
}
}
You can trigger it in onCreate(),but you must not run it on UI thread,for it might be a time-consuming operation.Read Specifying the Code to Run on a Thread to help,
you might add the following block in your onCreate() method:
new Runnable() {
#Override
public void run() {
getAllImages();
}
}.run();

How do i download multiple images on android from localhost server?

I created an android application to download images from my local server, but i failed to do it. I tried few times but i did not work out. Here is my source code at the exact class i created to do the function i want:
ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>(4);
public static final String URL = "http://localhost/img/";
Button load_img;
ImageView imageview;
Bitmap bitmap;
ProgressDialog pDialog;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_monitor);
load_img = (Button)findViewById(R.id.load);
imageview = (ImageView)findViewById(R.id.img);
load_img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new LoadImage().execute(new String[]{URL});
//img.setImageBitmap(bitmapArray.ge);
}
});
}
private class LoadImage extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Monitor.this);
pDialog.setMessage("Fetching Images ....");
pDialog.show();
}
protected Bitmap doInBackground(String... urls) {
bitmap = null;
for(String url : urls){
bitmap = downloadImage(url);
}
//List<Bitmap> bitmap = new ArrayList<Bitmap>;
// bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
return bitmap;
}
private Bitmap downloadImage(String arg0){
bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try{
stream = getHttpConnection(arg0);
bitmap = BitmapFactory.decodeStream(stream, null,bmOptions);
stream.close();
}catch(Exception e){
e.printStackTrace();
}
bitmapArray.add(bitmap);
return bitmap;
}
protected void onPostExecute(Bitmap result) {
if(result != null){
imageview.setImageBitmap(bitmap);
pDialog.dismiss();
}else{
pDialog.dismiss();
Toast.makeText(Monitor.this,"Failed in downloading the image", Toast.LENGTH_SHORT).show();
}
}
//creating open connection
private InputStream getHttpConnection(String urlString) throws IOException{
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if(httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
stream = httpConnection.getInputStream();
}
}catch(Exception e){
e.printStackTrace();
}
return stream;
}
}
}

Categories