Grid image adapter sort

I built some gridView with images and everything works fine. I have a set of images and i can click on each of them and proceed to another activity as i want. The problem is - when i add new image to adapter - it's added at the end of the stack. How can i rearrange the displaying of the images from new to old and not from old to new like now. (I did something by myself (as you can see in comments), and it's displayed like i want but when i click on image i get the wrong image):

final ArrayList<String> imgString = new ArrayList<>();
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
        Query query = reference
        query.addListenerForSingleValueEvent(new ValueEventListener() {
            public void onDataChange(DataSnapshot dataSnapshot) {
                for ( DataSnapshot singleSnapshot :  dataSnapshot.getChildren()){
                    // photos.add(singleSnapshot.getValue(Photo.class));
                //setup our image grid
                int gridWidth = getResources().getDisplayMetrics().widthPixels;
                int imageWidth = gridWidth/NUM_GRID_COLUMNS;

                final ArrayList<String> imgUrls = new ArrayList<String>();
                for(int i = 0; i < imgString.size(); i++){
//                for(int i = imgString.size()-1; i >=0 ; i--){
//                    imgUrls.add(imgString.get(i));
                GridImageAdapter adapter = new GridImageAdapter(ProfileActivity.this,R.layout.layout_grid_imageview,"", imgUrls);

                gridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        Intent intent = new Intent(ProfileActivity.this, ViewPostActivity.class);

            public void onCancelled(DatabaseError databaseError) {
                Log.d(TAG, "onCancelled: query cancelled.");

1 answer

  • answered 2018-09-23 07:20 navylover

    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        PostKey=imgString.get(i);//here i is the position of the view in the adapter.

    As you did:

    for(int i = imgString.size()-1; i >=0 ; i--){
                  imgUrls.add(imgString.get(i));//imgUrls.get(0) stored imgString.get(imgString.size()-1)

    When you click item in 0 position, its imgUrls doesn't points imgString.get(0), but imgString.get(imgString.size()-1).

    Edited: Try this: