在doInBackground之后如何更新recyclerView项目

时间:2019-01-02 14:16:13

标签: android android-recyclerview observable observer-pattern

我在我的应用程序中使用recyclerView,在其中计算UI线程以外的其他线程中城市之间的路线距离。现在,我只想在计算距离时刷新recyclerView的distance字段。 TIA

public class DashboardAdapter extends RecyclerView.Adapter<DashboardAdapter.ListItemViewHolder> {

private List<DashBoardData> dashBoardData;
private Context context;

public DashboardAdapter(List<DashBoardData> dashBoardData, Context context) {
    if (dashBoardData == null) {
        throw new IllegalArgumentException("Data must not be null");
    }
    this.dashBoardData = dashBoardData;
    this.context = context;
}

@NonNull
@Override
public ListItemViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_layout, viewGroup, false);
    return new ListItemViewHolder(itemView);
}

@Override
public void onBindViewHolder(@NonNull ListItemViewHolder holder, int position) {

    holder.tvSource.setText(dashBoardData.get(position).getSource());
    holder.tvDestination.setText(dashBoardData.get(position).getDestination());

    getDistance(context,
            dashBoardData.get(position).getStartLocation(),
            dashBoardData.get(position).getEndLocation());
    holder.tvDistance.setText("");
}

@Override
public int getItemCount() {
    return dashBoardData.size();
}


public final static class ListItemViewHolder extends RecyclerView.ViewHolder {
    TextView tvSource, tvDestination, tvDistance;

    public ListItemViewHolder(View itemView) {
        super(itemView);

        tvSource = (TextView) itemView.findViewById(R.id.tv_from_source);
        tvDestination = (TextView) itemView.findViewById(R.id.tv_to_destination);
        tvDistance = itemView.findViewById(R.id.tv_distance);

    }
}

public static void getDistance(Context context, String srcLocation, String destLocation) {
    String url = getDirectionsUrl(context, srcLocation, destLocation);
    DownloadTask downloadTask = new DownloadTask();
    downloadTask.execute(url);
}

public static class DownloadTask extends AsyncTask<String, Void, String> {

    // Downloading data in non-ui thread
    @Override
    protected String doInBackground(String... url) {

        String data = "";
        try {
            // Fetching the data from web service
            String urlEncoded = (url[0]).replaceAll(" ", "");
            data = downloadUrl(urlEncoded);
        } catch (Exception e) {
            Log.d("Background Task", e.toString());
        }
        return data;
    }

    // Executes in UI thread, after the execution of
    // doInBackground()
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        ParserTask parserTask = new ParserTask();
        // Invokes the thread for parsing the JSON data
        parserTask.execute(result);
    }
}

private static String downloadUrl(String strUrl) throws IOException {
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(strUrl);
        urlConnection = (HttpURLConnection) url.openConnection();

        // Connecting to url
        urlConnection.connect();

        // Reading data from url
        iStream = urlConnection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

        StringBuffer sb = new StringBuffer();

        String line = "";
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        data = sb.toString();

        br.close();

    } catch (Exception e) {
        Log.d("Exception downloading url", e.toString());
    } finally {
        if (iStream != null) {
            iStream.close();
        }
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    return data;
}

private static class ParserTask extends AsyncTask<String, Integer, String> {

    @Override
    protected String doInBackground(String... jsonData) {

        JSONObject jObject;
        String distance = "0 Mt";

        try {
            jObject = new JSONObject(jsonData[0]);

            JSONArray jRoutes = null;
            JSONArray jLegs = null;

            jRoutes = jObject.getJSONArray("routes");

            for (int i = 0; i < jRoutes.length(); i++) {
                jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");

                for (int j = 0; j < jLegs.length(); j++) {
                    distance = (String) ((JSONObject)((JSONObject) jLegs.get(j)).get("distance")).get("text");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return distance;
    }

    @Override
    protected void onPostExecute(String result) {

        //update ui
    }
}

}

这是我的适配器,我正在将仪表板列表传递给它。解析json数据以获取距离后,我想在onPostExecute()方法中通知距离字段。

1 个答案:

答案 0 :(得分:0)

最简单的方法是在完成更新所有调用的数据后,通知适配器上的数据集已更改,如下所示:

//Some Code
mAdapter.notifyDataSetChanged();

mAdapter是RecyclerView适配器的参考。