繁体   English   中英

如何在填充其他 EditTexts(线程)时让我的请求在后台运行?

[英]How can i make my request run in background while filling other EditTexts (Thread)?

我是线程新手,但我有一个 EditText 视图,只要它失去焦点,它就会使用来自 EditText 的用户输入填充带有图像徽标的 RecyclerView。 但是,每当用户离开焦点并调用该方法时,一切都会停止一段时间(这意味着我不擅长线程)。 如何改进此代码以使其平稳运行?

我的活动 class:

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 class:

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

这是我在评论中提到的如何使用回调实现它的示例。 为此,我们需要定义一个回调接口,我将其命名如下,为方便起见,您可以更改名称。

RequestConsumer是简单的 java 接口。

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

google请求线程class

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

添加项目活动class

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();


    }
}

注意我已经在文本编辑器中编写了它,因此代码需要一些 function 测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM