0

I am working on a project in which I get images URL dynamically from database. I previous created a gallery in LinearLayout which is fine. But I want to create a Gridview in which i can add the photos in same way. Can anyone give me hint or idea of from where to start. I have also created a GridView fragment (I want gridview in fragment) and ImageAdapter class according to tutorial here.
http://developer.android.com/guide/topics/ui/layout/gridview.html

This tutorial is for loading images from local resources which I don't need. Also I have tried searching online but couldn't find an appropriate way. Any help would be appreciated. Thank You!.

Edit:

ImageAdapter.java

package com.example.imran.myapp;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;

/**
 * Created by imran on 28-Mar-16.
 */
public class ImageAdapter extends BaseAdapter {
    private Context mContext;
    String url = "https://www.google.com/images/srpr/logo11w.png";
    public ImageAdapter(Context c) {
        mContext = c;
    }

    public int getCount() {
        return mThumbIds.length;
    }

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

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

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {
            // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(200, 200));
        } else {
            imageView = (ImageView) convertView;
        }

        Picasso.with(this.mContext).load(url).resize(100, 100).into(imageView);
        Picasso.with(this.mContext).setLoggingEnabled(true);

        return imageView;
    }

    // references to our images
    public Integer[] mThumbIds = {
          /*R.drawable.title_background,
            R.drawable.title_background,
            R.drawable.title_background,  R.drawable.sample_7,
            R.drawable.sample_0, R.drawable.sample_1,
            R.drawable.sample_2, R.drawable.sample_3,
            R.drawable.sample_4, R.drawable.sample_5,
            R.drawable.sample_6, R.drawable.sample_7,
            R.drawable.sample_0, R.drawable.sample_1,
            R.drawable.sample_2, R.drawable.sample_3,
            R.drawable.sample_4, R.drawable.sample_5,
            R.drawable.sample_6, R.drawable.sample_7
            */
    };
}

gridgallery.java

package com.example.imran.myapp;


import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;


/**
 * A simple {@link Fragment} subclass.
 */
public class gridgallery extends Fragment {


    public gridgallery() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_gridgallery, null);
        Myserver myserver = new Myserver();

        postStringRequest(myserver.url+"/api/albums/getalbums.php",view);
        return view;

        // Inflate the layout for this fragment
        //return inflater.inflate(R.layout.fragment_gridgallery, container, false);
    }

    public View postStringRequest(final String url,final View view){
        //final View view = inflater.inflate(R.layout.fragment_gallery, null);
        final TextView t = (TextView)view.findViewById(R.id.main_msg_gallery);
        // Instantiate the RequestQueue.
        RequestQueue queue = Volley.newRequestQueue(getContext());

        // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        // Display the first 500 characters of the response string

                       // LinearLayout linearLayout = (LinearLayout)view.findViewById(R.id.fragment_gallery);
                        //GridView gridView = (GridView)view.findViewById(R.id.fragment_gridgallery);
                        //gridView.setAdapter(new ImageAdapter(getContext()));
                        try {
                            JSONArray jsonObj = new JSONArray(response);
                            Myserver myserver = new Myserver();
                            for (int i=0;i<jsonObj.length();i++){
                                JSONObject c = jsonObj.getJSONObject(i);

                                //ImageView albumpic = new ImageView(getContext());
                                //Picasso.with(getContext()).load(myserver.url+"/images/thumbs/tn_"+c.getString("album_thumbnail")).centerCrop().resize(200,200).into(albumpic);
                                //linearLayout.addView(albumpic);
                                // gridView.addView(albumpic);

                                GridView gridView = (GridView) view.findViewById(R.id.fragment_gridgallery);
                                ImageAdapter myadap = new ImageAdapter(getContext());
                                myadap.url = myserver.url+"/images/thumbs/tn_"+c.getString("album_thumbnail");
                                gridView.setAdapter(myadap);

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                t.setText("Server error - Unable to reach server");
                Toast.makeText(getContext(), "Unable to reach server", Toast.LENGTH_LONG).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("getalbum", "getalbum");
                return params;
            }
        };
        queue.add(stringRequest);
        return view;
    }



}
Imran Aslam
  • 208
  • 2
  • 15

2 Answers2

1

This is one that I recently worked on. There are number of ways you can do this, but you will always have to extend/import ListAdapter, which is base for all of those types for listViews. Here are the ways:

  1. Create an adapter like you'd always do when making ListView, or list-array, that extends ListAdapter. (For me, I called it GroupTileAdapater.java)
  2. You will have to create its own view for the tile, which is just like you'd create for the each list. For me, I just created a layout and fills up the entire view with imageview, and you can customize whatever you want.(It was called media_tile.xml inside res/layout)
  3. Then you'd specify the image inside the adapter, by finding the corresponding id that you instantiated in your tile image view. (By calling Picasso's method, which you can take a look at the question I posted recently, Load image through picasso)

To be more specific, you'd override 4 methods from listAdapter, getCount, getItem, getItemId, getView, and when setting the adapter, you'd pass in your image lists to constructor, and inside getView is where you'd show the images.

  1. Now, you'd just set adapter to whatever fragment/activity you are in, with whatever layout you have initialized your gridview.

And I don't know what your URL type is, but if it starts with file/content, take a look at the following, contentUri:show image, and incorporate with picasso. There are youtube videos out there that can help you out as well to understand more about listAdapter. Hope it helps!

Community
  • 1
  • 1
xosuma
  • 267
  • 1
  • 3
  • 11
  • Thank you. Please look at my edited question and see the code. In Second file my loop runs multiple time. But no matter how many times loop run images doesn't show until i uncomment something in `public Integer[] mThumbIds` . – Imran Aslam Mar 28 '16 at 16:19
  • @ImranAslam Do images show up? How are the images shown? And didn't you say you wanted to show the images that were coming from the server? Then those uncommented codes become unnecessary. Take a look at this example, I think you are almost there. [baseAdapter example](http://www.pcsalt.com/android/listview-using-baseadapter-android/) – xosuma Mar 28 '16 at 17:46
  • thats not what i want. – Imran Aslam Mar 29 '16 at 14:57
  • T. Lee yes images shows up. The surprising thing is that i uncomment those images but images shown are different. – Imran Aslam Mar 29 '16 at 14:58
0

Thanks guys for your help, I finally figured it out.

ImageAdapter.java

public class ImageAdapter extends BaseAdapter {
    private Context mContext;

    public ImageAdapter(Context c, String urls[]) {
        mContext = c;
        mThumbIds = urls;
        //myurls = urls;
    }

    public int getCount() {
        return mThumbIds.length;
    }

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

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

    public String getURL(int position){
        return mThumbIds[position];
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {
            // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(200, 200));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(20, 20, 20, 20);
        } else {
            imageView = (ImageView) convertView;
        }

       // imageView.setImageResource(mThumbIds[position]);

        Picasso.with(mContext)
                .load(mThumbIds[position])
                .into(imageView);
        return imageView;
    }

    //private ArrayList<String> myurls = new ArrayList<String>();

    // references to our images
    private String[] mThumbIds = {

    };
}

gridgallery.java (fragment)

package com.example.imran.myapp;


    public class gridgallery extends Fragment {


    public gridgallery() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_gridgallery, null);
        Myserver myserver = new Myserver();
        postStringRequest(myserver.url + "/api/albums/getalbums.php", view);
        return view;
    }

    public View postStringRequest(final String url,final View view){
        //final View view = inflater.inflate(R.layout.fragment_gallery, null);
        // Instantiate the RequestQueue.
        RequestQueue queue = Volley.newRequestQueue(getContext());

        // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        GridView gv = (GridView)view.findViewById(R.id.fragment_gridgallery);
                        ArrayList<String> urls2 = new ArrayList<String>();
                        try {
                            JSONArray jsonObj = new JSONArray(response);
                            Myserver myserver = new Myserver();
                            for (int i=0;i<jsonObj.length();i++){
                                JSONObject c = jsonObj.getJSONObject(i);
                                String imgurl = myserver.url+"/images/thumbs/tn_"+c.getString("album_thumbnail");
                                urls2.add(imgurl);
                            }
                            String myabc[] = urls2.toArray(new String[urls2.size()]);
                            final ImageAdapter myadapter = new ImageAdapter(getContext(),myabc);
                            gv.setAdapter(myadapter);
                            gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    Toast.makeText(getContext(),myadapter.getURL(position),Toast.LENGTH_LONG).show();
                                }
                            });


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getContext(), "Unable to reach server", Toast.LENGTH_LONG).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("getalbum", "getalbum");
                return params;
            }
        };
        queue.add(stringRequest);
        return view;
    }



}
Imran Aslam
  • 208
  • 2
  • 15