2016-07-28 62 views
-1

我想將ArrayList轉換爲字符串並將其顯示在textview中。這裏是我的代碼:如何將數組轉換並顯示爲字符串在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; 
    } 
} 

}

我想從谷歌圖書API的JSON採取的作者和tvAuthor.setText((CharSequence) InfoList.get(position).getAuthors());位置BookAdaptergetView方法在列表視圖中顯示它。

但是,當我試圖從這個得到的數據:在doInBackground方法它給錯誤顯示不能將lis轉換爲字符串,錯誤在info.setAuthors(author);

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); 

這裏是我的JSON數據模型類:

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); 
} 
} 

請幫忙。

下面是谷歌圖書API的哪個我試圖解析樣本JSON數據: http://pastebin.com/Zvq7JkbN

+0

'ArrayList.toString()'將'ArrayList'轉換爲'String'。 – ifly6

+0

如果您需要從JSON中序列化一個對象,只需使用Guava併爲實例提供一個類文件。 – ifly6

+0

你的代碼非常麻煩。您創建infoList,但不要添加任何內容。您應該在每個循環中創建一個新的VolumeInfo,並將其添加到infoList。您還要繼續替換每個lopp中的作者值,而不是追加。 – lionscribe

回答

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) 
    } 
相關問題