修改依赖线程 API 调用的文本视图?

Modifying textviews reliant on threaded API calls?

public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = LayoutInflater.from(getContext());
    View theView = inflater.inflate(R.layout.match_layout, parent, false);
     matchID = getItem(position);

    TextView championName = (TextView) theView.findViewById(R.id.championNameText);
    new Thread(
            new Runnable() {
                public void run() {
                    selectedMatch = RiotAPI.getMatch(matchID);
                    Log.i(TAG, String.valueOf(selectedMatch)); // <-- returns the matches properly
                }
            }).start();

        championName.setText(String.valueOf(selectedMatch.getDuration()));


   // Log.i(TAG, String.valueOf(selectedMatch));  <-- returns nulls
    return theView;
}

我在尝试制作我的第一个应用程序时遇到了一个又一个问题 运行。我的理解是我不允许在主线程中进行 api 调用,所以我尝试使用单独的线程。问题是,API 到 return 数据需要几秒钟,所以当我尝试更新我的文本视图时,selectedMatch 为空,出现空指针异常。处理此问题的正确方法是什么?

编辑:到目前为止我发现的唯一解决方法是放置一个空的 while 循环等待线程先完成,但这似乎效率很低。将不胜感激。

    public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = LayoutInflater.from(getContext());
    View theView = inflater.inflate(R.layout.match_layout, parent, false);
     matchID = getItem(position);

    TextView championName = (TextView) theView.findViewById(R.id.championNameText);
    new Thread(
            new Runnable() {
                public void run() {
                    selectedMatch = RiotAPI.getMatch(matchID);
                    Log.i(TAG, String.valueOf(selectedMatch)); // <-- returns the matches properly
                }
            }).start();
     while (selectedMatch == null)
             {
             }
        championName.setText(String.valueOf(selectedMatch.getDuration()));


   // Log.i(TAG, String.valueOf(selectedMatch));  <-- returns nulls
    return theView;
}

尝试使用 runOnUiThread():

new Thread(
        new Runnable() {
            public void run() {
                selectedMatch = RiotAPI.getMatch(matchID);
                ((YourActivity)getContext()).runOnUiThread(new Runnable(){

               public void run(){
                   championName.setText(String.valueOf(selectedMatch.getDuration()));
               }

         });

        }
     }).start();