java.lang.ClassCastException: java.lang.Integer cannot be cast to java.util.HashMap

Posted by kongkea on Stack Overflow See other posts from Stack Overflow or by kongkea
Published on 2012-11-20T04:11:41Z Indexed on 2012/11/20 4:59 UTC
Read the original article Hit count: 1613

Filed under:
|
|

I've got this Error When I click listview to show full image size. how can i solve it?

Error

11-20 10:27:47.039: D/AndroidRuntime(5078): Shutting down VM
11-20 10:27:47.039: W/dalvikvm(5078): threadid=1: thread exiting with uncaught exception (group=0x40c061f8)
11-20 10:27:47.047: E/AndroidRuntime(5078): FATAL EXCEPTION: main
11-20 10:27:47.047: E/AndroidRuntime(5078): java.lang.ClassCastException: java.lang.Integer cannot be cast to java.util.HashMap
11-20 10:27:47.047: E/AndroidRuntime(5078):     at com.example.mylistview.MainActivity$1.onItemClick(MainActivity.java:103)
11-20 10:27:47.047: E/AndroidRuntime(5078):     at android.widget.AdapterView.performItemClick(AdapterView.java:292)
11-20 10:27:47.047: E/AndroidRuntime(5078):     at android.widget.AbsListView.performItemClick(AbsListView.java:1173)
11-20 10:27:47.047: E/AndroidRuntime(5078):     at android.widget.AbsListView$PerformClick.run(AbsListView.java:2701)
11-20 10:27:47.047: E/AndroidRuntime(5078):     at android.widget.AbsListView$1.run(AbsListView.java:3453)
11-20 10:27:47.047: E/AndroidRuntime(5078):     at android.os.Handler.handleCallback(Handler.java:605)
11-20 10:27:47.047: E/AndroidRuntime(5078):     at android.os.Handler.dispatchMessage(Handler.java:92)
11-20 10:27:47.047: E/AndroidRuntime(5078):     at android.os.Looper.loop(Looper.java:137)
11-20 10:27:47.047: E/AndroidRuntime(5078):     at android.app.ActivityThread.main(ActivityThread.java:4514)
11-20 10:27:47.047: E/AndroidRuntime(5078):     at java.lang.reflect.Method.invokeNative(Native Method)
11-20 10:27:47.047: E/AndroidRuntime(5078):     at java.lang.reflect.Method.invoke(Method.java:511)
11-20 10:27:47.047: E/AndroidRuntime(5078):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
11-20 10:27:47.047: E/AndroidRuntime(5078):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
11-20 10:27:47.047: E/AndroidRuntime(5078):     at dalvik.system.NativeStart.main(Native Method)

MainActivity

public class MainActivity extends Activity {

public static final int DIALOG_DOWNLOAD_JSON_PROGRESS = 0;
private ProgressDialog mProgressDialog;

ArrayList<HashMap<String, Object>> MyArrList;


@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    // Permission StrictMode
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    // Download JSON File   
    new DownloadJSONFileAsync().execute();

}


@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_DOWNLOAD_JSON_PROGRESS:
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("Downloading.....");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setCancelable(true);
        mProgressDialog.show();
        return mProgressDialog;
    default:
        return null;
    }
}

// Show All Content
public void ShowAllContent()
{
    // listView1
    final ListView lstView1 = (ListView)findViewById(R.id.listView1); 
    lstView1.setAdapter(new ImageAdapter(MainActivity.this,MyArrList));
    lstView1.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View v, int position,
                long id) {
            HashMap<String, Object> hm = (HashMap<String, Object>) lstView1.getAdapter().getItem(position);
            String imagePath = (String) hm.get("photo");
             Intent i = new Intent(MainActivity.this,FullImageActivity.class);
                i.putExtra("fullImage", imagePath);
                startActivity(i);
        }
    });

}

public class ImageAdapter extends BaseAdapter 
{
    private Context context;
    private ArrayList<HashMap<String, Object>> MyArr = new ArrayList<HashMap<String, Object>>();

    public ImageAdapter(Context c, ArrayList<HashMap<String, Object>> myArrList) 
    {
        // TODO Auto-generated method stub
        context = c;
        MyArr = myArrList;
    }

    public int getCount() {
        // TODO Auto-generated method stub
        return MyArr.size();
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub

        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);


        if (convertView == null) {
            convertView = inflater.inflate(R.layout.activity_column, null); 
        }

        // ColImage
        ImageView imageView = (ImageView) convertView.findViewById(R.id.ColImgPath);
        imageView.getLayoutParams().height = 80;
        imageView.getLayoutParams().width = 80;
        imageView.setPadding(5, 5, 5, 5);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
         try
         {
             imageView.setImageBitmap((Bitmap)MyArr.get(position).get("ImageThumBitmap"));
         } catch (Exception e) {
             // When Error
             imageView.setImageResource(android.R.drawable.ic_menu_report_image);
         }

        // ColImgID
        TextView txtImgID = (TextView) convertView.findViewById(R.id.ColImgID);
        txtImgID.setPadding(10, 0, 0, 0);
        txtImgID.setText("ID : " + MyArr.get(position).get("id").toString());

        // ColImgName
        TextView txtPicName = (TextView) convertView.findViewById(R.id.ColImgName);
        txtPicName.setPadding(50, 0, 0, 0);
        txtPicName.setText("Name : " + MyArr.get(position).get("first_name").toString());   

        return convertView;

    }

} 

// Download JSON in Background
public class DownloadJSONFileAsync extends AsyncTask<String, Void, Void> {

    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
    }

    @Override
    protected Void doInBackground(String... params) {
        // TODO Auto-generated method stub

        String url = "http://192.168.10.104/adchara1/";
        JSONArray data;
        try {
            data = new JSONArray(getJSONUrl(url));

            MyArrList = new ArrayList<HashMap<String, Object>>();
            HashMap<String, Object> map;

            for(int i = 0; i < data.length(); i++){
                JSONObject c = data.getJSONObject(i);
                map = new HashMap<String, Object>();
                map.put("id", (String)c.getString("id"));
                map.put("first_name", (String)c.getString("first_name"));

                // Thumbnail Get ImageBitmap To Object
                map.put("photo", (String)c.getString("photo"));
                map.put("ImageThumBitmap", (Bitmap)loadBitmap(c.getString("photo")));

                // Full (for View Popup)
                map.put("frame", (String)c.getString("frame"));

                MyArrList.add(map);
            }


        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(Void unused) {
        ShowAllContent(); // When Finish Show Content
        dismissDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
        removeDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
    }


}


/*** Get JSON Code from URL ***/
public String getJSONUrl(String url) {
    StringBuilder str = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    try {
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) { // Download OK
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                str.append(line);
            }
        } else {
            Log.e("Log", "Failed to download file..");
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return str.toString();
}


/***** Get Image Resource from URL (Start) *****/
private static final String TAG = "Image";
private static final int IO_BUFFER_SIZE = 4 * 1024;
public static Bitmap loadBitmap(String url) {
    Bitmap bitmap = null;
    InputStream in = null;
    BufferedOutputStream out = null;

    try {
        in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);

        final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
        out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
        copy(in, out);
        out.flush();

        final byte[] data = dataStream.toByteArray();
        BitmapFactory.Options options = new BitmapFactory.Options();
        //options.inSampleSize = 1;

        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
    } catch (IOException e) {
        Log.e(TAG, "Could not load Bitmap from: " + url);
    } finally {
        closeStream(in);
        closeStream(out);
    }

    return bitmap;
}

 private static void closeStream(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                android.util.Log.e(TAG, "Could not close stream", e);
            }
        }
    }

 private static void copy(InputStream in, OutputStream out) throws IOException {
    byte[] b = new byte[IO_BUFFER_SIZE];
    int read;
    while ((read = in.read(b)) != -1) {
        out.write(b, 0, read);
    }
}
 /***** Get Image Resource from URL (End) *****/

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

}

FullImageActivity

String imagePath = getIntent().getStringExtra("fullImage");
    if(imagePath != null && !imagePath.isEmpty()){
        File imageFile = new File(imagePath);
        if(imageFile.exists()){
            Bitmap myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
            ImageView iv = (ImageView) findViewById(R.id.fullimage);
            iv.setImageBitmap(myBitmap);
        }
    }

© Stack Overflow or respective owner

Related posts about android

Related posts about integer