Java 运行时_标志中设置的未知位:0x8000
这是我的应用程序。它应该获得一个基于HTTP查询的JSON字符串到GoogleBooks,并显示所有找到的书籍的列表。谷歌的回应总是只返回10本书。但是如果您在HTTP请求中更改“startIndex”参数,那么它将显示10本不同的书。我的应用程序过去只显示10本新书。在我对我的图书列表进行更改,使其包含所有找到的图书之后,我的应用程序停止查找任何内容,并开始显示“未找到任何图书”,而不管你在搜索查询中输入了什么。装载机甚至不能启动 Logcat显示的唯一内容是:“运行时设置的未知位\u标志0x8000” 怎么能修好呢 我在Android Studio中使用Android模拟器 MainActivity.javaJava 运行时_标志中设置的未知位:0x8000,java,android,json,http,Java,Android,Json,Http,这是我的应用程序。它应该获得一个基于HTTP查询的JSON字符串到GoogleBooks,并显示所有找到的书籍的列表。谷歌的回应总是只返回10本书。但是如果您在HTTP请求中更改“startIndex”参数,那么它将显示10本不同的书。我的应用程序过去只显示10本新书。在我对我的图书列表进行更改,使其包含所有找到的图书之后,我的应用程序停止查找任何内容,并开始显示“未找到任何图书”,而不管你在搜索查询中输入了什么。装载机甚至不能启动 Logcat显示的唯一内容是:“运行时设置的未知位\u标志0x
package com.example.android.booklisting;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.LoaderManager;
import android.content.Loader;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<Book>> {
/** Adapter for the list of earthquakes */
private BookAdapter mAdapter;
TextView mEmptyStateTextView;
ProgressBar loadingIndicator;
int loader_id = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadingIndicator = findViewById(R.id.loading_indicator);
Button searchButton = findViewById(R.id.search_button);
searchButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText searchText = findViewById(R.id.search_text);
QueryUtils.setSearchQuery(QueryUtils.getINIITIAL_GOOGLE_BOOKS_URL()
+ searchText.getText().toString()
.replace("\\s", "+"));
mAdapter = new BookAdapter(MainActivity.this,
new ArrayList<Book>());
ListView listView = findViewById(R.id.list);
listView.setAdapter(mAdapter);
mEmptyStateTextView = findViewById(R.id.empty_view);
listView.setEmptyView(mEmptyStateTextView);
// Get a reference to the ConnectivityManager to check state of network connectivity
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
// Get details on the currently active default data network
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
// If there is a network connection, fetch data
if (networkInfo != null && networkInfo.isConnected()) {
// Get a reference to the LoaderManager, in order to interact with loaders.
LoaderManager loaderManager = getLoaderManager();
// Initialize the loader. Pass in the int ID 1 and pass in null for
// the bundle. Pass in this activity for the LoaderCallbacks parameter (which is valid
// because this activity implements the LoaderCallbacks interface).
if (loader_id == 0) {
loader_id++;
loaderManager.initLoader(loader_id, null, MainActivity.this);
}
else {
loaderManager.restartLoader(loader_id, null, MainActivity.this);
}
}
else {
// Otherwise, display error
// First, hide loading indicator so error message will be visible
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
// Update empty state with no connection error message
mEmptyStateTextView.setText(getString(R.string.no_internet_connection));
}
}
});
}
@NonNull
@Override
public Loader<List<Book>> onCreateLoader(int id, @Nullable Bundle args) {
// If there were no books found last time, delete "no books found"
// from the screen.
mEmptyStateTextView.setText("");
// Make loading indicator appear because the loading is about to start
loadingIndicator.setVisibility(View.VISIBLE);
// Create a new loader for the given URL
return new BookLoader(this, QueryUtils.getSearchQuery());
}
@Override
public void onLoadFinished(@NonNull Loader<List<Book>> loader, List<Book> books) {
// Hide loading indicator because the data has been loaded
loadingIndicator.setVisibility(View.GONE);
// Clear the adapter of previous book data
mAdapter.clear();
// If there is a valid list of {@link Book}s, then add them to the adapter's
// data set. This will trigger the ListView to update.
if (books != null && !books.isEmpty()) {
mAdapter.addAll(books);
}
// Set empty state text to display "No books found."
if (!QueryUtils.hasResults)
mEmptyStateTextView.setText(getString(R.string.no_books_found));
}
@Override
public void onLoaderReset(@NonNull Loader<List<Book>> loader) {
// Loader reset, so we can clear out our existing data.
mAdapter.clear();
}
}
package com.example.android.booklisting;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.lang.StringBuilder;
public class QueryUtils {
private static final String INIITIAL_GOOGLE_BOOKS_URL = "https://www.googleapis.com/books/v1/volumes?startIndex=0&q=";
private static String searchQuery;
// Variable for checking if there are books found
public static boolean hasResults;
private static int numberOfIterations;
private QueryUtils() {
}
public static String getINIITIAL_GOOGLE_BOOKS_URL() {
return INIITIAL_GOOGLE_BOOKS_URL;
}
public static void setSearchQuery(String searchQuery) {
QueryUtils.searchQuery = searchQuery;
}
public static String getSearchQuery() {
return searchQuery;
}
/**
* Query the Google Books dataset and return an {@link ArrayList} object to represent a list of books.
*/
/**
* Return a list of {@link Book} objects that has been built up from
* parsing the given JSON response.
*/
private static List<Book> extractBooksFromJson(String bookJSON) {
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(bookJSON)) {
Log.e("nojson", "No JSON returned");
return null;
}
// Create an empty ArrayList that we can start adding books to
List<Book> books = new ArrayList<>();
// Try to parse the JSON response string. If there's a problem with the way the JSON
// is formatted, a JSONException exception object will be thrown.
// Catch the exception so the app doesn't crash, and print the error message to the logs.
try {
// Create a JSONObject from the JSON response string
JSONObject baseJsonResponse = new JSONObject(bookJSON);
Log.v("success", "JSONObject sucessfully created!");
// Check if there are books found
hasResults = false;
if (hasBooksFound(baseJsonResponse))
{
hasResults = true;
}
numberOfIterations = baseJsonResponse.getInt("totalItems")/10 + 1;
// Extract the JSONArray associated with the key called "items",
// which represents a list of items (or books).
JSONArray bookArray = baseJsonResponse.getJSONArray("items");
// For each book in the bookArray, create a {@link Book} object
for (int i = 0; i < bookArray.length(); i++) {
// Get a single Book at position i within the list of books
JSONObject currentBook = bookArray.getJSONObject(i);
// For a given book, extract the JSONObject associated with the
// key called "volumeInfo", which represents a list of all information
// for that book.
JSONObject volumeInfo = currentBook.getJSONObject("volumeInfo");
// Extract the value for the key called "title"
String title = volumeInfo.getString("title");
String authorsString = "No information";
//Extract the JSONArray associated with the key called "authors"
if (volumeInfo.has("authors")) {
JSONArray jsonAuthors = volumeInfo.getJSONArray("authors");
ArrayList<String> authors = new ArrayList<>();
StringBuilder authorsStringBuilder = new StringBuilder();
for (int j = 0; j < jsonAuthors.length(); j++) {
// Add a specific author to the "authors" list
// and add it to a the "authorsStringBuilder"
authors.add(jsonAuthors.getString(j));
authorsStringBuilder.append(authors.get(j) + ", \n");
}
//Remove the last 3 elements in the "authorsStringBuilder"
authorsStringBuilder.delete(authorsStringBuilder.length() - 3,
authorsStringBuilder.length() - 1);
//Convert StringBuilder to String
authorsString = authorsStringBuilder.toString();
}
// Extract the value for the key called "publishedDate"
String releaseDate = volumeInfo.getString("publishedDate");
//The link for a book cover
String imageLink;
// Get the JSONObject "readingModes" having information about
// whether or not a given book has a cover
JSONObject readingModes = volumeInfo.getJSONObject("readingModes");
// Extract the value for the key called "image"
boolean hasACover = readingModes.getBoolean("image");
//Check if a given book has a cover
if (hasACover)
{
// If yes, then assign a link for the book
// to the imageLink
imageLink = volumeInfo.getJSONObject("imageLinks")
.getString("thumbnail");
Log.v("Cover check", "Book has a cover");
}
else {
// If not, then assign the imageLink the default cover
imageLink = "https://books.google.ru/googlebooks/images/no_cover_thumb.gif";
}
//Get a book cover
Bitmap bookCover = getImage(imageLink);
// Create a new {@link Book} object with the magnitude, location, time,
// and url from the JSON response.
Book book = new Book(title, authorsString, releaseDate, bookCover);
// Add the new {@link Book} to the list of books.
books.add(book);
}
}
catch (JSONException e) {
// If an error is thrown when executing any of the above statements in the "try" block,
// catch the exception here, so the app doesn't crash. Print a log message
// with the message from the exception.
Log.e("QueryUtils", "Problem parsing the book JSON results", e);
}
// Return the list of books
return books;
}
/**
* Get a book cover.
*/
/**
* Return a book cover
*/
private static Bitmap getImage(String imageLink)
{
Bitmap image = null;
try {
URL url = new URL(imageLink);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
image = BitmapFactory.decodeStream(input);
} catch (IOException e) {
// Log exception
Log.e("getImage: ", "Image problems", e);
}
return image;
}
/**
* Check if there are books found
* @param baseJsonResponse — root JSONObject from the Google Books HTTP response
* @return boolean value (true if there are results, false if not)
*/
private static boolean hasBooksFound(JSONObject baseJsonResponse) {
boolean hasBooksFound = true;
try {
if (baseJsonResponse.getInt("totalItems") == 0) {
hasBooksFound = false;
}
}
catch (JSONException e)
{
Log.e("hasBooksFound: ", "JSONException", e);
}
return hasBooksFound;
}
public static int getNumberOfIterations() {
return numberOfIterations;
}
/**
* Query the Google Books dataset and return a list of {@link Book} objects.
*/
public static List<Book> fetchEarthquakeData(String requestUrl) {
// Create URL object
URL url = createUrl(requestUrl);
// Perform HTTP request to the URL and receive a JSON response back
String jsonResponse = null;
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
Log.e("", "Problem making the HTTP request.", e);
}
// Extract relevant fields from the JSON response and create a list of {@link Book}s
List<Book> books = extractBooksFromJson(jsonResponse);
Log.v("QueryUtils", "fetching data");
// Return the list of {@link book}s
return books;
}
/**
* Returns new URL object from the given string URL.
*/
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e("QueryUtils: : ", "Error with creating URL", e);
}
return url;
}
/**
* Make an HTTP request to the given URL and return a String as the response.
*/
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
// If the URL is null, then return early.
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// If the request was successful (response code 200),
// then read the input stream and parse the response.
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e("", "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e("", "Problem retrieving the earthquake JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
/**
* Convert the {@link InputStream} into a String which contains the
* whole JSON response from the server.
*/
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();
}
}
package com.example.android.booklisting;
import android.content.Context;
import androidx.annotation.Nullable;
import android.content.AsyncTaskLoader;
import java.util.ArrayList;
import java.util.List;
public class BookLoader extends AsyncTaskLoader<List<Book>> {
/** Query URL */
private String mUrl;
/**
* Constructs a new {@link BookLoader}.
*
* @param context of the activity
* @param url to load data from
*/
public BookLoader(Context context, String url) {
super(context);
mUrl = url;
}
@Override
protected void onStartLoading() {
forceLoad();
}
/**
* This is on a background thread.
*/
@Nullable
@Override
public List<Book> loadInBackground() {
if (mUrl == null) {
return null;
}
// List of 10 books from Google's JSON response
List<Book> currentBooks;
// List of all books combined from the different queries
// to Google Books changing startIndex parameter
List<Book> books = new ArrayList<>();
/*for (int i = 0; i < QueryUtils.getNumberOfIterations(); i = i + 10) {
mUrl = mUrl.replace("x=0", "x=" + i);*/
// Perform the network request, parse the response, and extract a list of earthquakes.
currentBooks = QueryUtils.fetchEarthquakeData(mUrl);
//books.addAll(currentBooks);
//}
return currentBooks;
//return books;
}
}
package com.example.android.booklisting;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class BookAdapter extends ArrayAdapter<Book> {
public BookAdapter(Activity context, ArrayList<Book> books) {
super(context, 0, books);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null)
{
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.book_item, parent, false);
}
Book currentBook = getItem(position);
TextView bookTitleView = listItemView.findViewById(R.id.book_title);
bookTitleView.setText(currentBook.getTitle());
TextView bookAuthorView = listItemView.findViewById(R.id.book_author);
bookAuthorView.setText(currentBook.getAuthor());
TextView bookReleaseYearView = listItemView.findViewById(R.id.book_release_year);
bookReleaseYearView.setText(currentBook.getReleaseYear());
ImageView bookCoverView = listItemView.findViewById(R.id.book_cover);
bookCoverView.setImageBitmap(currentBook.getBookCover());
return listItemView;
}
}
public List<Book> loadInBackground() {
if (mUrl == null) {
return null;
}
// List of 10 books from Google's JSON response
List<Book> currentBooks;
// List of all books combined from the different queries
// to Google Books changing startIndex parameter
List<Book> books = new ArrayList<>();
/*for (int i = 0; i < QueryUtils.getNumberOfIterations(); i = i + 10) {
mUrl = mUrl.replace("x=0", "x=" + i);*/
// Perform the network request, parse the response, and extract a list of earthquakes.
currentBooks = QueryUtils.fetchEarthquakeData(mUrl);
//books.addAll(currentBooks);
//}
return currentBooks;
//return books;
}
numberOfIterations = baseJsonResponse.getInt("totalItems")/10 + 1;