1

I am Creating a gallery application..It is described here. http://www.androidhive.info/2012/02/android-gridview-layout-tutorial/

I am able to achieve this from drawable resources.. What i need is i want to fetch image url as json from server and to display it.. My Json Format is: http://52.42.251.70/testData/imagelist.php

Fragment Code:

public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        GridView gridView = (GridView)getView().findViewById(R.id.grid_view);

        // Instance of ImageAdapter Class
        gridView.setAdapter(new ImageAdapter(this.getActivity()));

        /**
         * On Click event for Single Gridview Item
         * */
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent i = new Intent(getActivity(), FullImageActivity.class);
                // passing array index
                i.putExtra("id", position);
                startActivity(i);
            }
        });
    }

Imageadapter.java

public class ImageAdapter extends BaseAdapter {
    private Context mContext;
    JSONObject jsonobject;
    DatabaseUserTable myDatadb;
    JSONArray jsonarray;
    String imageUrl = "";
    String id = "";
    ArrayList<String> Urls = new ArrayList<String>();
    // Keep all Images in array
    public Integer[] mThumbIds = {
            R.drawable.imagewall,R.drawable.imagewall,
            R.drawable.imagewall,R.drawable.imagewall,
            R.drawable.imagewall,R.drawable.imagewall,
            R.drawable.imagewall,R.drawable.imagewall,
            R.drawable.imagewall,R.drawable.imagewall,
            R.drawable.imagewall,R.drawable.imagewall,
            R.drawable.imagewall,R.drawable.imagewall,
            R.drawable.imagewall
    };

    // Constructor
    public ImageAdapter(Context c){
        mContext = c;
    }

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

    @Override
    public Object getItem(int position) {
        return mThumbIds[position];
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView = new ImageView(mContext);
        imageView.setImageResource(mThumbIds[position]);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setLayoutParams(new GridView.LayoutParams(220, 220));
        return imageView;
    }
}
4
  • you can also check this from same site. Commented Oct 3, 2016 at 10:50
  • Your data is not response in JSON format jsonviewer.stack.hu/… Commented Oct 3, 2016 at 10:52
  • @LiemVo is correct, you json is not valid. You need a { before each "id" tag, you have one before the first but none others. Commented Oct 3, 2016 at 10:56
  • 2
    Sorry.. my Mistake.. I hope now i made the json correct.. But how could i achieve loading image from json Commented Oct 3, 2016 at 11:13

2 Answers 2

2

You can use picasso library to do the same.

configuration

put compile 'com.squareup.picasso:picasso:2.5.2'in your module level build.gradle file.

Uses

replace imageView.setImageResource(mThumbIds[position]); with Picasso.with(getActivity()).load("URL of the image").into(imageView);

For your url it seems a list of image urls. so you can pass this list to your adapter after getting the response.

Sign up to request clarification or add additional context in comments.

6 Comments

GridView gridView = (GridView)getView().findViewById(R.id.grid_view) gridView.setAdapter(new ImageAdapter(this.getActivity())); @Manu Sharma I used this to call the adapter.. How could i load the images from server to a list and pass to Adapter.. I could use asyc task to fill the list. But after that how could i pass them to adapter
When you get the List of URLs from server. Pass it to your adapter constuctor. Change signature of your adapter constuctor to public ImageAdapter(Context context,List<String> urls){mContext = context;
When you get the List of URLs from server. Pass it to your adapter constuctor. Change signature of your adapter constuctor to public ImageAdapter(Context context,List<String> urls){mContext = context;mUrls=urls and change gridView.setAdapter(new ImageAdapter(this.getActivity())); to gridView.setAdapter(new ImageAdapter(this.getActivity(),urls/*which is list of url strings*/));. try it and tell me if face any problem.
I used Picasso.with(getActivity).load(mUrls).into(imageView) but i got error showing i cant use getActivity and cannot resolve method load as i used mUrls
|
1

Here is simple solution:

The new data on the server: https://dl.dropboxusercontent.com/u/31298901/demo/demo_image.txt

The AndroidManifest.xml file

<uses-permission android:name="android.permission.INTERNET" />
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

MainActivity class

public class MainActivity extends AppCompatActivity {

    GridView gridView;
    MyGridAdapter myGridAdapter;
    private static String DATA_URL = "https://dl.dropboxusercontent.com/u/31298901/demo/demo_image.txt";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        gridView = (GridView) findViewById(R.id.gridview);
        getData();
    }


    private void getData(){

        RequestQueue queue = Volley.newRequestQueue(this);

        StringRequest stringRequest = new StringRequest(Request.Method.GET, DATA_URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONArray allImageArray = jsonObject.optJSONArray("images");
                    if(allImageArray != null && allImageArray.length() > 0){

                        ArrayList<ImageObject> imageObjects = new ArrayList<>();
                        for(int i = 0; i < allImageArray.length();i++){
                            JSONObject jsonItem = allImageArray.optJSONObject(i);

                            imageObjects.add(new ImageObject(jsonItem));
                        }

                        myGridAdapter= new MyGridAdapter(MainActivity.this, imageObjects);

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                gridView.setAdapter(myGridAdapter);
                            }
                        });
                    }
                } catch (Exception e){

                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        stringRequest.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }
}

The layout for MainActivity activity_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.android.vad.gridview.MainActivity">

    <GridView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/gridview"
        android:columnWidth="120dp"
        android:verticalSpacing="10dp"
        android:numColumns="auto_fit">

    </GridView>
</RelativeLayout>

GridAdapter.java

public class MyGridAdapter extends BaseAdapter{
private Context context;
private ArrayList<ImageObject> imageObjects;

private LayoutInflater mLayoutInflate;


public MyGridAdapter (Context context, ArrayList<ImageObject> imageObjects){
    this.context = context;
    this.imageObjects = imageObjects;

    this.mLayoutInflate = LayoutInflater.from(context);
}

public int getCount() {
    if(imageObjects != null) return  imageObjects.size();
    return 0;
}

@Override
public Object getItem(int position) {
    if(imageObjects != null && imageObjects.size() > position) return  imageObjects.get(position);

    return null;
}

@Override
public long getItemId(int position) {
    if(imageObjects != null && imageObjects.size() > position) return  imageObjects.get(position).getId();
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder = null;
    if (convertView == null) {

        viewHolder = new ViewHolder();

        convertView = mLayoutInflate.inflate(R.layout.imageitem, parent,
                false);
        viewHolder.imageView = (ImageView) convertView.findViewById(R.id.image);
        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }
    ImageObject imageObject = (ImageObject) getItem(position);
    if(imageObject != null) {
        Glide
                .with(context)
                .load(imageObject.getImageUrl())
                .centerCrop()
                .crossFade()
                .into(viewHolder.imageView);
    }

    return convertView;
}

private class ViewHolder {
    public ImageView imageView;
}

}

imageitem.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="80dp"
    android:layout_height="120dp">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/image"/>
</LinearLayout>

ImageObject.java

public class ImageObject {
    private int id;
    private String imageUrl;

    public ImageObject(){

    }

    public  ImageObject(JSONObject jsonObject){
        if(jsonObject == null) return;
        this.id = jsonObject.optInt("id");
        this.imageUrl = jsonObject.optString("imageUrl");
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }
}

Dependencies in gradle build

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.mcxiaoke.volley:library:1.0.19'
}

1 Comment

Great.. It Works Perfect.. But i would like to know something.. When i add this to fragement runOnUiThread is showing error.. Also how could i show a loading? Blank screen is showing..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.