ClassCastException: java.lang.Object[] cannot be cast to java.lang.String[] android
Solution 1
try
listofurls = image_urls.toArray(new String[image_urls.size()]);
Note: I suggest to rename listofurls to arrayOfURLs
Solution 2
You should use toArray
as mentioned above, but not in that way.
Either initialize the array first and fill it:
String[] urlArray = new String[image_urls.size()];
image_urls.toArray(urlArray);
After which, urlArray
will contain all the Strings from image_urls
, or pass in a zero-length String array:
listofurls = (String[]) image_urls.toArray(new String[0]);
See the documentation for toArray()
.
Solution 3
You just need to get the contents of arraylist in an array, right??
Can't u do like this?
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);
listofurls[i] = m ;
}
Solution 4
listofurls = image_urls.toArray(new String[0]);
that should do the trick for all cases, even if you don't know the size of the resulting array.
Solution 5
Try this:
ArrayList<String> stock_list = new ArrayList<String>();
stock_list.add("stock1");
stock_list.add("stock2");
String[] stockArr = new String[stock_list.size()];
stockArr = stock_list.toArray(stockArr);
for(String s : stockArr)
System.out.println(s);
Taken directly from here: link
Shweta
Updated on July 26, 2020Comments
-
Shweta almost 4 years
In my application I need to convert my arraylist to a string of an array. However, I am getting an error:
ClassCastException: java.lang.Object[] cannot be cast to java.lang.String[] android
At the line with
listofurls
I am getting the error:listofurls = (String[])image_urls.toArray();
This is the full code:
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); }