将图像加载到listview api中

时间:2016-10-24 18:42:23

标签: android image listview okhttp3

目前我正在尝试将图片加载到列表视图中。它的设置方式是我设置对象的所有属性,如名称位置等。其中一个恰好是图像。目前,每次我设置图像时,我都会调用一个转到URL的方法,我必须使用标记来检索图像。一旦我检索它,将变量Bitmap图像设置为我刚刚获得的图像。

这是超级慢,看起来很糟糕。我看了一些第三方,但他们直接加载到图像视图中,我需要设置一个对象来获取该图像,因为我不断重复使用它也需要进行操作。

public class conversationsFragment extends Fragment {
private String currentUserId;
private ArrayAdapter namesArrayAdapter;
//private ArrayList<String> names;
//private ListView usersListView;
private RecyclerView usersListView;
String names[] = {"Anant Kharod, MD", "Mustafa Ahmed, MD"};
String msg[] = {"What time do you want to get started adding more stuff go over the line", "Presentation is tomorrow"};
boolean readUnread [] = {false,false};
public static int [] images={R.drawable.msgone,R.drawable.msgtwo};

ArrayList<MessageData> arrMessageData; //= new ArrayList<MessageData>();
//CustomAdapterConversations adapter;
conversationRecyclerViewAdapter adapter;
Bitmap image;


public conversationsFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_conversations, container, false);
rootView.findViewById(R.id.conversationsListView);
        usersListView = (RecyclerView) rootView.findViewById(R.id.conversationsListView);




    callApi();


    return rootView;

}

private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case 1:
                adapter = new conversationRecyclerViewAdapter(getActivity().getBaseContext(), arrMessageData);
                usersListView.setAdapter(adapter);
                LinearLayoutManager layoutManager
                        = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
                usersListView.setLayoutManager(layoutManager);
                break;
            default:
                Log.d("TAG", msg.what + " ? ");
                break;
        }
    }
};

private void callApi() {
    String username, passowrd;
    username = "user";
    passowrd = "passwd";
    //OkHttpClient client = new OkHttpClient.Builder().addNetworkInterceptor(new StethoInterceptor()).build();


    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new BasicAuthInterceptor()).addNetworkInterceptor(new StethoInterceptor()).build();

    String credentials = "ezhu:Ccare@123";
    String auth = "Basic "
            + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

    Log.e("Test", auth);


    //SharedPreferences preferences = this.getActivity().getSharedPreferences("token", Context.MODE_PRIVATE);

    SharedPreferences settings = PreferenceManager
            .getDefaultSharedPreferences(getActivity());
    String auth_token_string = settings.getString("token", ""/*default value*/);
    String auth_token_type = settings.getString("tokenType", "");
    String userId = settings.getString("userId", "");

    Log.i("prefs", auth_token_type);



    String url  = "https://staging.vitalengine.com/portal-api/api/user/inbox/list?userId=" +
            userId +
            "&folderId=-1&tagId=0&page=1&itemPerPage=1000&showMsgInFolder=false";


    Request request = new Request.Builder().url(url)
            .addHeader("Authorization", auth_token_type + " " + auth_token_string)
            .addHeader("user-tz", "-330")
                    //.addHeader("Content-Type", "application/json")
            .build();




    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
           // Log.i(TAG, "call api error");
            Log.e("Volley", e.toString());
        }

        @Override
        public void onResponse(Call call, okhttp3.Response response)  {

            try {
                if (!response.isSuccessful())
                    throw new IOException("Unexpected code " + response);
                final String body = response.body().string();

                //final String jsonData = response.body().string();
                JSONObject Jobject = new JSONObject(body);




//JSONArray Jarray = Jobject.getJSONArray("inboxMsgList");
                JSONObject sub = Jobject.getJSONObject("response");
                JSONArray Jarray = sub.getJSONArray("inboxMsgList");

                //Log.e("Array", String.valueOf(Jarray.length()));




                arrMessageData = new ArrayList<>();

                for (int i = 0; i < Jarray.length(); i++) {
                    JSONObject object = Jarray.getJSONObject(i);

                    if (object.get("messageType").equals("CONVERSATION")) {

                        //String time = object.get("conversationDate");

                        Log.e("ConversationTest", object.getString("fromUser"));

                        MessageData msg3 = new MessageData();
                        msg3.setName((String) object.get("fromUser"));
                        msg3.setMessage((String) object.get("message"));
                        getImage((String) object.get("photo"));
                        msg3.setImage(image);
                        msg3.setRead(true);
                        msg3.setSubject((String) object.get("subject"));
                        msg3.setType((String) object.get("conversationDate"));
                        msg3.setId((Integer) object.get("conversationId"));

                        arrMessageData.add(msg3);
                    } else {
                        //Log.e("DetailObject", object.getString("fromUser"));
                    }


                    //Log.e("DetailObject", object.getString("fromUser"));
                    //Log.e("DetailObject", msg3.getName());

                    handler.sendEmptyMessage(1);

                }


                // Log.e("FullJsonReply", body.toString());
            } catch (Exception e) {
                //Log.e("Volley2", e.toString());
            }

        }


    });
}
public void getImage(String id) throws IOException {

    String credentials = "ezhu:Ccare@123";
    String auth = "Basic "
            + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

    Log.e("Test", auth);


    //SharedPreferences preferences = this.getActivity().getSharedPreferences("token", Context.MODE_PRIVATE);

    SharedPreferences settings = PreferenceManager
            .getDefaultSharedPreferences(getActivity());
    String auth_token_string = settings.getString("token", ""/*default value*/);
    String auth_token_type = settings.getString("tokenType", "");
    String userId = settings.getString("userId", "");

    Log.i("prefs", auth_token_type);




    URL imgurl = new URL("https://staging.vitalengine.com/portal-api/" + id);
    URLConnection conn = imgurl.openConnection();
    conn.addRequestProperty("Authorization", auth_token_type + " "+ auth_token_string);
    conn.connect();

    InputStream in = conn.getInputStream();

    Bitmap bmp = BitmapFactory.decodeStream(in);



}

}

这是它的GIF http://g.recordit.co/gGlG99jWm9.gif

1 个答案:

答案 0 :(得分:0)

试试这个Lib Android-Universal-Image-Loader

  1. 并设置为缓存在内存和鸡巴。Configuration Linked

  2. 用法:

  3. ImageLoader imageLoader = ImageLoader.getInstance(); // Get singleton instance // Load image, decode it to Bitmap and display Bitmap in ImageView (or any other view // which implements ImageAware interface) imageLoader.displayImage(imageUri, imageView);