如何使用Android中的异步任务通过阵列列表更新列表视图?

时间:2017-07-29 15:31:27

标签: android json listview android-asynctask

我正在关注udacity.com的地震应用程序。在使用异步任务进行json解析后,我无法更新视图。在forPostExecute方法中获取arraylist对象for doBackground方法我不明白如何更新视图,我的应用程序屏幕每次都是空白,我有一个自定义单词具有一些文本视图和列表视图的适配器类这是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);



    }
}
}

获取此earthquake_data后如何从onPostExecute方法更新视图。请告诉我代码。几个星期以来,我被困在这里。在此之前我使用离线json数据,那时候一切正常。

1 个答案:

答案 0 :(得分:0)

您需要使用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