我想将ArrayList转换为String并在textview中显示它。这是我的代码:
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{
public static final String Logcat = "vmech";
Button searchButton;
EditText editTextSearch;
TextView textViewDisplayResult;
String newText;
String urlstring;
ListView lvBooks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvBooks = (ListView) findViewById(R.id.lvBooks);
searchButton = (Button) findViewById(R.id.buttonSerch);
editTextSearch = (EditText) findViewById(R.id.editTextSearch);
searchButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
newText = editTextSearch.getText().toString();
if(newText.length()>0){
newText = newText.replace(" ", "+");
urlstring = "https://www.googleapis.com/books/v1/volumes?q=";
urlstring = urlstring + newText + "&maxResults=20" + "&key=" + MyAPIKey;
}
else {
Toast.makeText(MainActivity.this, "Please enter a book name to search.", Toast.LENGTH_LONG).show();
}
new JSONTask().execute(urlstring);
//Toast.makeText(MainActivity.this, "Search Button Clicked.", Toast.LENGTH_LONG).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
//super.onCreateOptionsMenu(menu);
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(this);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
Toast.makeText(this, "This is the Settings item", Toast.LENGTH_LONG).show();
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
public class JSONTask extends AsyncTask<String, String, List<VolumeInfo>>{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected List<VolumeInfo> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader bufferedReader = null;
try {
URL url = new URL(urlstring);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputstream = connection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputstream));
StringBuffer stringbuffer = new StringBuffer();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringbuffer.append(line);
}
String finalJson = stringbuffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("items");
List<VolumeInfo> infoList = new ArrayList<>();
String idText = null;
Item item = new Item();
VolumeInfo info = new VolumeInfo();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i).getJSONObject("volumeInfo");
info.setTitle(finalObject.getString("title"));
String author = null;
for (int j = 0; j < authors.length(); j++) {
JSONArray authors = finalObject.getJSONArray("authors");
author = authors.getString(i);
}
info.setAuthors(author);
info.setDescription(finalObject.getString("description"));
}
return infoList;
} catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
{
connection.disconnect();
}
try {
if (bufferedReader != null){
bufferedReader.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(List<VolumeInfo> result) {
super.onPostExecute(result);
BookAdapter adapter = new BookAdapter(getApplicationContext(), R.layout.book_row_layout, result);
lvBooks.setAdapter(adapter);
}
}
public class BookAdapter extends ArrayAdapter{
private List<VolumeInfo> InfoList;
private int resource;
private LayoutInflater inflater;
public BookAdapter(Context context, int resource, List<VolumeInfo> objects) {
super(context, resource, objects);
InfoList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = inflater.inflate(resource, null);
}
ImageView ivBookIcon;
TextView tvTitle;
TextView tvAuthor;
TextView tvDescription;
ivBookIcon = (ImageView) convertView.findViewById(R.id.ivBookIcon);
tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
tvAuthor = (TextView) convertView.findViewById(R.id.tvauthor);
tvDescription = (TextView) convertView.findViewById(R.id.tvDescription);
tvTitle.setText(InfoList.get(position).getTitle());
tvAuthor.setText((CharSequence) InfoList.get(position).getAuthors());
tvDescription.setText(InfoList.get(position).getDescription());
return convertView;
}
}
}
我想从Google Books API的JSON中获取作者,并将其显示在getView
BookAdapter
类tvAuthor.setText((CharSequence) InfoList.get(position).getAuthors());
类的doInBackground
方法的列表视图中。
但是当我试图从中获取数据时:在info.setAuthors(author);
方法中,它显示错误,显示无法将lis转换为字符串,错误位于for (int j = 0; j < authors.length(); j++) {
JSONArray authors = finalObject.getJSONArray("authors");
author = authors.getString(i);
}
info.setAuthors(author);
。
BookAdapter adapter = new BookAdapter(getApplicationContext(),R.layout.book_row_layout, result);
lvBooks.setAdapter(adapter);
同样在尝试运行应用程序时,它强制关闭在列表视图中给出Null Pointer Exception:
public class VolumeInfo {
private String title;
private String authors;
private String publisher;
private String publishedDate;
private String description;
private List<IndustryIdentifier> industryIdentifiers = new ArrayList<IndustryIdentifier>();
private ReadingModes readingModes;
private Long pageCount;
private String printType;
private Double averageRating;
private Long ratingsCount;
private String maturityRating;
private Boolean allowAnonLogging;
private String contentVersion;
private ImageLinks imageLinks;
private String language;
private String previewLink;
private String infoLink;
private String canonicalVolumeLink;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* @return
* The title
*/
public String getTitle() {
return title;
}
/**
*
* @param title
* The title
*/
public String setTitle(String title) {
this.title = title;
return title;
}
/**
*
* @return
* The authors
*/
public String getAuthors() {
return authors;
}
/**
*
* @param authors
* The authors
*/
public void setAuthors(String authors) {
this.authors = authors;
}
/**
*
* @return
* The publisher
*/
public String getPublisher() {
return publisher;
}
/**
*
* @param publisher
* The publisher
*/
public void setPublisher(String publisher) {
this.publisher = publisher;
}
/**
*
* @return
* The publishedDate
*/
public String getPublishedDate() {
return publishedDate;
}
/**
*
* @param publishedDate
* The publishedDate
*/
public void setPublishedDate(String publishedDate) {
this.publishedDate = publishedDate;
}
/**
*
* @return
* The description
*/
public String getDescription() {
return description;
}
/**
*
* @param description
* The description
*/
public void setDescription(String description) {
this.description = description;
}
/**
*
* @return
* The industryIdentifiers
*/
public List<IndustryIdentifier> getIndustryIdentifiers() {
return industryIdentifiers;
}
/**
*
* @param industryIdentifiers
* The industryIdentifiers
*/
public void setIndustryIdentifiers(List<IndustryIdentifier> industryIdentifiers) {
this.industryIdentifiers = industryIdentifiers;
}
/**
*
* @return
* The readingModes
*/
public ReadingModes getReadingModes() {
return readingModes;
}
/**
*
* @param readingModes
* The readingModes
*/
public void setReadingModes(ReadingModes readingModes) {
this.readingModes = readingModes;
}
/**
*
* @return
* The pageCount
*/
public Long getPageCount() {
return pageCount;
}
/**
*
* @param pageCount
* The pageCount
*/
public void setPageCount(Long pageCount) {
this.pageCount = pageCount;
}
/**
*
* @return
* The printType
*/
public String getPrintType() {
return printType;
}
/**
*
* @param printType
* The printType
*/
public void setPrintType(String printType) {
this.printType = printType;
}
/**
*
* @return
* The averageRating
*/
public Double getAverageRating() {
return averageRating;
}
/**
*
* @param averageRating
* The averageRating
*/
public void setAverageRating(Double averageRating) {
this.averageRating = averageRating;
}
/**
*
* @return
* The ratingsCount
*/
public Long getRatingsCount() {
return ratingsCount;
}
/**
*
* @param ratingsCount
* The ratingsCount
*/
public void setRatingsCount(Long ratingsCount) {
this.ratingsCount = ratingsCount;
}
/**
*
* @return
* The maturityRating
*/
public String getMaturityRating() {
return maturityRating;
}
/**
*
* @param maturityRating
* The maturityRating
*/
public void setMaturityRating(String maturityRating) {
this.maturityRating = maturityRating;
}
/**
*
* @return
* The allowAnonLogging
*/
public Boolean getAllowAnonLogging() {
return allowAnonLogging;
}
/**
*
* @param allowAnonLogging
* The allowAnonLogging
*/
public void setAllowAnonLogging(Boolean allowAnonLogging) {
this.allowAnonLogging = allowAnonLogging;
}
/**
*
* @return
* The contentVersion
*/
public String getContentVersion() {
return contentVersion;
}
/**
*
* @param contentVersion
* The contentVersion
*/
public void setContentVersion(String contentVersion) {
this.contentVersion = contentVersion;
}
/**
*
* @return
* The imageLinks
*/
public ImageLinks getImageLinks() {
return imageLinks;
}
/**
*
* @param imageLinks
* The imageLinks
*/
public void setImageLinks(ImageLinks imageLinks) {
this.imageLinks = imageLinks;
}
/**
*
* @return
* The language
*/
public String getLanguage() {
return language;
}
/**
*
* @param language
* The language
*/
public void setLanguage(String language) {
this.language = language;
}
/**
*
* @return
* The previewLink
*/
public String getPreviewLink() {
return previewLink;
}
/**
*
* @param previewLink
* The previewLink
*/
public void setPreviewLink(String previewLink) {
this.previewLink = previewLink;
}
/**
*
* @return
* The infoLink
*/
public String getInfoLink() {
return infoLink;
}
/**
*
* @param infoLink
* The infoLink
*/
public void setInfoLink(String infoLink) {
this.infoLink = infoLink;
}
/**
*
* @return
* The canonicalVolumeLink
*/
public String getCanonicalVolumeLink() {
return canonicalVolumeLink;
}
/**
*
* @param canonicalVolumeLink
* The canonicalVolumeLink
*/
public void setCanonicalVolumeLink(String canonicalVolumeLink) {
this.canonicalVolumeLink = canonicalVolumeLink;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
这是我的JSON数据的Model类:
{{1}}
请帮助。
以下是Google Books API的示例JSON数据,我正在尝试解析: http://pastebin.com/Zvq7JkbN
答案 0 :(得分:0)
我没有完成整个代码。
但是这里是将List转换为String []的代码。
List<String> arr = new ArrayList<>();
arr.add("Hi ");
arr.add("Hello ");
arr.add("How ");
arr.add("are ");
arr.add("you? ");
String[] str = arr.toArray(new String[arr.size()]);
foreach(String s: str){
((TextView) findViewById(R.id.TEXTVIEWID)).append(s)
}