D4Developer D4Developer - 4 months ago 8
Android Question

how to know which activity is calling custom list adapter?

Basically what I want to do is: I have a listview with custom list adapter in my application. But I want to change a TextLabel based on the calling activity of the adapter. I have three lists in activity like Product list,Favorites and History. So is there any way that we can get calling(parentActivity)?

Easy solution is design different layouts for all lists but I don't want that kind of redundant code.


public class CustomListAdapter extends BaseAdapter {

private final Context context;
private ArrayList<Product> products=new ArrayList<>() ;

public CustomListAdapter(Context context, ArrayList<Product> product) {



public int getCount() {
return products.size();

public Object getItem(int position) {
return null;

public long getItemId(int position) {
return 0;

public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater=(LayoutInflater) context
View rowView=inflater.inflate(R.layout.product_list_item, null, true);

TextView title = (TextView) rowView.findViewById(R.id.product_title);
//TextView url = (TextView) rowView.findViewById(R.id.product_url);
TextView createDate = (TextView) rowView.findViewById(R.id.product_create_date);
ImageView icon=(ImageView)rowView.findViewById(R.id.imageArrow);


createDate.setText("Created Date: "+productInfo.getCreatedDate());
return rowView;


So I want to change created date with modified date for history list.


When you call your adapter you pass the activity context. You can use that to identify the calling activity like this

Solution 1

String currentActivity = this.context.getClass().getName();
if(!TextUtils.isEmpty(currentActivity)) { 
        // do this
    else if(currentActivity.contains("com.example.activity2")){
        // do that

Solution 2

if(this.context instanceof Activity1){
    // do this
else if(this.context instanceof Activity2){
    // do that

Note: This is how you should be calling your adapter

CustomListAdapter myCustomListAdapter = new CustomListAdapter(this, myProducts); // In activity


CustomListAdapter myCustomListAdapter = new CustomListAdapter(getActivity(), myProducts); // In Fragment