skip to Main Content

I wrote some code to search Images on Twitter by using hashtags and display the images inside my application.

Here my structure. I have a SearchView, if an user put some text into the SearchView, the Twitter4j Query search for it on Twitter. Then I parse the image urls from the results.

Now my question. How can i put the images from the urls into a imageView to display the picture behind the url?

Here my code:

/* Setup Configurationbuilder for Twitter4j API, build a searchquery for search Twitter,
   search Twitter with the search string from the SearchView
 */
public void searchTweets(String searchString) {

    //auth. the application by creating new ConfigurationBuilder
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setJSONStoreEnabled(true);
    cb.setOAuthConsumerKey("someSecretStuff");
    cb.setOAuthConsumerSecret("someSecretStuff");
    cb.setOAuthAccessToken("someSecretStuff");
    cb.setOAuthAccessTokenSecret("someSecretStuff");

    //start the search by build a new query
    TwitterFactory tf = new TwitterFactory(cb.build());
    final twitter4j.Twitter twitter = tf.getInstance();
    final Query query = new Query(searchString);

    //start a new Thread to evaluate the searchQuery
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                //get the results
                QueryResult result = twitter.search(query);
                //for each result print the user and the the messagetext
                for (Status status : result.getTweets()) {
                    twitter4j.MediaEntity [] media = status.getMediaEntities();
                    for (twitter4j.MediaEntity m : media) {
                        System.out.println(m.getMediaURL());
                    }
                }
            } catch (TwitterException e) {
                e.printStackTrace();
            }
        }
    }).start();
}

Update

Hey Folks,

thanks a lot for all your answers and hints. Now I know, how to get a image from the url but I still have problems to show it in my imageView. I want to implement a stack of pictures to slide them for like and dislike. So I make a loop that create a relativeLayout and an imageView inside for each item. Now i tried to put the images from url into the imageView but it didn’t work. The app starts and I see only a white screen.

Here is my Code:

//for each picture into the list...
    for (int i = 0; i < imageUrl.size(); i++) {

        //set RelativeLayout
        final RelativeLayout relView = new RelativeLayout(this);
        //set Params for the RelativeLayout
        relView.setLayoutParams(new RelativeLayout.LayoutParams((windowWidth - 80), windowHeight - 80));
        relView.setX(40);
        relView.setY(40);
        relView.setTag(i);
        //set BackgroundColor RelativeLayout
        relView.setBackgroundColor(Color.WHITE);

        String url = imageUrl.get(i);

        //set ImageView
        ImageView img = new ImageView(this);
        Picasso
                .with(this)
                .load(url)
                .resize(600, 200)
                .centerCrop()
                .into(img);
        //set params to RelativLayout
        img.setLayoutParams(new RelativeLayout.LayoutParams((windowWidth), windowHeight));
        //show image
        relView.addView(img);

        //create and set like stamp
        final Button imageLike = new Button(this);
        imageLike.setLayoutParams(new ActionBar.LayoutParams(100, 50));
        imageLike.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_stamp_like));
        imageLike.setX(20);
        imageLike.setY(80);
        imageLike.setAlpha(alphaValue);

        relView.addView(imageLike);

        //create and set dislike stamp
        final Button imagePass = new Button(this);
        imagePass.setLayoutParams(new ActionBar.LayoutParams(100, 50));
        imagePass.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_stamp_pass));
        imagePass.setX((windowWidth - 200));
        imagePass.setY(100);
        imagePass.setRotation(45);
        imagePass.setAlpha(alphaValue);

        relView.addView(imagePass);


        //create touchlistener for slide
        final int finalI = i;
        relView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //get screen coordinates
                x_cord = (int) event.getRawX();
                y_cord = (int) event.getRawY();

                //set coordinates to RelativeLayout
                relView.setX(x_cord - screenCenter + 40);
                relView.setY(y_cord - 650);

                switch (event.getAction()) {
                    //if picture slide down, nothing happens
                    case MotionEvent.ACTION_DOWN:
                        break;
                    //if pictures slide to side right, set rotation coordinates
                    //to RelativeLayout, set likes to 2
                    case MotionEvent.ACTION_MOVE:
                        x_cord = (int) event.getRawX();
                        y_cord = (int) event.getRawY();
                        relView.setX(x_cord - screenCenter + 40);
                        relView.setY(y_cord - 650);
                        if (x_cord >= screenCenter) {
                            relView.setRotation((float) ((x_cord - screenCenter) * (Math.PI / 32)));
                            if (x_cord > (screenCenter + (screenCenter / 2))) {
                                imageLike.setAlpha(1);
                                if (x_cord > (windowWidth - (screenCenter / 4))) {
                                    likes = 2;
                                } else {
                                    likes = 0;
                                }

                            } else {
                                likes = 0;
                                imageLike.setAlpha(0);
                            }
                            imagePass.setAlpha(0);
                        } else {

                            //Rotation
                            relView.setRotation((float) ((x_cord - screenCenter) * (Math.PI / 32)));
                            if (x_cord < (screenCenter / 2)) {
                                imagePass.setAlpha(1);
                                if (x_cord < screenCenter / 4) {
                                    likes = 1;
                                } else {
                                    likes = 0;
                                }
                            } else {
                                likes = 0;
                                imagePass.setAlpha(0);
                            }
                            imageLike.setAlpha(0);
                        }
                        break;
                    //if pictures moved up, picture were dropped to the primary position
                    case MotionEvent.ACTION_UP:
                        x_cord = (int) event.getRawX();
                        y_cord = (int) event.getRawY();

                        Log.e("X Point", "" + x_cord + " , Y " + y_cord);
                        imagePass.setAlpha(0);
                        imageLike.setAlpha(0);

                        //if like 0 nothing happens
                        if (likes == 0) {
                            Log.e("Event Status", "Nothing");
                            relView.setX(40);
                            relView.setY(40);
                            relView.setRotation(0);
                            //if like == 1 destroy RelativeLayout with the picture
                        } else if (likes == 1) {
                            Log.e("Event Status", "Passed");
                            imgContainer.removeView(relView);
                        } else if (likes == 2) {
                            //check and creat list
                            if (likeImageList == null) {
                                likeImageList = new ArrayList<>();
                            }
                            //add picture to list
                            LikedImage likedImage = new LikedImage();
                            likedImage.img = (BitmapFactory.decodeResource(getResources(), imageList[finalI]));

                            //save image as file
                            saveImageToExternalStorage(likedImage.img);
                            likeImageList.add(likedImage);
                            Log.e("Event Status", "Liked");
                            Log.e("Groeße der Liste", "" + likeImageList.size());
                            imgContainer.removeView(relView);
                        }
                        break;
                    default:
                        break;
                }
                return true;
            }
        });

        imgContainer.addView(relView);
    }

3

Answers


  1. You’ll have to download the image first.

    public static Bitmap loadBitmap(String url) {
        Bitmap bitmap = null;
        InputStream in = null;
        BufferedOutputStream out = null;
    
        try {
            in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
    
            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
            copy(in, out);
            out.flush();
    
            final byte[] data = dataStream.toByteArray();
            BitmapFactory.Options options = new BitmapFactory.Options();
            //options.inSampleSize = 1;
    
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
        } catch (IOException e) {
            Log.e(TAG, "Could not load Bitmap from: " + url);
        } finally {
            closeStream(in);
            closeStream(out);
        }
    
        return bitmap;
    }
    

    Then use the Imageview.setImageBitmap to set bitmap into the ImageView.

    Login or Signup to reply.
  2. use Picaso ..

    Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
    

    in your gradel

    compile 'com.squareup.picasso:picasso:2.5.2'
    
    Login or Signup to reply.
  3. its simple, you can use image loaders with lazyload capacity like glide:

    first add dependency to build.gradle

    dependencies {
        // glide
        compile 'com.github.bumptech.glide:glide:3.7.0'
    }
    

    then use it in your activity:

    String imgUrl = "http://yoururl.com";
    
    ImageView imageView = (ImageView) view.findViewById(R.id.thumbnail);
    
    Glide.with(mContext).load(imgUrl)
                    .thumbnail(0.5f)
                    .crossFade()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(imageView);
    

    Goodluck.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search