[英]How to load an image from URL to Java Android? No error in code but it doesn't work
I'm working on a new Android Java program which brings two variables (String title and String imageUrl) then adds buttons named as the String (title).我正在开发一个新的 Android Java 程序,该程序带来两个变量(字符串标题和字符串 imageUrl),然后添加名为字符串(标题)的按钮。
When the user click on a button the application must load the image from the url in String (imageUrl).当用户单击按钮时,应用程序必须从 url 以字符串 (imageUrl) 加载图像。
The problem which I face is that none of the load images methodes worked with me!!我面临的问题是没有任何加载图像方法适用于我!
Although my project has no errors at all!!虽然我的项目完全没有错误!!
This is my code:这是我的代码:
public void start(String res) {
try {
JSONArray jarray = new JSONArray(jsonString);
for (int k = 0; k < jarray.length(); k++) {
JSONObject obj = jarray.getJSONObject(k);
Button btn = new Button(this);
btn.setText(obj.getString("title"));
final String link = obj.getString("link");
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openImage(link);
}
});
space.addView(btn);
dialog.dismiss();
}
} catch(Exception e) {
}
}
public void openImage(final String urk) {
dialog = ProgressDialog.show(this, "", "loading...", true);
new Thread(new Runnable() {
public void run() {
nextstepload(urk);
}
});
}
public void nextstepload(final String urk) {
try {
ImageView im = findViewById(R.id.img);
URL url = new URL(urk);
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
im.setImageBitmap(image);
dialog.dismiss();
} catch(IOException e) {
System.out.println(e);
}
}
And my Xml form is:我的Xml 表格是:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/displayer">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/img"/>
</LinearLayout>
</LinearLayout>
Notice: I read the previous writings about this subject on StackOverFlow but none of them helps me enough.注意:我在 StackOverFlow 上阅读了有关此主题的先前著作,但没有一篇对我有足够的帮助。 I may need a code suitable for my project especially.
我可能需要一个特别适合我的项目的代码。
Thanks very much非常感谢
Give it a try to Glide.试试 Glide。 https://github.com/bumptech/glide
https://github.com/bumptech/glide
You can load images like this:您可以像这样加载图像:
Glide
.with(context)
.load(YOUR URL HERE - AS STRING)
.placeholder(R.drawable.loading_spinner) // if you want some placeholder, it comes here
.into(myImageView); // The imageview reference.
You just forgot to Thread.start()
你只是忘了
Thread.start()
new Thread(new Runnable() {
public void run() {
nextstepload(urk);
}
}).start();
A Thread
object itself does nothing. Thread
object 本身什么也不做。 You must .start()
it after instantiated.实例化后必须
.start()
它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.