簡體   English   中英

如何在textview中將arraylist轉換並顯示為String

[英]How to convert and display arraylist to String in textview

我想將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中獲取作者,並在tvAuthor.setText((CharSequence) InfoList.get(position).getAuthors());BookAdapter類的getView方法的列表視圖中顯示該作者tvAuthor.setText((CharSequence) InfoList.get(position).getAuthors()); 位置。

但是,當我嘗試從中獲取數據時:在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);

另外,在嘗試運行應用程序時,它會強制關閉,在此處的列表視圖中給出Null Pointer Exception:

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

請幫忙。

這是我要解析的Google Books API的示例JSON數據: http : //pastebin.com/Zvq7JkbN

我沒有閱讀完整的代碼。

但是這里是將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)
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM