我是线程新手,但我有一个EditText视图,每当它失go 焦点时,它就会使用用户从EditText输入的图像徽标填充回收视图.但是,每当用户失go 焦点并调用该方法时,一切都会停止一段时间(这意味着我不擅长线程).如何改进此代码,使其能够顺利运行?
我的活动课:
public class addItem extends AppCompatActivity {
LoadingDialog loadingDialog;
RecyclerView imgList;
ArrayList<Bitmap> bitmapList = new ArrayList<>();
BitmapAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
/*
/ Code Unnecessary to the problem…
*/
et_title.setOnFocusChangeListener((v, hasFocus) -> {
if(!hasFocus){
getImageLogo(et_title.getText().toString());
}
});
}
@SuppressLint("NotifyDataSetChanged")
private void getImageLogo(String serviceName){
googleRequest googleList = new googleRequest(serviceName);
googleList.start();
try {
googleList.join();
} catch (InterruptedException e) {
Log.e("Interrupted Error","Thread Was Interrupted unexpectedly",e);
}
if(googleList.getImgRealList() != null) {
bitmapList.clear();
bitmapList.addAll(googleList.getImgRealList());
}else {
bitmapList.clear();
}
adapter.notifyDataSetChanged();
}
我的googleRequest类:
public class googleRequest extends Thread {
private ArrayList<Bitmap> imgRealList;
private final String keyword;
public googleRequest(String keyword){
this.keyword = keyword;
}
public ArrayList<Bitmap> getImgRealList() {
return imgRealList;
}
@Override
public void run() {
String newKeyword = keyword.toLowerCase(Locale.ROOT);
newKeyword = newKeyword.replace(' ','+');
String url = "https://www.google.gr/search?bih=427&biw=1835&hl=el&gbv=1&tbm=isch&og=&ags=&q="+ newKeyword;
try {
Document document = Jsoup.connect(url).get();
imgRealList = new ArrayList<>();
Elements imgList = document.select("img");
for (int i=1;i<imgList.size();i++) {
if(i==8)
break;
String imgSrc = imgList.get(i).absUrl("src");
InputStream input = new java.net.URL(imgSrc).openStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
imgRealList.add(bitmap);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}