Android - ClassCastException?
Asked Answered
S

3

5
@Override
public void onPause()
{
    super.onPause();
    save(notes.itemSelected);
}
@Override
public void onResume()
{
    super.onResume();
    notes.itemSelected.clear();
    notes.itemSelected = load();

}
@Override
public void onRestart()
{
    super.onRestart();
    notes.itemSelected.clear();
    notes.itemSelected = load();

}

private void save(final ArrayList<String> isChecked) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
 for(Integer i = 0; i < isChecked.size(); i++)
 {
     editor.putString(i.toString(), isChecked.get(i));
 }
editor.commit();
}

private ArrayList<String> load() {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
    ArrayList<String> reChecked = new ArrayList<String>();
    for(Integer i = 0; i < notes.getCount(); i++)
    {
        String s= i.toString();
        Log.e(TAG, s);
        reChecked.add(i, sharedPreferences.getString(s, "empty"));
    }
    return reChecked;
}

Here is my custom adapter whose instance called notes i am using in above code.

public class IconAdapter extends BaseAdapter
{
private Activity activity;
private Object[] data;
private ArrayList<HashMap<String,String>> listItems;
public static LayoutInflater inflater = null;
private PackageManager pm;
public ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();
public ArrayList<String> itemSelected = new ArrayList<String>();
public ArrayList<CheckBox> ctv = new ArrayList<CheckBox>();
//TextView textView;
CheckBox cb;
//ImageView imageView;
public CompleteTaskManager ctm = new CompleteTaskManager();

public IconAdapter(Activity a, ArrayList<HashMap<String,String>> items)
{
    activity = a;
    listItems = items;
    data = items.toArray();
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    pm = a.getPackageManager();


    for(int i = 0; i < items.size(); i++)
    {
        itemChecked.add(i,false);
    }


    for(int i = 0; i < items.size(); i++)
    {
        itemSelected.add(i, " ");
    }
     for(int i = 0; i < items.size(); i++)
    {
        cb  = new CheckBox(a);
        ctv.add(i,cb);
    }
}

public int getCount() {
    return listItems.size();
}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

public static class ViewHolder{
    public TextView textView;
    public ImageView imageView;
    public CheckBox checkBox;
}

public View getView(final int position, View convertView, ViewGroup parent)
{
    View row = convertView;
    final ViewHolder holder;
    if(convertView==null)
    {
        row = inflater.inflate(R.layout.item, parent, false);
        holder = new ViewHolder();
        holder.textView = (TextView)row.findViewById(R.id.text1);
        holder.checkBox = (CheckBox)row.findViewById(R.id.check);
        holder.imageView = (ImageView)row.findViewById(R.id.image);
        row.setTag(holder);
    }
    else
    {
        holder = (ViewHolder)row.getTag();

    }

    String s = data[position].toString();
    String[] tokens = s.split(",");
    String[] mToken = tokens[0].split("=");
    String taskName = mToken[1];
    holder.textView.setText(taskName);
    String[] mTokens = tokens[1].split("=");
    final String pkgName =  mTokens[1].substring(0, (mTokens[1].length() - 1));

    holder.checkBox.setTag(position);
    holder.checkBox.setChecked(itemChecked.get(position));
    /*for(int i = 0; i < itemSelected.length; i++)
    {
        if(itemSelected[i].equals(pkgName))
        {
            holder.checkBox.setChecked(true);
        }
    }*/
    ctv.set(position,holder.checkBox);
    holder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
    {
        public void onCheckedChanged(CompoundButton button, boolean b) {
            Integer posClicked = (Integer)button.getTag();
            if(b)
            {
                itemChecked.set(posClicked, b);
                itemSelected.set(posClicked, pkgName);
            }
            else
            {
                itemChecked.set(posClicked, b);
                itemSelected.set(posClicked, " ");
            }
        }
    });

   holder.checkBox.setChecked(itemChecked.get(position));

    try{
        Drawable icon =   pm.getApplicationIcon(pkgName);
        holder.imageView.setImageDrawable(icon);
    }
    catch (PackageManager.NameNotFoundException ne)
    {

    }
     row.setId(position);
     return row;
}

public boolean isChecked(int position)
{
    return itemChecked.get(position);
}
public String getPkgName(int position)
{
    return itemSelected.get(position);
}
public void removeItem(int position)
{
    listItems.remove(position);
}

}

Could anybody tell me why i am getting a ClassCastException at reChecked.add(i, sharedPreferences.getString(s, "empty"));. I mean it's strange that its telling me that i am casting boolean into string but how???? i did not even used boolean anywhere in this code.

Note. - notes.itemSelected is an ArrayList of string type.

Please help.

Slade answered 19/4, 2011 at 9:13 Comment(3)
I executed the code with dummy values .It worked for me.Post the whole code(atleast part where the isChecked arraylist is getting its values)so that we can have a look at it.P.S.:The class cast exception is thrown here because there is a preference with keyname that you specified that is not a String.Representation
@Representation i have posted more code above take a look and check if i did something wrong :(Slade
@Representation you must be executing this code on Windows based system as when i tried to execute the same code on my Windows seven it executed without any exception but when i tried to run it on my Mac OSX it is throwing an exception. weird....!!!!Slade
M
1

There reason has to be that you have a Shared Preferences with that key that is not a String.

The documentation says that in this case a ClassCastException is thrown:

Macymad answered 19/4, 2011 at 10:47 Comment(7)
@Roflcoptr i have read that thing too in documentation but i am not getting that where i have used boolean :( i did not even use it :( you seem to be an experienced person please take a good look at my code :(Slade
@Slade I think I don't need the code but the SharedPrefernces foile.Macymad
@Roflcoptr one of the strangest thing ever happened is that this code is running fine in Windows seven based system but not in my iMac. i mean how could its possible. i am using the same IDE and SDK in both. STRANGE!!!!Slade
@Slade and on an actual device? Maybe on your Mac the sharedPreferences aren't stored at all.Macymad
@Roflcoptr on actual device it did not generate any exception. why so? why only MAC OSX throwing an exception?Slade
@Slade I can't answer this. I would guess either some issues with permissions or directory structures.Macymad
@Roflcoptr hmmmm it could be the reason but thanks for your help :)Slade
C
3

A ClassCastException will occur when you are not type casting the data types properly. I have corrected your save method:

private void save(final ArrayList<String> isChecked) {
    SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    for(Integer i = 0; i < isChecked.size(); i++)
    {
        editor.putString(i+"", isChecked.get(i));
    }
    editor.commit();
}

Similarly you should also change the code in your load method...

Cummine answered 19/4, 2011 at 11:36 Comment(4)
i tried your solution but it is still giving me the same error :(Slade
sharedPreferences.getString(i+"", "empty") in this part of the code.Slade
you should write null inplace of "empty"Cummine
i think this problem is because i am using Mac OSX. I don't know what is wrong with Mac but on Win 7 this code is running fine. Thanks for you help. :)Slade
S
3

Actually i figure it out why i was getting ClassCastException. first of all it wasn't MAC OSX which we were thinking was the reason for this exception. And i just found out why this exception was occurring.

Let me explain what happened. Before storing the ArrayList of String type i saved one ArrayList of type Boolean using same for() loop so it means that key with the name of i.toString() was already taken and i was calling my save() method in onPause() which was never called because i was not able to run my app on device or emulator because of this exception so the saved keys were never overwritten. And when i figured it out i just changed the key name to j+"0" (just a random one) and bang it's stopped throwing the exception.

P.S. Exception was there because the key was already used.

I hope it will help others who are facing or might face the same situation in future.

@Roflcoptr and @Durga I really appreciate your help guys thanks a lot.

Thanks.

Slade answered 20/4, 2011 at 18:45 Comment(0)
M
1

There reason has to be that you have a Shared Preferences with that key that is not a String.

The documentation says that in this case a ClassCastException is thrown:

Macymad answered 19/4, 2011 at 10:47 Comment(7)
@Roflcoptr i have read that thing too in documentation but i am not getting that where i have used boolean :( i did not even use it :( you seem to be an experienced person please take a good look at my code :(Slade
@Slade I think I don't need the code but the SharedPrefernces foile.Macymad
@Roflcoptr one of the strangest thing ever happened is that this code is running fine in Windows seven based system but not in my iMac. i mean how could its possible. i am using the same IDE and SDK in both. STRANGE!!!!Slade
@Slade and on an actual device? Maybe on your Mac the sharedPreferences aren't stored at all.Macymad
@Roflcoptr on actual device it did not generate any exception. why so? why only MAC OSX throwing an exception?Slade
@Slade I can't answer this. I would guess either some issues with permissions or directory structures.Macymad
@Roflcoptr hmmmm it could be the reason but thanks for your help :)Slade

© 2022 - 2024 — McMap. All rights reserved.