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

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

try
listofurls = image_urls.toArray(new String[image_urls.size()]);
Note: I suggest to rename listofurls to arrayOfURLs

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().

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

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.

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

Related

Get number of post in list array from another class. But It doesn't work?

I try to get number of post from arraylist in the class into mainactivity.
But it is wrong .
Here is my code.
public static int countNotify;
public static List<Notification> bindNotifyData(JsonElement list)
{
List<Notification> results= new ArrayList<>();
JsonObject dataJsonObj = list.getAsJsonObject();
// get data api from Json array "updates"
JsonArray notifyJsonArray = dataJsonObj.get("updates").getAsJsonArray();
ArrayList<Notification> notifyList = new ArrayList<>();
countNotify=notifyJsonArray.size();
if(notifyJsonArray != null && notifyJsonArray.size() > 0) {
for(int i = 0; i < notifyJsonArray.size(); i++) {
JsonObject notifyJson = (JsonObject) notifyJsonArray.get(i);
Notification notification = new Notification();
notification.setContent(notifyJson.get("content").getAsString());
// Convert timestamp to Datetime
String timestamp= notifyJson.get("time").getAsString();
notification.setTime(ConvertTimestamp(timestamp));
results.add(notification);
// count numbers of the post in the list json array.
}
}
return results;
}
And in the MainActivity.class
final int count=BindFetchDataHelper.countNotify;
But the value of count always is 0
Try to create a instance of your class
BindFetchDataHelper bindFetchDataHelper = new BindFetchDataHelper ()
and then call final int count=bindFetchDataHelper.countNotify;
I had the same issue, it should work now.
EDIT
Try like this :
public class BindFetchDataHelper {
private static int sTest;
static {
public static int countNotify=0;
}
public static int getcountNotify() {
return countNotify;
}
public static void setcountNotify(int setcountNotify) {
this.countNotify = countNotify;
}
//your others functions
}
And now to access variable or to set it :
BindFetchDataHelper bindFetchDataHelper = new BindFetchDataHelper ()
bindFetchDataHelper.setcountNotify(YOURVALUE); //set
int whatyourwant = bindFetchDataHelper.getcountNotify(); //get

How to create Async Task to build a RSSReader

Before getting down vote. Yes I read the forums before asking this question. RSSReader Async Task
Read that one above but I still don't get it.
The question:
I wrote een RSSReader in Java. This perfectly works in the console prints what I want etc. But in Android it doesn't work because it's not using een Async Task. Now I understood from the Google Documentation that there are three types to be entered AsyncTask something like that. I have no idea how I can implement this in my code. Do I need to make a seperate class extends it with AsyncTask and create and instance of my Reader and in it's doInBackground method call my reader or how do I need to do this.
This is the code of my RSSReader:
public class RSSReader {
//Lists to store headlines, descriptions & images
String url = "http://www.nu.nl/rss/Algemeen";
List<String> titleList;
List<String> descriptionList;
List<String> imageList;
public RSSReader(){
try {
titleList = readRSS(url, "<title>", "</title>");
descriptionList = listFilter(readRSS(url, "<description>", "</description>"), "&nbsp;", "");
imageList = readRSS(url, "<enclosure url \"", "\" length=\"0\" type=\"image/jpeg\"</enclosure>");
}
catch (IOException e){
}
}
public List<String> readRSS(String feedUrl, String openTag, String closeTag) throws IOException, MalformedURLException {
URL url = new URL(feedUrl);
BufferedReader reader= new BufferedReader(new InputStreamReader(url.openStream()));
String currentLine;
List<String> tempList = new ArrayList<String>();
while((currentLine = reader.readLine()) != null){
Integer tagEndIndex = 0;
Integer tagStartIndex = 0;
while (tagStartIndex >= 0){
tagStartIndex = currentLine.indexOf(openTag, tagEndIndex);
if(tagStartIndex >= 0){
tagEndIndex = currentLine.indexOf(closeTag, tagStartIndex);
tempList.add(currentLine.substring(tagStartIndex + openTag.length(), tagEndIndex) + "\n");
}
}
}
tempList.remove(0);
return tempList;
}
public List<String> getDesciptionList(){
return descriptionList;
}
public List<String> getTitleList(){
return titleList;
}
public List<String> getImageList(){
return imageList;
}
public List<String> listFilter(List<String> tempList, String require, String
replace){
//Creates new List
List<String> newList = new ArrayList<>();
//Loops through old list and checks for the 'require' variable
for(int i = 0; i < tempList.size(); i++){
if(tempList.get(i).contains(require)){
newList.add(tempList.get(i).replace(require, replace));
}
else{
newList.add(tempList.get(i));
}
}
return newList;
}
}
In RSSReader#readRSS,you do not check tempList.size()
and do not forget add
<uses-permission android:name="android.permission.INTERNET"/>
to your AndroidManifest.xml
for example
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new RssReaderAsyncTask(new RSSCallBack() {
#Override
public void success(RSSReader rssReader) {
// TODO That Should run on UI Thread if you update UI
// for example
final RSSReader reader = rssReader;
// you can use runOnUiThread or Handler update UI
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Toast
Toast.makeText(MainActivity.this, reader.getTitleList().toString(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void failed() {
// TODO That Should run on UI Thread if you update UI
Log.e("RSS", "failed");
}
}).execute("");
}
private class RssReaderAsyncTask extends AsyncTask<String, Integer, Integer> {
private RSSCallBack rssCallBack;
public RssReaderAsyncTask(RSSCallBack rssCallBack) {
this.rssCallBack = rssCallBack;
}
#Override
protected Integer doInBackground(String... params) {
// TODO
try {
RSSReader reader = new RSSReader();
rssCallBack.success(reader);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
rssCallBack.failed();
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
rssCallBack.failed();
e.printStackTrace();
}
return null;
}
}
private interface RSSCallBack {
void success(RSSReader rssReader);
void failed();
}
public class RSSReader {
// Lists to store headlines, descriptions & images
String url = "http://www.nu.nl/rss/Algemeen";
List<String> titleList;
List<String> descriptionList;
List<String> imageList;
public RSSReader() throws MalformedURLException, IOException {
titleList = readRSS(url, "<title>", "</title>");
descriptionList = listFilter(readRSS(url, "<description>", "</description>"), "&nbsp;", "");
imageList = readRSS(url, "<enclosure url \"", "\" length=\"0\" type=\"image/jpeg\"</enclosure>");
}
public List<String> readRSS(String feedUrl, String openTag, String closeTag)
throws IOException, MalformedURLException {
URL url = new URL(feedUrl);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String currentLine;
List<String> tempList = new ArrayList<String>();
while ((currentLine = reader.readLine()) != null) {
Integer tagEndIndex = 0;
Integer tagStartIndex = 0;
while (tagStartIndex >= 0) {
tagStartIndex = currentLine.indexOf(openTag, tagEndIndex);
if (tagStartIndex >= 0) {
tagEndIndex = currentLine.indexOf(closeTag, tagStartIndex);
tempList.add(currentLine.substring(tagStartIndex + openTag.length(), tagEndIndex) + "\n");
}
}
}
if (tempList.size() > 0) {
//TODO you do not check it
tempList.remove(0);
}
return tempList;
}
public List<String> getDesciptionList() {
return descriptionList;
}
public List<String> getTitleList() {
return titleList;
}
public List<String> getImageList() {
return imageList;
}
public List<String> listFilter(List<String> tempList, String require, String replace) {
// Creates new List
List<String> newList = new ArrayList<String>();
// Loops through old list and checks for the 'require' variable
for (int i = 0; i < tempList.size(); i++) {
if (tempList.get(i).contains(require)) {
newList.add(tempList.get(i).replace(require, replace));
} else {
newList.add(tempList.get(i));
}
}
return newList;
}
}
}
You are right, you need Asynctask. But it is too much to explain here, it has already been explained very thoroughly here, so you might wanna take a look:
https://stackoverflow.com/a/9671602/3673616
What you need to make sure is to run your network calls in doInBackground, you can manipulate the UI in onPreExcute and after finish in onpostExecute. For more details please visit the link.
Well i assume that you already know the code so in the doInBackground method should be the long running code, like getting information from internet/server etc. You can then return a string with success or error that will be catched from onPostExecute method, where you can just do what ever you like with the result.
So i would say no need for new class just extend async task in this, implement the 2 methods i mentioned and in the methods call the right function that you already have with just a litttle change for returning result.

Convert multidimensional java array list to string, store and restore

I am building a program that randomly generates multidimensional list arrays of the type :
ArrayList(ArrayList(ArrayList(String)));
My challenge is to find a way to save and restore these array lists once they have been (randomly) generated. I believe one solution is to convert them to a string and restore the array from that string although I can't seem to find a way to do so (I tried Json and deepToString). Please let me know if anyone has an idea. Thanks.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
Gson gson = new Gson();
if (savedInstanceState == null) {
//GEREATE MAP
GenMap();
jsonmaps = gson.toJson(maps);
} else {
maps = gson.fromJson(jsonmaps, new TypeToken<ArrayList<ArrayList<ArrayList<String>>>>() {
}.getType());
}
//LAYOUT MAP
MapLayout();
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
jsonmaps = savedInstanceState.getString("Sjsonmaps");
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("Sjsonmaps", jsonmaps);
}
The following program shows converting multidimensional array to jsonString and restore back to multidimensional array using same jsonString.
You can also store converted json String and restore back when required.
public static void main(String[] args) {
ArrayList<ArrayList<ArrayList<String>>> maps = new ArrayList<ArrayList<ArrayList<String>>>();
Gson gson = new Gson();
ArrayList<String> list10 = new ArrayList<String>();
list10.add("str10");
list10.add("str11");
list10.add("str12");
ArrayList<String> list11 = new ArrayList<String>();
list11.add("str20");
list11.add("str22");
list11.add("str23");
ArrayList<ArrayList<String>> list20 = new ArrayList<ArrayList<String>>();
list20.add(list10);
list20.add(list11);
ArrayList<ArrayList<String>> list21 = new ArrayList<ArrayList<String>>();
ArrayList<String> list13 = new ArrayList<String>();
list13.add("str30");
list13.add("str31");
list13.add("str32");
list21.add(list13);
maps.add(list20);
maps.add(list21);
String jsonString = gson.toJson(maps);
System.out.println(jsonString); // maps is converted to jsonString
// converted value is [[["str10","str11","str12"],["str20","str22","str23"]],[["str30","str31","str32"]]]
ArrayList<ArrayList<ArrayList<String>>> genratedMap = gson.fromJson(jsonString, new TypeToken<ArrayList<ArrayList<ArrayList<String>>>>() {}.getType());
System.out.println("genratedMap : " + genratedMap); // jsonString restored back to maps (ArrayList)
}
Note: In above program i have used Gson Library - https://github.com/google/gson
You could use standard serialization, since ArrayList and String are serializable.
Here is an example:
public static void main(String args[]) throws Exception{
ArrayList<String> obj = new ArrayList<>();
obj.add("Hello");
System.out.println(obj);
/* Writing */
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("myFile"));
oos.writeObject(obj);
oos.close();
/* Reading */
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("myFile"));
ArrayList<String> obj2 = (ArrayList<String>) ois.readObject();
ois.close();
System.out.println(obj2);
}

Passing List<classname> to ArrayAdapter

The problem is this adapter is giving the error although i have pass the Object array to it.(Read the methods belows then you will find what i want to know from you guys)
This method declares a List of private class objects. Then return that list of object to onPostExecute method.
private class DownloadXmlTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
try {
return loadXmlFromNetwork(urls[0]);
} catch (IOException e) {
return "I/O exception ae hy";
} catch (XmlPullParserException e) {
return "XML pull parser ke exception ae hy";
}
}
#Override
protected void onPostExecute(List<StackOverflowXmlParser.Entry> result) {
//Log.d(TAG,result.toString());
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,result);
setListAdapter(adapter);
}
private Object loadXmlFromNetwork(String urlString) throws XmlPullParserException, IOException {
InputStream stream = null;
// Instantiate the parser
StackOverflowXmlParser stackOverflowXmlParser = new StackOverflowXmlParser();
List<StackOverflowXmlParser.Entry> entries = null;
String title = null;
String url = null;
String summary = null;
try {
stream = downloadUrl(urlString);
entries = stackOverflowXmlParser.parse(stream);
} finally {
if (stream != null) {
stream.close();
}
}
for (StackOverflowXmlParser.Entry entry : entries)
{
Log.d(TAG, entry.link + " /" + entry.title);
}
return entries;
}
I think it should be onPostExecute(List<StackOverflowXmlParser.Entry> result)
And you AsyncTask should be
extends AsyncTask<smth, smth, List<StackOverflowXmlParser.Entry> >
ArrayAdapter<String> requires that you provide it a String[] or a List<String>. You are trying to pass in Object[], which is neither String[] nor List<String>. And, it would appear that you are really trying to populate the ListView with a list of StackOverflowXmlParser.Entry objects, which are not String objects.
My guess is that the right answer is for you to create an ArrayAdapter<StackOverflowXmlParser.Entry> instead of an ArrayAdapter<String>.
Regardless, you need to ensure that the data type in your declaration (String in ArrayAdapter<String>) matches the data type in your constructor parameter that supplies the data to be adapted.

AsyncTask Returns Error

I have been trying to parse XML files using Asynctask, following [1] and [2] tutorials. I have implemented a class in my Activity as follows:
private class GetRoutes extends AsyncTask<String, Void, String[]> {
#Override
protected String[] doInBackground(String... urls) {
String[] read;
try{
RouteReader route = new RouteReader();
read = route.getRoutes();
} catch(IOException iox){
read = new String[1];
read[0] = getResources().getString(R.string.loading_error);
} catch(ArrayIndexOutOfBoundsException aiob){
read = new String[1];
read[0] = getResources().getString(R.string.loading_error);
} catch(NullPointerException npe){
read = new String[1];
read[0] = getResources().getString(R.string.loading_error);
}
return read;
}
#Override
protected void onPostExecute(String[] result) {
values = result;
}
}
This is then called in my onCreate method as new GetRoutes().execute("test");.
However, when I try to run this, my app crashes as a result of a NullPointerException (logcat is available here).
Could you please guide me on how I can fix this?
For further reference, my RouteReader class is as follows:
public class RouteReader extends Reader{
public final static String routeURL =
"http://webservices.nextbus.com/service/publicXMLFeed?command=routeList&a=ttc";
private Map<String, String> routes;
public RouteReader()
throws IOException, ArrayIndexOutOfBoundsException{
super(new URL(routeURL));
routes = xmlToMap();
}
public String[] getRoutes(){
return (String[]) routes.keySet().toArray();
}
public String getRouteNum(String route){
return routes.get(route);
}
private Map<String, String> xmlToMap()
throws IOException, ArrayIndexOutOfBoundsException{
Map<String, String> data = new HashMap<String, String>();
String input;
do{
input = getReader().readLine();
if (input.startsWith("<route")){
String[] read = input.split("\"");
data.put(read[3], read[1]);
}
}while (!input.equals("</body>"));
return data;
}
}
from your log:
Caused by: java.lang.NumberFormatException: Invalid int: "1S"
this is probably caused in this line:
data.put(read[3], Integer.parseInt(read[1]));
We'll your log shows a NumberFormatException at RouteReader lines 35. That's not a NullPointerException - it's a failure to parse a string as an integer, because the string is "1S". You should work out what you want to do with invalid data, and handle it appropriately.
Additionally, you're comparing strings with == instead of equals, which is almost never what you want to do. Personally I wouldn't try to use string operations to parse the XML in the first place: use an XML parser... That's what it's there for. Your current approach is very brittle in the face of seemingly-harmless changes in the XML format.

Categories