【问题标题】:How to update List View through Array List using Async Task in Android?如何在 Android 中使用异步任务通过数组列表更新列表视图?
【发布时间】:2018-01-05 13:18:54
【问题描述】:

我正在关注来自 udacity.com 的 Earthquake 应用程序。我被困在使用异步任务解析json后更新视图。在onPostExecute方法中为doInBackground方法获取arraylist对象后,我不明白如何更新视图,我的应用程序屏幕每次都是空白的,我有一个自定义词带有一些文本视图和列表视图的适配器类 这是 EarthquakeActivity.java 类的代码

 package com.example.android.quakereport;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import java.util.ArrayList;

   public class EarthquakeActivity extends AppCompatActivity {

public static final String LOG_TAG = EarthquakeActivity.class.getName();

            private static final String USGS_REQUEST_URL =
                    "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2016-01-01&endtime=2016-05-02&minfelt=50&minmagnitude=5";


ArrayList<Earthquak_Data> list=new ArrayList<>();
EarthquakAdaptor earthquakAdaptor;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.earthquake_activity);

    EarthquakAsyncTask task= new EarthquakAsyncTask();
    task.execute(USGS_REQUEST_URL);



}

private class EarthquakAsyncTask extends AsyncTask<String,Void,ArrayList<Earthquake_Data>> {
    @Override
    protected ArrayList<Earthquak_Data> doInBackground(String... strings) {
        ArrayList<Earthquak_Data> result=QueryUtils.Fentch_EarthQuake_Data(USGS_REQUEST_URL);
        return result;
    }

    @Override
    protected void onPostExecute(ArrayList<Earthquak_Data> earthquake_datas) {
        super.onPostExecute(earthquak_datas);



    }
}
}

获得这个地震数据后,我如何从 onPostExecute 方法更新视图。请告诉我代码。我被困在这里好几个星期了。在此之前,我使用离线 json 数据,当时一切正常。

【问题讨论】:

  • 您需要将您在 onPost 方法中收到的列表传递给适配器,然后将适配器设置为您正在使用的 listview 或 recyclerview。

标签: android json listview android-asynctask


【解决方案1】:

您需要使用 arrayadapter 来填充列表视图,如下所示...

 // Construct the data source as in background
    ArrayList<Earthquak_Data> result = .......
    // Create the adapter to convert the array to views in postexecute
    UsersAdapter adapter = new UsersAdapter(this, result);
    // Attach the adapter to a ListView
    ListView listView = (ListView) findViewById(R.id.lvItems);
    listView.setAdapter(adapter);

更多详情here.

【讨论】:

  • UsersAdapter 适配器 = new UsersAdapter(this, result);这给了我一个错误,即地震适配器无法应用于 EarthquakeActivity.AsyncTask
  • @adityapratap: 试试 UsersAdapter 适配器 = new UsersAdapter(EarthquakeActivity.this, result);看看会发生什么。
  • 您还需要修改 UsersAdapter(任何名称)以接受 Earthquak_Data 对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多