ClassCastException: java.lang.Object[] 不能 cast to java.lang.String[] android

2022-08-31 16:47:49

在我的应用程序中,我需要将数组列表转换为数组的字符串。但是,我收到一个错误:

ClassCastException: java.lang.Object[] cannot be cast to java.lang.String[] android

在行我得到错误:listofurlslistofurls = (String[])image_urls.toArray();

这是完整的代码:

public class Test2 extends AsyncTask<Void, Void, Void> 
{
  String[] listofurls ;
  private static final String url = "http://www.tts.com/album_pro/array_to_encode";
  JSONParser jParser = new JSONParser();
  ArrayList<String> image_urls = new ArrayList<String>();

  protected void onPreExecute() {
    //Log.e(LOG_CLASS, "in side assyntask");
  }

  protected Void doInBackground(Void... voids) {
    Log.v("Async","Async");
    JSONObject json = jParser.getJSONFromUrl(url);

    try {
      JSONObject seo = json.getJSONObject("SEO");
      JSONArray folio = seo.getJSONArray("Folio");

      // JSONArray image_urls1 = new JSONArray();
      //String s1=seo.getString("Folio");

      for(int i=0;i<folio.length();++i) {
        String m = folio.getString(i);
        Log.v("M"+i,m);
        image_urls.add(m);
        Log("test-url"+image_urls);
      }
    } catch(Exception e) {
      e.printStackTrace();
    }

    listofurls = (String[])image_urls.toArray();  //ERROR OCCURS HERE

    return null;
  }

  private void Log(String string) {
    Log.v("Test",string);
  }

  protected void onProgressUpdate(Integer... progress) { }

  protected void onPostExecute(Void result) {
    mAdapter = new ImagePagerAdapter(getSupportFragmentManager(),listofurls.length );
    mAdapter.setImageurls(listofurls);
    mPager.setAdapter(mAdapter);
  }

答案 1

尝试

listofurls = image_urls.toArray(new String[image_urls.size()]);

注意:我建议将listofurls重命名为arrayOfURLs


答案 2

您应该如上所述使用,但不是以这种方式使用。toArray

首先初始化数组并填充它:

String[] urlArray = new String[image_urls.size()];
image_urls.toArray(urlArray);

之后, 将包含 来自 的所有字符串,或传入长度为零的字符串数组:urlArrayimage_urls

listofurls = (String[]) image_urls.toArray(new String[0]);

请参阅 toArray() 的文档