我是线程新手,但我有一个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();
        }
    }
}

推荐答案

这是一个如何使用回调实现它的示例,正如我在 comments 中提到的.为此,我们需要定义一个回调函数,我将其命名为下面的函数,为了方便起见,您可以更改名称.

RequestConsumer它是简单的java接口.

/// Must be executed in the UI (main) thread.
@MainThread
public interface RequestConsumer {
    void onRequestResult(List<Bitmap> bitmaps);
}

googleRequest螺纹等级.

public class googleRequest extends Thread {

    private ArrayList<Bitmap> imgRealList;
    private final String keyword;
    /*
    We will use the request consumer callback in order to deliver the results
    to the UI from background. Since we need to touch the UI by this callback
    we ensure that it will execute within the UI thread's queue using the
    uiHandler.
    */
    private final RequestConsumer requestConsumer;
    private final Handler uiHandler = new Handler(Looper.getMainLooper());

    public googleRequest(@NonNull String keyword, @NonNull RequestConsumer requestConsumer){
        this.keyword = keyword;
        this.requestConsumer = requestConsumer;
    }

    @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);
            }

            // I think according to your code; the data you've requested is ready
            // to deliver from now on. But attention! we post it to execute it in the UI thread
            uiHandler.post(() -> requestConsumer.onRequestResult(imgRealList));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

addItem活动类

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, images -> {
            // Here we get the delivered results in this callback
            if(images != null) {
                bitmapList.clear();
                bitmapList.addAll(images);
            }else {
                bitmapList.clear();
            }
            adapter.notifyDataSetChanged();
        });
        googleList.start();


    }
}

Note我在文本编辑器中编写了它,因此代码需要一些功能测试.

Java相关问答推荐

在Java中使用带限制的回归打印星形三角形

Spring Jpa findById会导致StackOverFlow错误,但其他查询没有问题

RDX触发ChoiceBox转换器(并按字符串值排序)

日食IDE 2024-03在Ubuntu下崩溃,导致hr_err_pid.log

int Array Stream System. out. print方法在打印Java8时在末尾添加% sign

使用标记时,场景大纲不在多个线程上运行

基本时态运算的ISO-8601周数据表示法

使用Testcontainers与OpenLiberty Server进行集成测试会抛出SocketException

JavaFX如何在MeshView中修复多个立方体?

如何将其他属性引用到log4j2 yaml配置中?

如何在JavaFX中处理多个按钮

继续收到错误SQLJDBC EXCEPTION执行";org.springframework.dao.InvalidDataAccessResourceUsageException:&

JNI:将代码打包成自包含的二进制文件

在Oracle JDBC连接中,连接失效和身份验证失效是什么意思?

基于配置switch 的@Controller的条件摄取

无法使用Java PreparedStatement在SQLite中的日期之间获取结果

为什么我不能建立输入/输出流?Java ServerSocket

Oracle中从JSON中提取和插入数据

为什么创建Java动态代理需要接口参数

如何在Spring Security中设置一个任何人都可以打开的主页?