java 使用接口将数据传递给主线程

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 使用接口将数据传递给主线程相关的知识,希望对你有一定的参考价值。

//This is inside an asynctask

public interface AsyncResponse {
    void getKeywords(List<String> s);
    void getImageUrls(List<String> s);
}

AsyncResponse obj1=null;

//Inside the asynctask's postExecute method

protected void onPostExecute(List<String> strings) {
    super.onPostExecute(strings);
    if(url.equals("http://dev.theappsdr.com/apis/photos/keywords.php"))
        obj1.getKeywords(strings);
    else
        obj1.getImageUrls(strings);
}
//First of all, MainActivity implements the interface created in the asynctask
//Call the asynctask like this
APIparsing data = new APIparsing();
data.obj1 = MainActivity.this; //setMainActivity context for the interface object
data.execute("http://dev.theappsdr.com/apis/photos/keywords.php");

//The methods of the implemented interfaces should be defined here.
//These methods run on main thread and can be used to get data from the thread and access UI elements
@Override
public void getKeywords(List < String > s) {
    keywordsListSize = s.size();
    for (int index = 0; index < s.size(); index++) {
        keywordList.add(s.get(index));
    }
    keywordList.add("Select a Keyword");
    adapter = new ArrayAdapter < > (MainActivity.this, android.R.layout.simple_spinner_item, keywordList);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    Loading.dismiss();
}

@Override
public void getImageUrls(List < String > s) {

    if (s.get(0).equals("") && s.size() == 1) {
        img.setAlpha(0 f);
        Loading.dismiss();
        next.setEnabled(false);
        prev.setEnabled(false);
        Toast.makeText(MainActivity.this, "No Images found for this keyword.", Toast.LENGTH_LONG).show();
    } else {
        Loading.dismiss();
        imageList = s;
        Loading.setMessage("Loading Photo...");
        Loading.show();
        getImageAsync displayImage = new getImageAsync();
        displayImage.obj2 = MainActivity.this;
        displayImage.execute(imageList.get(i));
    }
}

以上是关于java 使用接口将数据传递给主线程的主要内容,如果未能解决你的问题,请参考以下文章

Android:如何将数据传递给子活动?

如何将数据传递给 kthread_run

从 tableviewcontroller 将数据传递给父 viewcontroller

将数据传递给 mdDialog

通过指针值将数据传递给 dll

Vue-Router 将数据传递给另一个组件