尚未解决,所以请有人帮忙。请。
我在主要活动中有一个ListView,它由Google Books API JSON中的数据动态填充,我希望在ListView上单击时启动一个新的Intent(每次都进行相同的活动),以便它随身携带单击的ListView项中包含的数据。我正在使用“Bundle”但无法做到这一点。 请参阅下面的详细信息,请告诉我我正在犯的错误。我是新手,完全坚持了2-3天。 请看,帮助我。谢谢。 我的问题类似于以下问题,但解决方案无法帮助我。这些是指向这些主题的链接:how to start new activity in listview item click和Pass custom list item content to new activity when list item is clicked from a listview
这是我的 MainActivity:,它使用“标题,作者和发布商非常容易”填充activity_main.xml
public class MainActivity extends AppCompatActivity {
String title;
String firstAuthor;
String publisher;
String pageCount;
String description;
int averageRating;
String publishedDate;
String isbnType;
String isbnValue;
Books booksObject = new Books();
private String searchQuery;
/**
* Tag for the log messages
*/
public static final String LOG_TAG = MainActivity.class.getSimpleName();
/**
* URL to query the GoogleBook dataset for book's information
*/
private static String BOOK_REQUEST_URL = "https://www.googleapis.com/books/v1/volumes?q=";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button search = (Button) findViewById(R.id.search);
search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Find the edit text's actual text and make it compatible for a url search query
searchQuery = ((EditText) findViewById(R.id.searchQuery)).getText().toString().replace(" ", "+");
//Check if user input is empty or it contains some query text
if (searchQuery.isEmpty()) {
Context context = getApplicationContext();
String text = "Nothing Entered in Search";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
} else {
// String to be attached to the BOOK_REQUEST_URL
String appendableQuery = searchQuery + "&key=MyGoogleBookAPIKey&maxResults=10&country=IN";
BOOK_REQUEST_URL += appendableQuery; //final value of "URL for Google Book API"
BookAsyncTask task = new BookAsyncTask();
//If network is available then perform the further task of AsynckTask calling
if (isNetworkAvailable()) {
// Kick off an {@link AsyncTask} to perform the network request
task.execute();
} else {
Toast.makeText(getApplicationContext(), "Network not available", Toast.LENGTH_SHORT).show();
//Reset the to the original URL to prevent app crash
BOOK_REQUEST_URL = "https://www.googleapis.com/books/v1/volumes?q=";
}
}
}
});
}
//Check if network is available or not
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
/**
* Update the screen to display information from the given {@link Books}.
*/
private void updateUi(final ArrayList<Books> book) {
final ListView listView = (ListView) findViewById(R.id.list);
BooksAdapter booksAdapter = new BooksAdapter(MainActivity.this, book);
listView.setAdapter(booksAdapter);
/*Setting click listener on ListView*/
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Books bookses = book.get(position);
Bundle bookDetailsBundle = new Bundle();
bookDetailsBundle.putParcelableArrayList("bookDetailsArrayList", book);
Intent booksIntent = new Intent(getApplicationContext(), BookDetailsActivity.class);
booksIntent.putExtra("bookDetailsBundle", bookDetailsBundle);
startActivity(booksIntent);
}
});
}
/**
* {@link AsyncTask} to perform the network request on a background thread, and then
* update the UI with the first earthquake in the response.
*/
private class BookAsyncTask extends AsyncTask<URL, Void, ArrayList<Books>> {
@Override
protected ArrayList<Books> doInBackground(URL... urls) {
// Create URL object
URL url = createUrl(BOOK_REQUEST_URL);
// Perform HTTP request to the URL and receive a JSON response back
String jsonResponse = "";
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
// TODO Handle the IOException
}
// Extract relevant fields from the JSON response and create an {@link Books} object
ArrayList<Books> book = extractFeatureFromJson(jsonResponse);
// Return the {@link Books} object as the result fo the {@link BookAsyncTask}
return book;
}
/**
* Update the screen with the given book (which was the result of the
* {@link BookAsyncTask}).
*/
@Override
protected void onPostExecute(ArrayList<Books> book) {
if (book == null) {
return;
}
updateUi(book);
EditText editText = (EditText) findViewById(R.id.searchQuery);
editText.setText(null);
BOOK_REQUEST_URL = "https://www.googleapis.com/books/v1/volumes?q="; //Reset the to the original URL
}
/**
* Returns new URL object from the given string URL.
*/
private URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException exception) {
Toast.makeText(MainActivity.this, "Error Creating URL", Toast.LENGTH_SHORT).show();
return null;
}
return url;
}
/**
* Make an HTTP request to the given URL and return a String as the response.
*/
private String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.connect();
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Toast.makeText(MainActivity.this, "Error Response Code: "
+ urlConnection.getResponseCode(), Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
// TODO: Handle the exception
Toast.makeText(MainActivity.this, "There is an IO exception: " + e.getMessage(), Toast.LENGTH_SHORT).show();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
// function must handle java.io.IOException here
inputStream.close();
}
}
return jsonResponse;
}
/**
* Convert the {@link InputStream} into a String which contains the
* whole JSON response from the server.
*/
private 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();
}
/**
* Return an {@link Books} object by parsing out information
* about the first earthquake from the input googleBooksJSON string.
*/
private ArrayList<Books> extractFeatureFromJson(String googleBooksJSON) {
try {
ArrayList<Books> arrayListOfBooks = new ArrayList<Books>();
JSONObject baseJsonResponse = new JSONObject(googleBooksJSON);
//Check if the base/root JSONObject has the desired "key" of value "items" and then only proceed
if (baseJsonResponse.has("items")) {
JSONArray itemsArray = baseJsonResponse.getJSONArray("items");
if (itemsArray.length() > 0) {
for (int i = 0; i < itemsArray.length(); i++) {
JSONObject volumeInfo = itemsArray.getJSONObject(i).getJSONObject("volumeInfo");
//Check if the JSONObject volumeInfo has the desired string with value "title" and then only proceed
booksObject.setVolumeId(i);
if (volumeInfo.has("title")) {
title = volumeInfo.getString("title");
booksObject.setTitle(title);
}
// String publisher = volumeInfo.getString("publisher");
//Check if the JSONObject volumeInfo has the desired string with value "authors" and then only proceed
if (volumeInfo.has("authors")) {
JSONArray authors = volumeInfo.getJSONArray("authors");
//get first author's name
firstAuthor = authors.getString(0);
booksObject.setAuthor(firstAuthor);
}
if (volumeInfo.has("publisher")) {
publisher = volumeInfo.getString("publisher");
booksObject.setPublisher(publisher);
}
if (volumeInfo.has("pageCount")) {
pageCount = volumeInfo.getString("pageCount");
booksObject.setPageCount(pageCount);
}
if (volumeInfo.has("description")) {
description = volumeInfo.getString("description");
booksObject.setDescription(description);
}
if (volumeInfo.has("averageRating")) {
averageRating = volumeInfo.getInt("averageRating");
booksObject.setRatings(averageRating);
}
if (volumeInfo.has("publishedDate")) {
publishedDate = volumeInfo.getString("publishedDate");
booksObject.setPublishedDate(publishedDate);
}
if (volumeInfo.has("industryIdentifiers")) {
JSONArray industryIdentifiers = volumeInfo.getJSONArray("industryIdentifiers");
JSONObject firstISBN = industryIdentifiers.getJSONObject(0);
isbnType = firstISBN.getString("type");
isbnValue = firstISBN.getString("identifier");
booksObject.setISBNType(isbnType);
booksObject.setISBNValue(isbnValue);
}
arrayListOfBooks.add(new Books(booksObject.getVolumeId(), booksObject.getTitle(), booksObject.getAuthor(), booksObject.getPublisher(),
booksObject.getPageCount(), booksObject.getDescription(), booksObject.getRatings(),
booksObject.getPublishedDate(), booksObject.getISBNType(), booksObject.getISBNValue()));
}
}
return arrayListOfBooks;
} else
Toast.makeText(MainActivity.this, "No Book found, search again", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
Toast.makeText(MainActivity.this, "Problem parsing the Google Books JSON results" + e, Toast.LENGTH_SHORT).show();
}
return null;
}
}
} 我的 BookAdapter 在这里:
public class BooksAdapter extends ArrayAdapter<Books> {
// View lookup cache
private static class ViewHolder {
TextView title;
TextView author;
TextView publisher;
}
public BooksAdapter(Context context, ArrayList<Books> books){
super(context, 0, books);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
final Books currentBook = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
// If there's no view to re-use, inflate a brand new view for row
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.activity_main_items, parent, false);
/*Find the TextView and ImageView and set them on the VIewHolder*/
viewHolder.title = (TextView) convertView.findViewById(R.id.title);
viewHolder.author = (TextView) convertView.findViewById(R.id.author);
viewHolder.publisher = (TextView) convertView.findViewById(R.id.publisher);
// Cache the viewHolder object inside the fresh view
convertView.setTag(viewHolder);
} else {
// View is being recycled, retrieve the viewHolder object from tag
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data into the template view using the data object
viewHolder.title.setText(currentBook.getTitle());
viewHolder.author.setText(currentBook.getAuthor());
viewHolder.publisher.setText(currentBook.getPublisher());
return convertView;
}
}
以下是每次单击列表视图时调用的活动(intent):
public class BookDetailsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.book_details_listview);
//Bundle bundle = new Bundle();
ArrayList<Books> booksArrayList = getIntent().getBundleExtra("bookDetailsBundle").getParcelableArrayList("bookDetailsArrayList");
BookDetailsAdapter bookDetailsAdapter = new BookDetailsAdapter(this, booksArrayList);
ListView listView = (ListView) findViewById(R.id.book_details_listview);
listView.setAdapter(bookDetailsAdapter);
}
} 它的适配器就在这里:
public class BookDetailsAdapter extends ArrayAdapter<Books> {
public BookDetailsAdapter(Activity context, ArrayList<Books> bookses) {
super(context, 0, bookses);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if the existing view is being reused, otherwise inflate the view
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.book_details_items, parent, false);
}
// Get the {@link AndroidFlavor} object located at this position in the list
Books currentBook = getItem(position);
// Find the TextView in the list_item.xml layout with the ID version_name
TextView title_book = (TextView) listItemView.findViewById(R.id.title_book);
TextView author_book = (TextView) listItemView.findViewById(R.id.author_book);
TextView publisher_book = (TextView) listItemView.findViewById(R.id.publisher_book);
TextView page_count_book = (TextView) listItemView.findViewById(R.id.page_count_book);
TextView description_book = (TextView) listItemView.findViewById(R.id.description_book);
TextView ratings_book = (TextView) listItemView.findViewById(R.id.ratings_book);
TextView publication_date_book = (TextView) listItemView.findViewById(R.id.publication_date_book);
TextView isbn_type_book = (TextView) listItemView.findViewById(R.id.isbn_type_book);
TextView isbn_value_book = (TextView) listItemView.findViewById(R.id.isbn_value_book);
// set this text on these TextViews
title_book.setText(currentBook.getTitle());
author_book.setText(currentBook.getAuthor());
publisher_book.setText(currentBook.getPublisher());
page_count_book.setText(currentBook.getPageCount());
description_book.setText(currentBook.getDescription());
ratings_book.setText(currentBook.getRatings());
publication_date_book.setText(currentBook.getPublishedDate());
isbn_type_book.setText(currentBook.getISBNType());
isbn_value_book.setText(currentBook.getISBNValue());
return listItemView;
}
}
无论我做什么,我都会得到同样的错误:引起:java.lang.NullPointerException:尝试在null上调用虚方法'void android.widget.ListView.setAdapter(android.widget.ListAdapter)'对象参考 在com.example.android.booklisting.BookDetailsActivity.onCreate(BookDetailsActivity.java:24) 我现在完全无能为力而且失去了但是清楚地知道我无法获得“listview”中点击的“列表项”的位置,即使我尝试使用“Books books = getItem(position)之类的东西” ;”在“onItemClick”。请告诉我到底哪里错了,解决方案是什么。非常欢迎您的回复。 我的book_details_item在这里:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/book_details_item"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/title_book"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="book's title" />
<TextView
android:id="@+id/author_book"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="book's title" />
<TextView
android:id="@+id/publisher_book"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="book's title" />
<TextView
android:id="@+id/page_count_book"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="book's title" />
<TextView
android:id="@+id/description_book"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="book's title" />
<TextView
android:id="@+id/ratings_book"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="book's title" />
<TextView
android:id="@+id/publication_date_book"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="book's title" />
<TextView
android:id="@+id/isbn_type_book"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="book's title" />
<TextView
android:id="@+id/isbn_value_book"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="book's title" />