[英]How to get Image from JSON using Glide
运行应用程序后出现错误,在这一行
String string=response.getString("url");
Android 工作室让我创建一个 try and catch mtd,但这不起作用。 正确的方法是什么?
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private void loadMeme() {
JSONObject obj = new JSONObject();
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://meme-api.herokuapp.com/gimme";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, null,
new Response.Listener < JSONObject > () {
@Override
public void onResponse(JSONObject response) {
String string = response.getString("url");
ImageView imageView = (ImageView) findViewById(R.id.shareImageView);
Glide.with(MainActivity.this).load(url).into(imageView);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
// Add the request to the RequestQueue.
queue.add(jsonObjectRequest);
}
尝试访问Main Thread
上的 UI 元素。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
// Block of code to try
loadMeme();
}
catch(Exception e) {
// Block of code to handle errors
System.out.println(e);
}
}
private void loadMeme() throws
{
JSONObject obj = new JSONObject();
RequestQueue queue = Volley.newRequestQueue(this);
String url ="https://meme-api.herokuapp.com/gimme";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url,null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
String string=response.getString("url");
ImageView imageView = (ImageView) findViewById(R.id.shareImageView);
Glide.with(MainActivity.this).load(url).into(imageView);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
// Add the request to the RequestQueue.
queue.add(jsonObjectRequest);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.