试图从json url获取图像但应用程序崩溃

时间:2018-02-06 05:17:15

标签: android json image

来自JSON URL我已经获取 String avatar = jsonObject.getString(“avatar_url”); 此对象以显示列表中的图像,但我不知道如何显示URL中的图像在用户界面。

我尝试了一些东西,但代码不起作用......

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;
    }
}

5 个答案:

答案 0 :(得分:0)

您需要使用任何库从URL加载图片,而不是 setImageResource

对于E.G。

您可以使用 Picasso Glide 来加载图片。你可以使用下面的东西。

首先设置 Picasso 库。

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

示例代码。

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

确保适配器中的currentUser.getUrl()内有URL值。

答案 1 :(得分:0)

使用Picasso库从网址设置图片。

在你的gradle中添加:

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

使用以下代码使用毕加索将图像设置为imageview:

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);

            }

答案 2 :(得分:0)

您可以使用Picasso来加载图片。

的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

答案 3 :(得分:0)

要设置图像,您需要使用Pissaco-
而不是代码:

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

使用Picasso作为

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

它会很好用。

答案 4 :(得分:0)

您可以尝试Glide。将其添加到您的应用build.gradle

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

像这样使用:

Bitmap bitmap = Glide.with(this)
                     .load("http://....")
                     .asBitmap()
                     .into(100, 100)
                     .get();