-1

I am trying to build an android application. I want to retrieve data from a website (.php) using JSON. So far I am able to get the recent post's title, URL and the the respective content but how can I retrieve image of that particular post? Thank you.

this is a piece of the code:

private TextView techPostCount, techPostTitle, techPostUrl, techPostContent, techPostAuthor 

private ImageView techImages;

.
.
.

int jsonArrLength = jsonMainNode.length();

            for(int i=0; i < jsonArrLength; i++) {

                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                String postTitle = jsonChildNode.getString("slug");
                String postUrl = jsonChildNode.getString("url");
                String postContent=jsonChildNode.getString("content");
                String postImage=jsonChildNode.getString("author");

                techcPostCount.setText("Number of posts:" +postCount);
                techPostTitle.setText("Page :" +postTitle);
                techPostUrl.setText("Page URL:" +postUrl);
                techPostContent.setText("Article:"+ postContent);

                techclinchPostImage?????("Picture:"+ ????);
Mike
  • 2,132
  • 3
  • 20
  • 33

2 Answers2

2

To display an image in an ImageView from a URI, you have to download the image first then put the downloaded image in the ImageView.

Or you can consider using Picasso to just let it do all this work for you

// context here can be the Activity or its application context
Picasso.with(context)
    .load(postImage)
    .into(techclinchPostImage);
Gorcyn
  • 2,807
  • 1
  • 20
  • 22
0

You can download Images in a separate Thread like this

 private class LoadImage extends AsyncTask<String, String, Bitmap> {
            ImageView img=null;
            public LoadImage(ImageView img){
                this.img=img;
            }
            @Override
            protected void onPreExecute() {
                super.onPreExecute();

            }
            protected Bitmap doInBackground(String... args) {
                Bitmap bitmap=null;
                try {
                    bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return bitmap;
            }
            protected void onPostExecute(Bitmap image) {
                if(img != null && image != null){
                    img.setImageBitmap(image);
                }
            }
        }`

add the above code to your project. and you call it like this

 ImageView techclinchPostImage =findViewbyId....
 new LoadImage(techclinchPostImage).execute("Your URL");
Gorcyn
  • 2,807
  • 1
  • 20
  • 22
Muthu
  • 1,022
  • 1
  • 7
  • 17