getting image from remote server issue - java

Just two things, is this a good simple way to grab images? also when i do try it on the android AVD nothing gets displayed on screen as well as in log_cat, no errors or crashes. Here is my code:
public class MainActivity extends Activity {
Bitmap bitmap = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
bitmap = getBitmap("https://twimg0-a.akamaihd.net/profile_images/2275552571/image_normal.jpg");
ImageView img = (ImageView) findViewById(R.id.img);
img.setImageBitmap(bitmap);
}catch(Exception e){
}
}
public Bitmap getBitmap(String bitmapUrl) {
try {
URL url = new URL(bitmapUrl);
return BitmapFactory.decodeStream(url.openConnection().getInputStream());
}catch(Exception ex) {return null;}
}
}

try : http://code.google.com/p/android-imagedownloader/ .
You can download remote images synchronously, Asynchronously, etc. it works really good
ImageDownloader imageDownloader = new ImageDownloader();
imageDownloader.setMode(ImageDownloader.Mode.CORRECT);
ImageView imageView = (ImageView) rowView.findViewById(R.id.picture);
imageView.setLayoutParams(new GridView.LayoutParams(140, 140));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(4, 4, 4, 4);
List<ImageSize> images = this.pictures.get(position).getImages();
imageDownloader.download(images.get(images.size()-3).getSource(), imageView);

It doesn't work because your picture's url starts with HTTPS. Try to use HttpGet. Something like that.

Related

Is there a way to use multiple sources for the same ImageView?

I'm trying to use an Activity which displays a random object from my array. This object is passed in from an intent.
I am trying to use an image for each of these objects and then display the correct image for the correct object.
So far I've been using the drawable folder to hold my images and then loading them in through the XML however this stops me using multiple images for the same ImageView.
I tried using imageview.setImageResource(R.drawable.imagename); but that doesn't seem to like loading in for some reason.
Do I need to make a new activity for each of the objects in this case?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_random_race);
TextView name = (TextView)findViewById(R.id.raceName);
Intent secondIntent = getIntent();
Race message = (Race)secondIntent.getSerializableExtra("RACE");
ImageView image = (ImageView) findViewById(R.id.raceImage);
image.setImageResource(R.drawable.hacan);
image.setImageBitmap(imageToBitmapImage(message, image));
name.setText(message.getName());
}
Bytes to Bitmap method
public Bitmap imageToBitmapImage (Race message, ImageView image){
Bitmap bmp;
try {
FileInputStream in = new FileInputStream(message.getImageName());
BufferedInputStream buffer = new BufferedInputStream(in);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int input = buffer.read();
while (input != -1){
baos.write(input);
input = buffer.read();
}
byte[] bytes = baos.toByteArray();
bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
return bmp;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Class of each object I'm talking about.
public class Race implements Serializable {
private String name;
private String imageName; //name of file within drawable
As #XavierFalempin commented, you can't access ressources through a file stream. Using setImageResource() should work. Following this answer your onCreate() method should look something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_random_race);
TextView name = (TextView)findViewById(R.id.raceName);
Intent secondIntent = getIntent();
Race message = (Race)secondIntent.getSerializableExtra("RACE");
ImageView image = (ImageView) findViewById(R.id.raceImage);
image.setImageResource(getResources().getIdentifier(message.getImageName(),
"drawable",
getPackageName()));
name.setText(message.getName());
}

Cannot resolve method 'getdrawable()

I'm a newbie in programming. I want to build a QR Code Generator that the QR Code can be saved or downloaded.
Here's my code for the generator:
public class GeneratorActivity extends AppCompatActivity {
EditText text;
Button gen_btn;
ImageView image;
String text2Qr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_generator);
text = findViewById(R.id.text);
gen_btn = findViewById(R.id.gen_btn);
image = findViewById(R.id.image);
gen_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text2Qr = text.getText().toString().trim();
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
try{
BitMatrix bitMatrix = multiFormatWriter.encode(text2Qr, BarcodeFormat.QR_CODE,200,200);
BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);
image.setImageBitmap(bitmap);
bitmap = ((BitmapDrawable) ImageView.getdrawable()).getBitmap();
}
catch (WriterException e){
e.printStackTrace();
}
}
});
}
}
I got a error that I cannot resolve method 'getdrawable()
anybody know how to fix this?
Here's the screenshot of the error: screenshot
get the drawable like from imageview like
Drawable myDrawable = imageView.getDrawable();
You can compare it with a drawable resource like
if(iv.getDrawable()==getResources().getDrawable(R.drawable.image1)){
//do work here
}
getDrawable
Return a drawable object associated with a particular resource ID and
styled for the specified theme.
You should pass OBJECT
bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
FYI
Drawable drawable = image.getDrawable();
You already have a bitmap and you have set it to imageview. Why do you need this line
bitmap = ((BitmapDrawable) ImageView.getdrawable()).getBitmap();
The error is saying that there is no method called getDrawable() in the ImageView class.
I think you can use it Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);directly. may be not need bitmap = ((BitmapDrawable) image.getdrawable()).getBitmap();
You are getting drawable from empty imageview that will return null. for getting bitmap from drawble, try this method.
public static Bitmap drawableToBitmap (Drawable drawable) {
Bitmap bitmap = null;
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if(bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}
Hope it will help you!!

Load Image File to Image View

So, I'm (still) trying to build a simple camera app and what I have so far is an Image Controller which is able to take a picture, save it into the storage and pass the filepath with an intent to another activity.
In my new activity the first step I'm tying to achieve is, to get my final Image loaded into an ImageView, so I did the following:
ImageView finalImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_after);
Intent getIntent = getIntent();
String filePath = getIntent.getExtras().getString("filePath");
File imgFile = new File(filePath);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
finalImage = (ImageView) findViewById(R.id.finalImage);
finalImage.setImageBitmap(myBitmap);
}
But, its not working, and I dont quite unterstand why not... :( The Activity starts completely fine, but the ImageView just does nothing.
There are few things you must know in the process of saving Image in Android
ccv2WithPreview.takePicture();
In this line the method executed is
public void takePicture() {
try {
// This is how to tell the camera to lock focus.
mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_START);
// Tell #mCaptureCallback to wait for the lock.
mState = STATE_WAITING_LOCK;
mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback, backgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
Toast.makeText(activity.getApplicationContext(), file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
}
In this method, capture() call is asynchronous. Since you are ending the activity soon after calling it and starting new Activity, so by the time your code saves the Image in Image Saver, you are starting new Activity already and your file is not yet ready.
You button implementation works because by the time you click button, Image will be saved.
To solve this problem,
CameraHelper.java
public interface CameraHelper{
void fileSaved(String filePath);
}
MainActivity.java
public class MainActivity extends AppCompatActivity
implements SensorEventListener, ActivityCompat.OnRequestPermissionsResultCallback, CameraHelper{
...
#Override
public void fileSaved(String file){
Intent intent = new Intent(this, AfterActivity.class);
intent.putExtra("filePath", file);
startActivity(intent);
finish();
}
}
in onCreate of MainActivity
ccv2WithPreview = new CameraControllerV2WithPreview(MainActivity.this, textureView, MainActivity.this);
in your camera class
private CameraHelper cameraHelper; //Initialize in constructor
Then in ImageSaver
private boolean imageSaved = false;
public void run() {
if(!imageSaved) {
ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
try (FileOutputStream output = new FileOutputStream(mFile)) {
output.write(bytes);
imageSaved = true;
cameraHelper.fileSaved(mFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
} finally {
mImage.close();
}
}
}
This is how you must handle any Asynchronous tasks you get in future. Callback based implementations.
Can you try to invalidate() the ImageView after setting the bitmap?
(I'm pretty much guessing here, but working with GUIs a couple of years ago, i remember that if a view changed you have to tell the view to about it, so that it can be redrawn.)
Please also see: How to refresh image view immediately

load Imge from my server error android studio

I'm trying to load some images from my server to New App, but i don't have any result :
This is my MainActivity code :
import java.io.InputStream;
import static android.net.Uri.parse;
public class MainActivity extends Activity {
private ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadImageTask((ImageView)findViewById(R.id.loadimg)).execute(getString(R.string.link));
private class DownloadImageTask extends AsyncTask<String,Void,Bitmap>{
private final ImageView bmImage;
ImageView bmImg;
public DownloadImageTask (ImageView bmImage){
this.bmImage=bmImage;
}
protected Bitmap doInBackground (String...urls){
String underplay = urls[0];
Bitmap mIcon11 =null;
try {
InputStream in =new java.net.URL(underplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e){
Log.e("Error",e.getMessage());
e.printStackTrace();
}
return mIcon11 ;
}
}
The Result in emulator is not appear any thing just my Button ?
Add the following dependency to your build.gradle file under app:
dependencies {
compile 'com.squareup.picasso:picasso:2.3.2'
}
Then in your code you can simply load a bitmap or image from a server like so:
Picasso.with(this)
.load(IMAGE_URL)
.into(yourImageView);
Where this is the activity context. IMAGE_URL is the url of the image, example: http://yourapi.com/image_1034.png, and yourImageView is the ImageView, ImageButton, or other Custom View where you want to upload the image into.
Doing it this way is considered best practice, and reduces a lot of the boilerplate code you've written. Try building a scalable app writing AsyncTasks for every time you upload a Bitmap.
In your AsyncTask you need to implement:
protected void onPostExecute(Bitmap icon) {
iv.setImageBitmap(icon)
}
Can you try this code?
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.image);

Why aren't my images downloading into ImageViews?

I'm pretty new to native Android development. What my app is currently doing:
Download a JSON of image urls from our server
Add an ImageView to a ListView for each image
I've gotten the JSON and am now working on using an ImageAdapter (extends BaseAdapter) to populate the ListView, but I'm running into an error:
I'm getting println needs a message during creation of the InputStream in my OpenHttpGETConnection function.
Here's my code (in order of highest to lowest with unnecessary code removed):
Once JSON Is loaded my onPostExecute code'll run to start the adapter:
private class DownloadImagesTextTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls){
return getImages(urls[0]);
}
#Override
protected void onPostExecute(String result){
JSONArray images = null;
images = new JSONArray(result);
// TURN images into array of imageviews
ListView listView = (ListView) findViewById(R.id.list);
#here----> listView.setAdapter(new ImageAdapter(getBaseContext(), images));
Log.d("DownloadTextTask", images.toString());
}
}
Here's my ImageAdapter code:
public class ImageAdapter extends BaseAdapter {
private Context context;
private JSONArray images;
public ImageAdapter(Context c, JSONArray i){
context = c;
images = i;
}
// returns an imageview view
public View getView(int position, View convertView, ViewGroup parent){
ImageView imageView = new ImageView(context);
try {
String url = "http://www.example.com/" + images.get(position);
#here----> imageView.setImageBitmap(getImageBitmap(url));
} catch (Exception e){
Log.d("LoadImage", e.getLocalizedMessage());
}
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
return imageView;
}
}
Here's my getImageBitmap function:
private Bitmap getImageBitmap(String url){
Bitmap bitmap = null;
InputStream in = null;
try {
#here----> in = OpenHttpGETConnection(url);
} catch (Exception e) {
#i_get
#this ----> Log.wtf("OpenGET", e.getMessage() + ": " + url );
#error
}
bitmap = BitmapFactory.decodeStream(in);
in.close();
return bitmap;
}
And finally, here's my OpenHttpGETConnection function:
public static InputStream OpenHttpGETConnection(String url){
InputStream inputStream = null;
HttpClient httpClient = null;
HttpResponse httpResponse = null;
httpClient = new DefaultHttpClient();
httpResponse = httpClient.execute(new HttpGet(url));
inputStream = httpResponse.getEntity().getContent();
return inputStream;
}
And here's the pertaining LogCat line: (Happens for 3 images that came through the JSON file)
A/OpenGET﹕ println needs a message: http://www.example.com/image1.jpg
The weird thing is, I use the same OpenHttpGETConnection when I load my JSON data, so I'm pretty sure that's returning a correct InputStream object. Are there some caveats when using it for text vs. binary data (jpg)?
Thanks in advance!
First of all in the adapter, in the getView() method, you're not recycling the items. Have a look on the ViewHolder pattern (http://www.javacodegeeks.com/2013/09/android-viewholder-pattern-example.html).
Then, getImageBitmap() seems to be executed on the same thread, I wonder why it doesn't crash. I guess there you download the actual image. It should be done asynchronously, and you should send a reference of the ImageView and when the download is finished you should load it into it. Of course you'll have to care about if when you put the bitmap inside the ImageView you have the good ImageView on the screen (because it might have been recycled).
To get rid of all these concerns you could just use Picasso library (http://square.github.io/picasso/) and that will do all this for you.

Categories