Tags
Android
Asked 8 years ago
21 Sep 2016
Views 2411
ajamil

ajamil posted

Error in Andorid : ArrayList can not cast to CharSequence

Hi

i am beginner to Android and playing with some code

    ArrayList<String> list = new ArrayList<String>();
            
            	JSONArray jsona = new JSONArray(result);
            	
                for(int i=0; i < jsona.length(); i++){
                	JSONObject jsonObject=  jsona.getJSONObject(i);
	                int userid= Integer.parseInt(jsonObject.optString("userid"));
	        
	                String username= jsonObject.optString("username").toString();
	                String pair=userid+":"+username;
	                
	                list.add(pair);
 
                }
 
               Toast.makeText(getBaseContext(),(CharSequence) list, Toast.LENGTH_LONG).show();


and i am getting error is

java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.lang.CharSequence
its right you cant cast ArrayList to CharSequence direct like this - jagdish  
Sep 21 '16 11:46
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

i think you dont need ArrayList instead simply use String and append in loop

String list=new String();//placed
//removed     ArrayList<String> list = new ArrayList<String>();
 
            	JSONArray jsona = new JSONArray(result);
            	
                for(int i=0; i < jsona.length(); i++){
                	JSONObject jsonObject=  jsona.getJSONObject(i);
	                int userid= Integer.parseInt(jsonObject.optString("userid"));
	        
	                String username= jsonObject.optString("username").toString();
                     //  changed here : simply append to string 	
                     list+=userid+":"+username;
	              //remvoed    list.add(pair);
 
                }
 
               Toast.makeText(getBaseContext(),(CharSequence) list, Toast.LENGTH_LONG).show();

hope it work
Post Answer