D4Developer D4Developer - 5 months ago 11
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.

customListAdapter:

public class CustomListAdapter extends BaseAdapter {

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

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


this.context=context;
this.products=product;

}

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

@Override
public Object getItem(int position) {
return null;
}

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

public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater=(LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
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);


...........
title.setText(productInfo.getTitle());

createDate.setText("Created Date: "+productInfo.getCreatedDate());
icon.setImageResource(R.drawable.go_right);
return rowView;

};
}


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

Answer

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)) { 
    if(currentActivity.contains("com.example.activity1")){
        // 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

or

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