为什么我在使用AsyncTask时没有填充ListView?

问题描述 投票:0回答:3

我正在编写一个使用Google图书搜索API的应用程序,该应用程序应该做的是基于我在应用程序代码中以String形式提供的搜索查询来显示书籍列表,我使用AsyncTask内部类来处理后台工作(进行HTTP请求,JSON格式...等),我也有书籍服装适配器和书籍类来获取数据,我的问题是应用程序未在列表视图中显示任何书籍。

这是我的代码:

公共类MainActivity扩展了AppCompatActivity {

final static String bookUrl = "https://www.googleapis.com/books/v1/volumes?q=android&maxResults=6";
private BookAdapter bookAdapter;

private ArrayList<Book> books;

private ListView list;

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


     list = (ListView) findViewById(R.id.list);
     new BookAsynck().execute(bookUrl);


}

private class BookAsynck extends AsyncTask<String, Void, ArrayList<Book>> {
    @Override
    protected ArrayList<Book> doInBackground(String... strings) {
        books = Utils.fetchBookData(bookUrl);
        return books;
    }

    @Override
    protected void onPostExecute(ArrayList<Book> books) {
        bookAdapter = new BookAdapter(MainActivity.this, books);
        list.setAdapter(bookAdapter);
    }
}

}


public class Utils {
public static final String LOG_TAG = Utils.class.getSimpleName();


public static ArrayList<Book> fetchBookData(String requestUrl) {

    ArrayList<Book> bookList = new ArrayList<>();

    URL url = CreateURl(requestUrl);
    String json = null;
    try {
        json = makeHttpRequest(url);
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error closing input stream", e);
    }
    bookList = extractBookData(json);
    return bookList;
}


public static URL CreateURl(String stringUrl) {
    URL url = null;
    try {
        url = new URL(stringUrl);
    } catch (MalformedURLException e) {
        Log.e(LOG_TAG, "Error with creating URL ", e);
    }
    return url;
}

//make http  request and return a string containing the response
public static String makeHttpRequest(URL url) throws IOException {
    String jsonResponse = "";
    //if the url is null return empty string
    if (url == null) {
        return jsonResponse;
    }

    HttpURLConnection urlcon = null;
    InputStream inputstream = null;
    try {
        urlcon = (HttpURLConnection) url.openConnection();
        urlcon.setRequestMethod("GET");
        urlcon.setReadTimeout(1000 /*milleseconds*/);
        urlcon.setConnectTimeout(1500 /*milleseconds*/);
        urlcon.connect();

//如果请求是Successul(代码200)//获取输入流并对其进行解码

        if (urlcon.getResponseCode() == 200) {
            inputstream = urlcon.getInputStream();
            jsonResponse = readFromStream(inputstream);
        } else {
            Log.e(LOG_TAG, "Error response code " + urlcon.getResponseCode());

        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Problem retrieving the book JSON results", e);
    } finally {
        if (urlcon != null) {
            urlcon.disconnect();
        }
        if (inputstream != null) {
            inputstream.close();
        }
    }

    return jsonResponse;
}

//将输入流解码为包含来自服务器的Jsponse的字符串

private static String readFromStream(InputStream inputStream) throws IOException {
    StringBuilder output = new StringBuilder();
    if (inputStream != null) {
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
        BufferedReader reader = new BufferedReader(inputStreamReader);
        String line = reader.readLine();
        while (line != null) {
            output.append(line);
            line = reader.readLine();
        }
    }
    return output.toString();
}

public static ArrayList<Book> extractBookData(String json) {
    ArrayList<Book> booklist = new ArrayList<>();

    if (TextUtils.isEmpty(json)) {
        return null;
    }

    try {
        JSONObject base = new JSONObject(json);
        JSONArray itemsArray = base.optJSONArray("items");

        for (int i = 0; i < itemsArray.length(); i++) {
            JSONObject first = itemsArray.getJSONObject(i);
            JSONObject volume = new JSONObject("volumeInfo");
            String title = volume.getString("title");
            JSONArray authorsArray = volume.getJSONArray("authors");
            String author = authorsArray.getString(0);

            Book b = new Book(title, author);
            booklist.add(b);
        }

    } catch (JSONException e) {
        Log.e(LOG_TAG, "Problem parsing the book JSON results", e);
    }
    return booklist;
}

}

public class BookAdapter extends ArrayAdapter<Book> {
public BookAdapter(Context c, ArrayList<Book> book) {
    super(c, 0, book);
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

    View list = convertView;
    if (list == null) {
        list = LayoutInflater.from(getContext()).inflate(R.layout.item, parent, false);

    }
    Book b = getItem(position);

    TextView titleTextView = (TextView) list.findViewById(R.id.title);
    titleTextView.setText(b.getName());

    TextView author = (TextView) list.findViewById(R.id.author);
    author.setText(b.getAuthor());


    return list;
}

}

java android android-listview android-adapter
3个回答
0
投票

似乎您错过了在活动中调用异步任务的时间


0
投票

欢迎使用stackoverflow !!


0
投票

onCreate()更改下一行

© www.soinside.com 2019 - 2024. All rights reserved.