Category

ListView

Category

Gson is Java library which we use to convert Java Objects to JSON representation or String to JSON object.  Gson is open source library which is available on  GSON library. A serializer allows to convert a JSON string to corresponding Java type and a deserializer allows to convert from Java to a JSON. With the help of JSON Serialize, you can change JSON key name in your Java Object. Let’s we do an example, first I am sync GSON library in my Android project.

dependencies {
    implementation 'com.google.code.gson:gson:2.8.5'
}

I have local JSON file.

{
  "data": [
    {
      "name": "Rana Aamer Sohail",
      "phone": "923446859884",
      "address": "Islamabad, Rawalpindi Pakistan",
      "basic_info": {
        "father_name": "Rana Aluddin",
        "brother": "Rana "
      }
    },
    {
      "name": "Malik Munawar",
      "phone": "923446859884",
      "address": "street 24, Banglasdesh",
      "basic_info": {
        "father_name": "Rana Aluddin",
        "brother": "Rana "
      }
    },
    {
      "name": "Glod In Mind",
      "phone": "923446859884",
      "address": "delhi, India, pune",
      "basic_info": {
        "father_name": "Rana Aluddin",
        "brother": "Rana "
      }
    }
  ]
}

Now create Pojo according to JSON schema.

package becody.com.simplelistview.dto;

import java.util.List;

/**
 * Created by ranaaamersohail on 6/9/18.
 */

public class InfoJSON {
    private List<Data> data;

    public List<Data> getData() {
        return data;
    }

    public void setData(List<Data> data) {
        this.data = data;
    }

    public static class Data {
        private String name;
        private String phone;
        private String address;
        private BasicInfo basic_info;

        public String getName() {
            return name;
        }

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

        public String getPhone() {
            return phone;
        }

        public void setPhone(String phone) {
            this.phone = phone;
        }

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        public BasicInfo getBasic_info() {
            return basic_info;
        }

        public void setBasic_info(BasicInfo basic_info) {
            this.basic_info = basic_info;
        }
    }

    public static class BasicInfo{
        private String father_name;
        private String brother;

        public String getFather_name() {
            return father_name;
        }

        public void setFather_name(String father_name) {
            this.father_name = father_name;
        }

        public String getBrother() {
            return brother;
        }

        public void setBrother(String brother) {
            this.brother = brother;
        }
    }
}

Now I am creating adapter row XML design.

<?xml version="1.0" encoding="utf-8"?>
<layout>

    <data>

        <variable
            name="basicInfo"
            type="becody.com.simplelistview.data.BasicInfo" />
    </data>

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="@{basicInfo.name}"
                android:textSize="16sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="@{basicInfo.contact}"
                android:textSize="16sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="@{basicInfo.address}"
                android:textSize="16sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="@{basicInfo.fatherName}"
                android:textSize="16sp" />
        </LinearLayout>
    </RelativeLayout>
</layout>

 

Now create AdapterBasicInfo.java class

package becody.com.simplelistview.adapters;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.List;

import becody.com.simplelistview.R;
import becody.com.simplelistview.data.BasicInfo;
import becody.com.simplelistview.databinding.RowBasicInfoBinding;

/**
 * Created by ranaaamersohail on 6/2/18.
 */

public class AdapterBasicInfo extends BaseAdapter {
    private Context _context;
    private List<BasicInfo> basicInfoList;

    public AdapterBasicInfo(Context _context, List<BasicInfo> countryList) {
        this._context = _context;
        this.basicInfoList = countryList;
    }

    @Override
    public int getCount() {
        return basicInfoList.size();
    }

    @Override
    public Object getItem(int position) {
        return basicInfoList.indexOf(basicInfoList.get(position));
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Holder holder;
        if (convertView == null) {
            RowBasicInfoBinding binding = DataBindingUtil.inflate(LayoutInflater.from(_context),R.layout.row_basic_info, parent, false);
            holder = new Holder(binding);
            convertView = binding.getRoot();
            convertView.setTag(holder);
        } else {
            holder = (Holder) convertView.getTag();
        }

        BasicInfo country = basicInfoList.get(position);
        holder.bind(country);

        return convertView;
    }

    private class Holder {
        private final RowBasicInfoBinding binding;

        public Holder(RowBasicInfoBinding binding) {
            this.binding = binding;
        }

        public void bind(BasicInfo item) {
            binding.setBasicInfo(item);
            binding.executePendingBindings();
        }
    }
}

full code of MainActivity is

package becody.com.simplelistview;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

import com.google.gson.Gson;

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

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import becody.com.simplelistview.adapters.AdapterBasicInfo;
import becody.com.simplelistview.data.BasicInfo;
import becody.com.simplelistview.databinding.ActivityMainBinding;
import becody.com.simplelistview.dto.InfoJSON;

public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding binding;
    private AdapterBasicInfo adapterCountry;
    private List<BasicInfo> basicInfoList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        initComponents();

    }


    private void initComponents() {
        basicInfoList = new ArrayList<>();
        loadJsonFile();
    }

    private void loadJsonFile() {
        InputStream inputStream = getResources().openRawResource(R.raw.info);
        String jsonString = new Scanner(inputStream).useDelimiter("\\A").next();
        try {
            Gson gson = new Gson();
            InfoJSON infoJSON = gson.fromJson(jsonString, InfoJSON.class);
            for (InfoJSON.Data data : infoJSON.getData()) {
                BasicInfo basicInfo = new BasicInfo();
                basicInfo.setName(data.getName());
                basicInfo.setContact(data.getPhone());
                basicInfo.setAddress(data.getAddress());
                basicInfo.setFatherName(data.getBasic_info().getFather_name());
                basicInfoList.add(basicInfo);
            }

            adapterCountry = new AdapterBasicInfo(this, basicInfoList);
            binding.innerContent.listView.setAdapter(adapterCountry);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Gson provides us two method, fromJson() and toJson(). fromJson() method convert your String file in Java object and toJson() method convert your Java object into String.

Note:  If you still have any confusion then you can watch video tutorial in Hindi and Urdu.


Download Source Code