Pages

Wednesday, 1 November 2017

Custom Gridview using image and text

Hi guys,
 Here i'm showing How to create custom gridview with image and text. Here images are loading from url to gridview items.Following is the array format.

[{
"name": "Asus",
"imageurl": "https://madofcoding.000webhostapp.com/asus.jpg"

},
{
"name": "Samsung",
"imageurl": "https://madofcoding.000webhostapp.com/samsung.jpg"

},
{
"name": "Lenovo",
"imageurl": "https://madofcoding.000webhostapp.com/lenovo.jpg"
},
{
"name": "HTC",
"imageurl": "https://madofcoding.000webhostapp.com/htc.jpg"
}]

My url to show this json format is https://madofcoding.000webhostapp.com/gridviewitems.json

Now the server side enough.

Let's Come to Android side. First Step is create your own project in android studio.After gradle building just go to gradle app module.Your gradle should be like following for our gridview project.

apply plugin: 'com.android.application'
android {
compileSdkVersion 26 buildToolsVersion "26.0.1" defaultConfig {
applicationId "com.blogspot.madofcoding.customgrridview" minSdkVersion 15 targetSdkVersion 26 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" }
buildTypes {
release {
minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' }
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations' })
compile 'com.android.support:appcompat-v7:26.+' compile 'com.android.support.constraint:constraint-layout:1.0.2' compile 'com.mcxiaoke.volley:library-aar:1.0.0' testCompile 'junit:junit:4.12'} 


Next go to AndroidManifest.xml. Should be as follows.


<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.blogspot.madofcoding.customgrridview">

    <uses-permission android:name="android.permission.INTERNET" />

    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:roundIcon="@mipmap/ic_launcher_round"        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>

</manifest>

We need Following Class files And MainActivity file in our project.
1.AppController.java
2.ViewAdapter.java
3.LruBitmapCache.java
4.gridview_items.java
5.MainAcctivity.java

Following are the xml resource files
1.activity_main.xml
2.row.xml


Now I'm going to discussing about row.xml file,
row.xml file is to create our custom gridview items.Here i'm going to create a network imageview and a textview to display the name that shown in json array.shown code is the row.xml

row.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical" android:layout_width="match_parent"    android:layout_height="match_parent">
    <com.android.volley.toolbox.NetworkImageView        android:layout_width="100dp"        android:layout_height="100dp"        android:id="@+id/imageView"/>
    <TextView        android:layout_width="100dp"        android:layout_height="wrap_content"        android:id="@+id/imageViewText"/>

</LinearLayout>


Another resource file is activity_main.xml and it should be like following code

activity_main.xml
 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.blogspot.madofcoding.customgrridview.MainActivity">

    <GridView        android:layout_width="match_parent"        android:layout_height="match_parent"        android:id="@+id/grid_view"        android:numColumns="auto_fit"/>



</LinearLayout>

In activity_main.xml i'm creating a gridview only.

Now let's go to Java files following are the java codes to create our custom gridview


AppController.java 


package com.blogspot.madofcoding.customgrridview;

/** * Created by Mad on 11/1/2017. */
import android.app.Application;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.blogspot.madofcoding.customgrridview.LruBitmapCache;

/** * Created by XianInfotech on 10/27/2017. */
public class AppController extends Application {

    public static final String TAG = AppController.class.getSimpleName();

    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;

    private static AppController mInstance;

    @Override    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized AppController getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public ImageLoader getImageLoader() {
        getRequestQueue();
        if (mImageLoader == null) {
            mImageLoader = new ImageLoader(this.mRequestQueue,
                    new LruBitmapCache());
        }
        return this.mImageLoader;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        // set the default tag if tag is empty        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}


  
LruBitmapCache.java

package com.blogspot.madofcoding.customgrridview;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.toolbox.ImageLoader;

/** * Created by mad on 11/1/2017. */

public class LruBitmapCache extends LruCache<String, Bitmap> implements ImageLoader.ImageCache {
    public static int getDefaultLruCacheSize() {
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemory / 8;

        return cacheSize;
    }

    public LruBitmapCache() {
        this(getDefaultLruCacheSize());
    }

    public LruBitmapCache(int sizeInKiloBytes) {
        super(sizeInKiloBytes);
    }

    @Override    protected int sizeOf(String key, Bitmap value) {
        return value.getRowBytes() * value.getHeight() / 1024;
    }

    @Override    public Bitmap getBitmap(String url) {
        return get(url);
    }

    @Override    public void putBitmap(String url, Bitmap bitmap) {
        put(url, bitmap);
    }
}


gridview_items.java

package com.blogspot.madofcoding.customgrridview;

/** * Created by mad on 11/1/2017. */
public class gridview_items {

    String name;
    String imgUrl;
    public gridview_items(){

    }
    public gridview_items(String name,String imgUrl){
        this.name=name;
        this.imgUrl=imgUrl;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getImgUrl() {
        return imgUrl;
    }

    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }
}



Now we need to create an Adapter class for showing json datas to our gridview items.
ViewAdapter.java


package com.blogspot.madofcoding.customgrridview;
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.NetworkImageView; import java.util.List; /** * Created by mad on 11/1/2017. */public class ViewAdapter extends BaseAdapter{ private List<gridview_items> gridviewItems; private ImageLoader gridviewImageloader; private Context context; public ViewAdapter(Context context,List<gridview_items> gridviewItems ){ this.gridviewItems=gridviewItems; this.context=context; } @Override public int getCount() { return gridviewItems.size(); } @Override public Object getItem(int location) { return gridviewItems.get(location); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup viewGroup) { if(convertView == null){ LayoutInflater li = (LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE); convertView = li.inflate(R.layout.row,null); } TextView textView_name = (TextView) convertView.findViewById(R.id.imageViewText); NetworkImageView networkimageview_img = (NetworkImageView) convertView.findViewById(R.id.imageView); gridview_items gridview_itemsList=gridviewItems.get(position); String gridview_img_url=gridview_itemsList.getImgUrl(); gridviewImageloader = AppController.getInstance().getImageLoader(); gridviewImageloader.get(gridview_img_url,ImageLoader.getImageListener(networkimageview_img,R.mipmap.ic_launcher,R.mipmap.ic_launcher)); textView_name.setText(gridview_itemsList.getName()); networkimageview_img.setImageUrl(gridview_img_url,gridviewImageloader); return convertView; } }

Now we can go to our main class and it's MainActivity.java 


MainActivity.java

package com.blogspot.madofcoding.customgrridview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.GridView;
import android.widget.ListView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;

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

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private GridView gridView;
    private List<gridview_items> gridview_itemsList = new ArrayList<gridview_items>();
    private ViewAdapter viewAdapter;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        makeShopNameArrayRequest();

        gridView = (GridView) findViewById(R.id.grid_view);
        viewAdapter = new ViewAdapter(this,gridview_itemsList);
        gridView.setAdapter(viewAdapter);

    }

    //Downloading Json Valuess from Internet Using Json Array Request    public void makeShopNameArrayRequest() {
        String url="https://madofcoding.000webhostapp.com/gridviewitems.json";
        // Creating volley request obj        JsonArrayRequest movieReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        //hidePDialog();
                        // Parsing json                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject categoryObj = response.getJSONObject(i);
                                gridview_items gridview_items = new gridview_items();
                                gridview_items.setName(categoryObj.getString("name"));
                                gridview_items.setImgUrl(categoryObj.getString("imageurl"));

                                // adding movie to movies array                                gridview_itemsList.add(gridview_items);

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

                        }

                        // notifying list adapter about data changes                        // so that it renders the list view with updated data                        viewAdapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                //hidePDialog();
            }
        });

        // Adding request to request queue        AppController.getInstance().addToRequestQueue(movieReq);
    }
}

You can run the app to your android adb device or phone...

Enjoy coding  :-)
Thank you.


No comments:

Post a Comment