0

from JSON URL I have fetched String avatar = jsonObject.getString("avatar_url"); this object to show the image in the list but I have no idea how to show the image from the URL in the UI.

I have tried somthing but that code doesn't work...

list_item.xml

<LinearLayout
android:padding="15dp"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">

    <ImageView
        android:id="@+id/avatar"
        tools:src="@mipmap/ic_launcher"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />



    <LinearLayout
        android:paddingLeft="15dp"
        android:orientation="vertical"
        android:layout_height="match_parent"
        android:layout_width="match_parent">
<TextView
    android:id="@+id/login"
    tools:text="USER_LOGIN"
    android:textSize="18sp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
<TextView
    android:paddingTop="2dp"
    android:id="@+id/type"
    tools:text="USER_TYPE"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
    </LinearLayout>

</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private static String LOG_TAG = MainActivity.class.getSimpleName();
    private static String JSON_URL = "https://api.github.com/users";

    UserAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        ListView listView = (ListView)findViewById(R.id.list);
        // Create a new adapter that takes an empty list of earthquakes as input
        mAdapter = new UserAdapter(this, new ArrayList<User>());

        listView.setAdapter(mAdapter);

        UserAsync task = new UserAsync();
        task.execute(JSON_URL);

    }



    private class UserAsync extends AsyncTask<String,Void,List<User>>{

        @Override
        protected List<User> doInBackground(String... urls) {

            if(urls.length <1 || urls[0] == null){
                return null;
            }

            List<User> result = null;
            try {
                result = QueryUtils.fetchJson(urls[0]);
            } catch (JSONException e) {
                Log.e(LOG_TAG,"Error in fetching json",e);
            }


            return result;
        }

        @Override
        protected void onPostExecute(List<User> users) {
            // Clear the adapter of previous earthquake data
            mAdapter.clear();

            // If there is a valid list of {@link user}s, then add them to the adapter's
            // data set. This will trigger the ListView to update.

            if(users != null && !users.isEmpty()){
                mAdapter.addAll(users);
                // After adding user to the adapter, Notify adapter for UI update
                mAdapter.notifyDataSetChanged();
            }
        }
    }

}

QueryUtils()

public class QueryUtils {

    private static final String LOG_TAG = QueryUtils.class.getSimpleName();

    public QueryUtils() {
    }



    /**
     * Query the github dataset and return a list of {users} objects.
     */

    public static List<User> fetchJson(String requestUrl) throws JSONException {
        //create URL object
        URL url = createUrl(requestUrl);

        //perform http request to the URL and receive a json
        String jsonResponse = null;
        try {
            jsonResponse = makeHttpRequest(url);

        } catch (IOException e) {
            Log.e(LOG_TAG,"problem in making http request",e);
        }

        // Extract relevant fields from the JSON response and create a list of {@link Users}
        List<User> users = extractFromJson(jsonResponse);

        //return list of {@link Users}
        return users;
    }


    /**
     * Returns new URL object from the given string URL.
     */
    private static URL createUrl(String stringUrl){
        URL url = null;
        try {
            url = new URL(stringUrl);
        } catch (MalformedURLException e) {
            Log.e(LOG_TAG,"Error in creating url",e);
        }
        return url;
    }

    /**
     * Make an HTTP request to the given URL and return a String as the response.
     */

    private static String makeHttpRequest(URL url) throws IOException{
        String jsonResponse = "";

        //If url is null return early
        if(url == null){
            return jsonResponse;
        }

        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;

        try{
            urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.setReadTimeout(10000);
            urlConnection.setConnectTimeout(15000);
            urlConnection.setRequestMethod("GET");

            if(urlConnection.getResponseCode() == 200){
                inputStream = urlConnection.getInputStream();
                jsonResponse = readFromStream(inputStream);
            }else {
                Log.e(LOG_TAG,"Error response code: " + urlConnection.getResponseCode());
            }
        }catch (IOException e){
            Log.e(LOG_TAG,"Problem in retrieving the json response",e);
        }finally {
            if (urlConnection != null){
                urlConnection.disconnect();
            }
            if (inputStream != null){
                inputStream.close();
            }
        }

        return jsonResponse;
    }


    /**
     * Convert the {@link InputStream} into a String which contains the
     * whole JSON response from the server.
     */

    private static String readFromStream(InputStream inputStream) throws IOException {
        StringBuilder output = new StringBuilder();

        if (inputStream != null){
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line = reader.readLine();
            while (line != null){
                output.append(line);
                line = reader.readLine();
            }
        }
        return output.toString();
    }

    private static List<User> extractFromJson(String user) throws JSONException {
        // If the JSON string is empty or null, then return early.
        if (TextUtils.isEmpty(user)) {
            return null;
        }

        // Create an empty ArrayList that we can start adding earthquakes to

        List<User> users = new ArrayList<>();

        try{
            JSONArray array = new JSONArray(user);
            for (int i = 0; i<array.length(); i++){
                JSONObject jsonObject = array.getJSONObject(i);

                String login = jsonObject.getString("login");

                String type = jsonObject.getString("type");

                String avatar = jsonObject.getString("avatar_url");

                User user1 = new User(login,type,avatar);

                users.add(user1);

            }

        }catch (JSONException e){
            Log.e(LOG_TAG,"Problem in parsing user",e);
        }


        return users;
    }
}

UserAdapter.java

public class UserAdapter extends ArrayAdapter<User>{

    public UserAdapter(@NonNull Context context, @NonNull List<User> objects) {
        super(context, 0, objects);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        View listView = convertView;
        if (listView == null){
            listView = LayoutInflater.from(getContext()).inflate(R.layout.list_item,parent,false);
        }

        User currentUser = getItem(position);

        TextView login = (TextView)listView.findViewById(R.id.login);
        login.setText(currentUser.getUser_login());

        TextView type = (TextView) listView.findViewById(R.id.type);

        type.setText(currentUser.getType());

        ImageView avatar = (ImageView)listView.findViewById(R.id.avatar);
        avatar.setImageResource(Integer.parseInt(currentUser.getUrl()));



        return listView;
    }
}

User.java

public class User {

    private String user_login;
    private String type;
    private String url;


    public User(String user_login, String type, String url) {
        this.user_login = user_login;
        this.type = type;
        this.url = url;
    }

    public String getUser_login() {
        return user_login;
    }

    public String getType() {
        return type;
    }

    public String getUrl() {
        return url;
    }
}
Shubham Kumar
  • 295
  • 3
  • 13

5 Answers5

0

Instead of setImageResource you need to use any of the library to load image from URL.

For E.G.

You can use Picasso or Glide to load images. You can use something like below.

First of all setup Picasso library.

compile 'com.squareup.picasso:picasso:2.5.2'

Sample code.

ImageView avatar = (ImageView)listView.findViewById(R.id.avatar);
Picasso.with(context).load(currentUser.getUrl()).into(avatar);

Make sure you have the URL value inside currentUser.getUrl() in adapter.

Jay Rathod
  • 11,131
  • 6
  • 34
  • 58
0

Use Picasso library to set image from url.

add this in your gradle :

compile 'com.squareup.picasso:picasso:2.5.2'

Use following code to set image to imageview using picasso:

if (currentUser.getUrl() != null) {
                Picasso.with(getActivity()).load(currentUser.getUrl()).placeholder(R.drawable.progress_animator).error(drawable).resize(100, 100).into(profilepic);
            } else {

                profilepic.setImageDrawable(drawable);

            }
sandeep kolhal
  • 393
  • 1
  • 4
  • 14
0

You can use Picasso for loading image.

build.gradle

implementation 'com.squareup.picasso:picasso:2.3.2'

Adapter.java

Picasso.with(context).load(currentUser.getUrl()).into(imageView);

https://www.learn2crack.com/2016/02/image-loading-recyclerview-picasso.html

Arya
  • 1,729
  • 3
  • 17
  • 35
0

To set image you need to use Pissaco-
Instead of below code:

 ImageView avatar = (ImageView)listView.findViewById(R.id.avatar);
 avatar.setImageResource(Integer.parseInt(currentUser.getUrl()));

Use Picasso as

Picasso.with(context).load(currentUser.getUrl()).into(avatar);

It will pretty work fine.

0

You can try Glide. Add this to your app build.gradle:

implementation 'com.github.bumptech.glide:glide:4.3.0'

Use it like this:

Bitmap bitmap = Glide.with(this)
                     .load("http://....")
                     .asBitmap()
                     .into(100, 100)
                     .get();
Jai Prak
  • 2,855
  • 4
  • 29
  • 37