如何修复将 JSON 数据添加到 ArrayList 并更新到 ArrayAdapter
How to fix adding JSON data to the ArrayList and updating to the ArrayAdapter
这段代码只是查询Google本书API和returnJSON中的数据。然后,解析 JSON 数据并将书名、作者和出版日期存储在类型 'Book' 的 ArrayList 中。尝试解析 JSON 数据数组时出现问题。它不会从 MainActivity.java class 中的第 70 行的循环中出来。可能的解决方案是什么?
存储库是 https://github.com/PRAVEENT26/GoogleBooksAPI
我也会在这里列出文件。
MainActivity.java
package com.praveent.googlebooksapi;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;
import static java.lang.System.in;
public class MainActivity extends AppCompatActivity {
EditText query;
Button submit;
String dataJSON;
TextView test;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
query = (EditText) findViewById(R.id.query);
submit = (Button) findViewById(R.id.submit);
final String baseURL = "https://www.googleapis.com/books/v1/volumes";
final String queryParameter = "q";
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String searchQuery = query.getText().toString();
Uri tempUri = Uri.parse(baseURL).buildUpon().appendQueryParameter(queryParameter, searchQuery).build();
URL url;
try {
url = new URL(tempUri.toString());
new fetchDataAsync().execute(url);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public void jsonParsing() throws JSONException {
JSONObject response = new JSONObject(dataJSON);
int total = response.getInt("totalItems");
TextView test = (TextView) findViewById(R.id.test);
int flag = 0;
JSONArray bookArray = response.getJSONArray("items");
//test.setText(Integer.toString(bookArray.length()));
ArrayList < Book > bookList = new ArrayList < > ();
ListView listView = (ListView) findViewById(R.id.commonView);
for (int i = 0; i < total; i++) {
flag++;
JSONObject volume = bookArray.getJSONObject(i);
if (volume.has("volumeInfo")) {
JSONObject tempObject = volume.getJSONObject("volumeInfo");
String bookName = tempObject.getString("title");
String authorName = null;
if (tempObject.has("authors")) {
JSONArray authorsArray = tempObject.getJSONArray("authors");
for (int j = 0; j < authorsArray.length(); j++) {
authorName += authorsArray.getString(j);
if (j < authorsArray.length() - 1) {
authorName += ", ";
}
}
}
String publicationDate = tempObject.getString("publishedDate");
bookList.add(new Book(bookName, authorName, publicationDate));
}
}
test.setText(Integer.toString(flag));
BookAdapter bookAdapter = new BookAdapter(this, bookList);
listView.setAdapter(bookAdapter);
}
public class fetchDataAsync extends AsyncTask < URL, Void, String > {
@Override
protected String doInBackground(URL...url) {
URL searchURL = url[0];
try {
dataJSON = fetchData(searchURL);
} catch (IOException e) {
e.printStackTrace();
}
return dataJSON;
}
@Override
protected void onPostExecute(String s) {
try {
jsonParsing();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public static String fetchData(URL url) throws IOException {
HttpURLConnection newConnection = (HttpURLConnection) url.openConnection();
try {
InputStream newStream = newConnection.getInputStream();
Scanner scanner = new Scanner(newStream);
scanner.useDelimiter("\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else
return null;
} finally {
newConnection.disconnect();
}
}
}
BookAdapter.java
package com.praveent.googlebooksapi;
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 java.util.ArrayList;
public class BookAdapter extends ArrayAdapter<Book>{
public BookAdapter(Activity context, ArrayList<Book> bookArrayListAdapter) {
super(context, 0, bookArrayListAdapter);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View tempView = convertView;
if (tempView == null){
tempView = LayoutInflater.from(getContext()).inflate(R.layout.book_details,parent,false);
}
Book temp = getItem(position);
ImageView imageView = (ImageView) tempView.findViewById(R.id.image);
TextView nameView = (TextView) tempView.findViewById(R.id.bookName);
TextView authorView = (TextView) tempView.findViewById(R.id.authorName);
TextView dateView = (TextView) tempView.findViewById(R.id.publishDate);
imageView.setImageResource(R.drawable.google);
nameView.setText(temp.getbookName());
authorView.setText(temp.getAuthorName());
dateView.setText(temp.getPublishedDate());
return tempView;
}
}
Book.java //自定义对象
package com.praveent.googlebooksapi;
public class Book {
String bookName;
String authorName;
String publishedDate;
public Book(String name, String authors, String date){
bookName = name;
authorName = authors;
publishedDate = date;
}
public String getbookName() {
return bookName;
}
public String getAuthorName() {
return authorName;
}
public String getPublishedDate() {
return publishedDate;
}
}
XML 布局:
book_details.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp">
<ImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:padding="8dp"
android:id="@+id/image"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/bookName"
android:textSize="16dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/authorName"
android:textSize="16dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/publishDate"
android:textSize="16dp" />
</LinearLayout>
</LinearLayout>
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.praveent.googlebooksapi.MainActivity">
<EditText
android:id="@+id/query"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Enter the Book Query" />
<Button
android:id="@+id/submit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SUBMIT QUERY" />
<TextView
android:id="@+id/test"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/commonView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"/>
</LinearLayout>
ANDROID 清单文件:
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.praveent.googlebooksapi">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
样本JSON数据:Query Results in JSON。单击此处可查看 JSON 结构。
请帮助我 运行 没有任何问题。提前致谢!
试试这个,
try
{
JSONObject result = new JSONObject(resultResponse);
String kind = result.getString("kind");
JSONArray items_arr=result.getJSONArray("items");
for(int i=0;i<items_arr.length();i++)
{
JSONObject obj=items_arr.getJSONObject(i);
JSONObject volumeInfo_obj=obj.getJSONObject("volumeInfo");
String bookName=volumeInfo_obj.getString("title");
JSONArray volumeInfo_arr=volumeInfo_obj.getJSONArray("authors");
String authorName=volumeInfo_arr.getString(0);
String publicationDate=volumeInfo_obj.getString("publishedDate");
bookList.add(new Book(bookName, authorName, publicationDate));
}
BookAdapter bookAdapter = new BookAdapter(this, bookList);
listView.setAdapter(bookAdapter);
} catch (JSONException e) {
Constants.dismiss_progress_dialog();
e.printStackTrace();
}
这段代码只是查询Google本书API和returnJSON中的数据。然后,解析 JSON 数据并将书名、作者和出版日期存储在类型 'Book' 的 ArrayList 中。尝试解析 JSON 数据数组时出现问题。它不会从 MainActivity.java class 中的第 70 行的循环中出来。可能的解决方案是什么?
存储库是 https://github.com/PRAVEENT26/GoogleBooksAPI
我也会在这里列出文件。
MainActivity.java
package com.praveent.googlebooksapi;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;
import static java.lang.System.in;
public class MainActivity extends AppCompatActivity {
EditText query;
Button submit;
String dataJSON;
TextView test;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
query = (EditText) findViewById(R.id.query);
submit = (Button) findViewById(R.id.submit);
final String baseURL = "https://www.googleapis.com/books/v1/volumes";
final String queryParameter = "q";
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String searchQuery = query.getText().toString();
Uri tempUri = Uri.parse(baseURL).buildUpon().appendQueryParameter(queryParameter, searchQuery).build();
URL url;
try {
url = new URL(tempUri.toString());
new fetchDataAsync().execute(url);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public void jsonParsing() throws JSONException {
JSONObject response = new JSONObject(dataJSON);
int total = response.getInt("totalItems");
TextView test = (TextView) findViewById(R.id.test);
int flag = 0;
JSONArray bookArray = response.getJSONArray("items");
//test.setText(Integer.toString(bookArray.length()));
ArrayList < Book > bookList = new ArrayList < > ();
ListView listView = (ListView) findViewById(R.id.commonView);
for (int i = 0; i < total; i++) {
flag++;
JSONObject volume = bookArray.getJSONObject(i);
if (volume.has("volumeInfo")) {
JSONObject tempObject = volume.getJSONObject("volumeInfo");
String bookName = tempObject.getString("title");
String authorName = null;
if (tempObject.has("authors")) {
JSONArray authorsArray = tempObject.getJSONArray("authors");
for (int j = 0; j < authorsArray.length(); j++) {
authorName += authorsArray.getString(j);
if (j < authorsArray.length() - 1) {
authorName += ", ";
}
}
}
String publicationDate = tempObject.getString("publishedDate");
bookList.add(new Book(bookName, authorName, publicationDate));
}
}
test.setText(Integer.toString(flag));
BookAdapter bookAdapter = new BookAdapter(this, bookList);
listView.setAdapter(bookAdapter);
}
public class fetchDataAsync extends AsyncTask < URL, Void, String > {
@Override
protected String doInBackground(URL...url) {
URL searchURL = url[0];
try {
dataJSON = fetchData(searchURL);
} catch (IOException e) {
e.printStackTrace();
}
return dataJSON;
}
@Override
protected void onPostExecute(String s) {
try {
jsonParsing();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public static String fetchData(URL url) throws IOException {
HttpURLConnection newConnection = (HttpURLConnection) url.openConnection();
try {
InputStream newStream = newConnection.getInputStream();
Scanner scanner = new Scanner(newStream);
scanner.useDelimiter("\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else
return null;
} finally {
newConnection.disconnect();
}
}
}
BookAdapter.java
package com.praveent.googlebooksapi;
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 java.util.ArrayList;
public class BookAdapter extends ArrayAdapter<Book>{
public BookAdapter(Activity context, ArrayList<Book> bookArrayListAdapter) {
super(context, 0, bookArrayListAdapter);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View tempView = convertView;
if (tempView == null){
tempView = LayoutInflater.from(getContext()).inflate(R.layout.book_details,parent,false);
}
Book temp = getItem(position);
ImageView imageView = (ImageView) tempView.findViewById(R.id.image);
TextView nameView = (TextView) tempView.findViewById(R.id.bookName);
TextView authorView = (TextView) tempView.findViewById(R.id.authorName);
TextView dateView = (TextView) tempView.findViewById(R.id.publishDate);
imageView.setImageResource(R.drawable.google);
nameView.setText(temp.getbookName());
authorView.setText(temp.getAuthorName());
dateView.setText(temp.getPublishedDate());
return tempView;
}
}
Book.java //自定义对象
package com.praveent.googlebooksapi;
public class Book {
String bookName;
String authorName;
String publishedDate;
public Book(String name, String authors, String date){
bookName = name;
authorName = authors;
publishedDate = date;
}
public String getbookName() {
return bookName;
}
public String getAuthorName() {
return authorName;
}
public String getPublishedDate() {
return publishedDate;
}
}
XML 布局:
book_details.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp">
<ImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:padding="8dp"
android:id="@+id/image"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/bookName"
android:textSize="16dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/authorName"
android:textSize="16dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/publishDate"
android:textSize="16dp" />
</LinearLayout>
</LinearLayout>
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.praveent.googlebooksapi.MainActivity">
<EditText
android:id="@+id/query"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Enter the Book Query" />
<Button
android:id="@+id/submit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SUBMIT QUERY" />
<TextView
android:id="@+id/test"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/commonView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"/>
</LinearLayout>
ANDROID 清单文件:
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.praveent.googlebooksapi">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
样本JSON数据:Query Results in JSON。单击此处可查看 JSON 结构。
请帮助我 运行 没有任何问题。提前致谢!
试试这个,
try
{
JSONObject result = new JSONObject(resultResponse);
String kind = result.getString("kind");
JSONArray items_arr=result.getJSONArray("items");
for(int i=0;i<items_arr.length();i++)
{
JSONObject obj=items_arr.getJSONObject(i);
JSONObject volumeInfo_obj=obj.getJSONObject("volumeInfo");
String bookName=volumeInfo_obj.getString("title");
JSONArray volumeInfo_arr=volumeInfo_obj.getJSONArray("authors");
String authorName=volumeInfo_arr.getString(0);
String publicationDate=volumeInfo_obj.getString("publishedDate");
bookList.add(new Book(bookName, authorName, publicationDate));
}
BookAdapter bookAdapter = new BookAdapter(this, bookList);
listView.setAdapter(bookAdapter);
} catch (JSONException e) {
Constants.dismiss_progress_dialog();
e.printStackTrace();
}