簡體   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