如何使用Retrofit 1.9从下面的响应中获取图像?

时间:2017-06-29 09:22:55

标签: android retrofit

我无法获取图片网址并在imageview中设置。如何使用Retrofit 1.9从下面的响应中获取图像? JSON响应如下:

{
"url": [
    "http://demo.in/url1/image/707/20170315063426.jpg",
    "http://demo.in/url2/image/707/374728.jpg"
],
"imagelist": [
    {
        "imageId": "1",
        "slipId": "707",
        "agentId": "6",
        "imageType": null,
        "slipImage": "20170315063426.jpg"
    },
    {
        "imageId": "2",
        "slipId": "707",
        "agentId": "6",
        "imageType": null,
        "slipImage": "374728.jpg"
    }
],
"slipId": "707",
"agentId": "6",
"message": "",
"success": "1"
}

我的代码如下为了从JSON获取响应,我不知道如何获取图像URL列表并在ImageView中设置:

public class MainActivity extends AppCompatActivity {

MyRecyclerView task_list;
MyAdapter mAdapter;
public static List<String> taskEmployeeLists;

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

    task_list=(MyRecyclerView)findViewById(R.id.task_list);


    task_list.setHasFixedSize(true);

    // use a linear layout manager
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(MainActivity.this);
    task_list.setLayoutManager(mLayoutManager);

    getListofTask();


}

private void getListofTask() {
    final ProgressDialog dialog;
    dialog = new ProgressDialog(MainActivity.this);
    dialog.setMessage("please wait....");
    dialog.setCanceledOnTouchOutside(false);
    dialog.show();

    Map<String, String> map = new HashMap<>();
    map.put("username","vishal" );
    map.put("password", "vishal");
    map.put("slipno", "707");

    ApiHandler.getApiService().signin(map, new Callback<Example>() {
        @Override
        public void success(Example feedcomment, Response response) {
            try {
                if (feedcomment.getSuccess().equals("1")) {
                    dialog.dismiss();
                    taskEmployeeLists = feedcomment.getUrl();
                    Log.e("Commentlistsize", taskEmployeeLists.size() + "");
                    try {
                        mAdapter = new MyAdapter((ArrayList<String>) feedcomment.getUrl());
                        task_list.setAdapter(mAdapter);
                        mAdapter.notifyDataSetChanged();
                    } catch (Exception e) {
                        Log.e("exception", e.toString());
                    }
                } else {
                    dialog.dismiss();
                    Log.e("status", "0");

                    task_list.setAdapter(null);

                }
            } catch (Exception e) {
                dialog.dismiss();
                Log.e("comment exception", e.toString());
            }
        }

        @Override
        public void failure(RetrofitError error) {
            dialog.dismiss();
            Log.e("retrofit_error", error.toString());
        }
    });
}

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
    private ArrayList<String> mDataset;


    public MyAdapter(ArrayList<String> url) {
        mDataset = url;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        // each data item is just a string in this case
        public View mainView;
        ImageView task_detail,task_discussion;

        public ViewHolder(View v) {
            super(v);
            mainView = v;

            task_detail = (ImageView) v.findViewById(R.id.task_detail);
        }
    }

    // Create new views (invoked by the layout manager)
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // create a new view
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_tasks_data, parent, false);

        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        // - get element from your dataset at this position
        // - replace the contents of the view with that element

        Picasso.with(getApplicationContext()).load(mDataset.get(position).getUrl().toString()).noFade().into(holder.task_detail);
    }
    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return mDataset.size();
    }
}
}

3 个答案:

答案 0 :(得分:2)

编辑:这是一个如何用Gson解析你的json的例子。您必须创建与您的json匹配的Pojos,并使用@SerializedName("fieldname")

注释字段

这是你的Pojos应该是什么样子(我删除了getter和setter)。演示:

public class Example {
    @SerializedName("url")
    private List<String> mUrls;

    @SerializedName("imagelist")
    private List<Imagelist> mImagelist;

    @SerializedName("slipId")
    private String mSlipId;

    @SerializedName("agentId")
    private String mAgentId;

    @SerializedName("message")
    private String mMessage;

    @SerializedName("success")
    private String mSuccess;
}

你的形象列表Pojo:

public class Imagelist {

    @SerializedName("imageId")
    private String mImageId;

    @SerializedName("slipId")
    private String mSlipId;

    @SerializedName("agentId")
    private String mAgentId;

    @SerializedName("imageType")
    private Object mImageType; // Fill in correct type - String maybe?

    @SerializedName("slipImage")
    private String mSlipImage;
}

构建Retrofit界面时,您必须添加GsonConverterfactory:

.addConverterFactory(GsonConverterFactory.create())

您的Retrofit界面应该有类似

的方法
@GET("your/path")
Example requestImageList();

您无法直接将网址传递给ImageView。我建议你使用图像处理库来完成这项工作,而不是直接使用Retrofit。示例包括PicassoGlide

这是毕加索的一个例子:

Picasso.with(context)
    .load(example.getImageList().get(0))
    .into(imageView);

这是Glide的一个例子:

GlideApp.with(context)
    .load(example.getImageList().get(0))
    .into(imageView);

答案 1 :(得分:0)

First of all you will have to parse the above response. Retrofit does this with Gson, 

new Retrofit.Builder()
                .baseUrl(BuildConfig.SERVER_URL)
                .client(client)
           .addConverterFactory(GsonConverterFactory.create(getGSonClient()))
                .build();


And get that response as a Model, from that model you can use the image URL

答案 2 :(得分:0)

您可以查看一些可用于将您的json转换为POJO的在线工具。

  1. http://www.freecodeformat.com/json2pojo.php
  2. http://pojo.sodhanalibrary.com