Category

Uncategorized

Category

We use a callback when we need value from another Java class. Before making a callback, you should have basic knowledge of Java interfaces. We can use a callback in Android on different position according to requirements. In this tutorial, I will explain how to make callback? With help of callback, when a user clicks on adapter row image, TextView or on row, then how we can display the value of activity from which adapter called.

I am taking the example of my previous post Parsing JSON on Android using GSON and DataBinding. In this tutorial, I will add callback class and some other logic according to an example.

My example is that I want to get a name of the user when user will click on the ImageView. So I am creating Interface class.

package becody.com.simplelistview.callbacks;

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

public interface EdtImgCallBack {
    void fetchNameByCallback(String name);
}

 

This callback I will implement where I need value and I will send the reference of this callback to another class or adapter where I want to fetch the name of the user. So in my MainActivity.java class, I implement callback like this

public class MainActivity extends AppCompatActivity implements EdtImgCallBack

Now I will pass the reference of this callback in adapter through adapter constructor.

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

with this reference, when user will click on the ImageView or another TextView, then I will call callback method with this reference.

   holder.binding.edtImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edtImgCallBack.fetchNameByCallback(country.getName());
            }
        });

Now full code of AdapterBasicInfo.java is

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.callbacks.EdtImgCallBack;
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;
    private EdtImgCallBack edtImgCallBack;

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

    @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();
        }

        final BasicInfo country = basicInfoList.get(position);
        holder.binding.edtImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edtImgCallBack.fetchNameByCallback(country.getName());
            }
        });
        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();
        }
    }
}

and full code of MainActivity.java 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 android.widget.Toast;

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.callbacks.EdtImgCallBack;
import becody.com.simplelistview.data.BasicInfo;
import becody.com.simplelistview.databinding.ActivityMainBinding;
import becody.com.simplelistview.dto.InfoJSON;

public class MainActivity extends AppCompatActivity implements EdtImgCallBack {
    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, this);
            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);
    }

    @Override
    public void fetchNameByCallback(String name) {
        Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
    }
}

Note: If you still have any confusion in post tutorial, you can watch full post detail in Urdu and Hindi on

 

 

Download Source Code