简体   繁体   中英

Android Gridview is not showing images from assets folder

I have a specific problem which has not be answered yet on stackoverflow; I have images in the assets folder numbered like 0.jpg, 1.jpg, 2.jpg etc. Using a for loop I select three images from the asssets folder and I am trying to add these images to a gridview but the images are not showing. The activity starts up okay just no images!

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);
        gridView = (GridView) findViewById(R.id.gridview_result);

        // Sets the Tag
        gridView.setTag(GRIDVIEW_TAG);

        /*
         * Adapt the image for the GridView format
         */
        imageAdapter = new ImageGridViewAdapter(getApplicationContext());
        gridView.setAdapter(imageAdapter);

        // Set the orientation to landscape
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        // Retrieve 3 images form the database which appear
        // similar
        for (int i = 0; i < 3; i++) {
            // System.out.println(Retrieval.distances[i][0]);
            image = Retrieval.distances[i][0];
            int num = (int) image;
            StringBuilder sBuilder = new StringBuilder();
            sBuilder.append(num);
            String imageNum = sBuilder.toString();
            System.out.println(imageNum);

            String file = imageNum + ".jpg";

            try {
                // get input stream
                InputStream ims = getAssets().open(file);
                Log.i("ERROR_IMS", ims + "");
                // load image as Drawable
                Drawable d = Drawable.createFromStream(ims, file);
                // set image to ImageView
                gridView.setBackground(d);
                Log.i("ERROR_d", d + "");
                Log.i("ERROR_gridview", gridView+"");
            } catch (IOException ex) {
                Log.e("I/O ERROR", "Failed when ...");
            }
        }
    }

I believe the issue is occurring in the try/catch. Any help will be much appreciated!

You should get all images first and set it to your adapter. // set image to ImageView gridView.setBackground(d); doesn't affect to your grid items view.

A good tutorial for it: guide

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM