Where is my static context? - java

I'm brand new to android programming and I'm trying to use a gridviewpager with fragments. My code is:
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid);
final Resources res = getResources();
GridViewPager pager = (GridViewPager) findViewById(R.id.gridpager);
pager.setOnApplyWindowInsetsListener(new OnApplyWindowInsetsListener() {
#Override
public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
// Adjust page margins:
// A little extra horizontal spacing between pages looks a bit
// less crowded on a round display.
final boolean round = insets.isRound();
int rowMargin = res.getDimensionPixelOffset(R.dimen.page_row_margin);
int colMargin = res.getDimensionPixelOffset(round ?
R.dimen.page_column_margin_round : R.dimen.page_column_margin);
pager.setPageMargins(rowMargin, colMargin);
// GridViewPager relies on insets to properly handle
// layout for round displays. They must be explicitly
// applied since this listener has taken them over.
pager.onApplyWindowInsets(insets);
return insets;
}
});
// MyPagerAdapter adapter=new MyPagerAdapter();
pager.setAdapter(new MyPagerAdapter(Activity.getFragmentManager()));
}
public class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
case 2: return SecondFragment.newInstance("SecondFragment, Instance 2");
default: return SecondFragment.newInstance("SecondFragment, Default");
}
}
#Override
public int getCount() {
return 3;
}
}
}
I've collapsed some to be concise. The error is in this line:
pager.setAdapter(new MyPagerAdapter(Activity.getFragmentManager()));
This returns the error:
Non-static method 'getFragmentManager()' cannot be referenced from a static context
But I don't know what is static in my code. I've tried assigning everything I can think of to variables but still can't get this. Thanks for your help.

Activity is the name of a class. By stating Activity.getFragmentManager(), you are attempting to call a method on the class itself rather than a specific instance of the class.
In your case, you don't need the Activity. section at all - just call getFragmentManager() itself:
pager.setAdapter(new MyPagerAdapter(getFragmentManager()));

Related

Fragment Crashing when receiving data from an Activity

Good day all,
I have an issue where my activity is making a network call and when the network call is completed, it makes some changes in the activity using the data from the JSON object received from the call, it then passes the object down to the fragments in the same activity. These fragments are in a TabLayout.
I had this same issue which I asked here at this SO Question That sorted it out but I seem to be having the same issue, even after it worked for a little bit after not changing anything significant. I was just adding more fields I wanted to change?
The issue I have is that if I put a System.out.println() it prints out the correct data. The minute I want to set say a TextView with the data I receive in the Fragment the app Crashes with Nullpointer. When I debug it with the Debug in Android studio, the TextView I'm setting is always null for some reason.
Activity Code that does the initial Network call:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listings);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
handleIntent(getIntent());
}
private void handleIntent(Intent aIntent) {
if (aIntent != null) {
String tradeType = aIntent.getStringExtra("itemType");
String tradeId = aIntent.getStringExtra("itemId");
presenter = new ItemPresenterImpl(this, ItemBuyNowActivity.this);
presenter.doListingServiceCall(tradeId); // <------- This is the where I send the Trade Id so I can do the network call.
} else {
System.out.println("Intent is null in " + ItemBuyNowActivity.class.getSimpleName());
}
}
Interface between Activity and Presenter:
public interface ItemPresenter {
void doListingServiceCall(String itemId); //<------- Comes to this Interface
void doToolbarBackgroundImageCall(TradeItem aTradeItem);
}
Class the implements the Presenter:
#Override
public void doListingServiceCall(String aItemId) { // <------- This is where the network call starts
String homeURL = BobeApplication.getInstance().getWsURL() + mContext.getString(R.string.ws_url_item) + aItemId;
BobeJSONRequest jsObjRequest = new BobeJSONRequest(Request.Method.GET, homeURL, null, this, this);
VolleySingleton.getInstance().addToRequestQueue(jsObjRequest, "ListingRequest");
}
#Override
public void doToolbarBackgroundImageCall(TradeItem aTradeItem) {
ImageRequest request = new ImageRequest(aTradeItem.getItem().getImageUrl(),
new Response.Listener<Bitmap>() {
#Override
public void onResponse(Bitmap bitmap) {
Drawable drawable = new BitmapDrawable(mContext.getResources(), bitmap);
mItemView.loadBackgroundImage(drawable);
}
}, 0, 0, null,
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
mItemView.displayErrorMessage(VolleyErrorHelper.getErrorType(error, mContext) + " occurred downloading background image");
}
});
VolleySingleton.getInstance().addToRequestQueue(request, "ListItemToolbarBackgroundImageRequest");
}
#Override
public void onResponse(Object response) {
Gson gson = new Gson();
TradeItem tradeItem = gson.fromJson(response.toString(), TradeItem.class);
mItemView.populateListViews(tradeItem); // <------- This is the where I send the Object so the views in the activity can be manipulated
doToolbarBackgroundImageCall(tradeItem);
}
Method in the Activity that handles
#Override
public void populateListViews(TradeItem aTradeItem) {
mOverviewPresenter = new OverviewPresenterImpl(new OverviewListItemFragment(), aTradeItem);
OverviewListItemFragment.setData(aTradeItem); //<------- This is the where I send the Object to the fragment so i can manipulate the views in the fragment
}
class TabAdapter extends FragmentPagerAdapter {
public TabAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
if (position == 0) {
fragment = new OverviewListItemFragment();
}
if (position == 1) {
fragment = new DescriptionListItemFragment();
}
if (position == 2) {
fragment = new ShippingListItemFragment();
}
if (position == 3) {
fragment = new PaymentListItemFragment();
}
return fragment;
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
if (position == 0) {
return "Overview";
}
if (position == 1) {
return "Description";
}
if (position == 2) {
return "Shipping";
}
if (position == 3) {
return "Payment";
}
return null;
}
}
The Fragment that receives the data:
public class OverviewListItemFragment extends Fragment implements OverviewView {
private static TextView mOverViewHeading;
public OverviewListItemFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.overview_list_item_fragment, container, false);
mOverViewHeading = (TextView) view.findViewById(R.id.frag_overview_heading_textview);
return view;
}
#Override
public void populateOverviewViews(final TradeItem aTradeItem) {
System.out.println("Overview Trade Object title is:" + aTradeItem.getItem().getTradeTitle()); // <------- This is print statement works 100% but when I try setting mOverViewHeading to the text in aTradeItem.getItem().getTradeTitle() I get a Null pointer Exception.
}
public static void setData(TradeItem aTradeItem) {
System.out.println("Overview Trade Object title is:" + aTradeItem.getItem().getTradeTitle()); // <------- This is print statement works 100% but when I try setting mOverViewHeading to the text in aTradeItem.getItem().getTradeTitle() I get a Null pointer Exception.
mOverViewHeading.setText(aTradeItem.getItem().getTradeTitle());// <------- This is where it crashes and mOverViewHeading is still null at this point.
}
}
EDIT: Sorry I forgot the LogCat:
02-05 17:08:21.554 30512-30512/com.example.app E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.app.ui.fragments.OverviewListItemFragment.setData(OverviewListItemFragment.java:46)
at com.example.app.ui.activities.ItemBuyNowActivity.populateListViews(ItemBuyNowActivity.java:95)
at com.example.app.listing.ItemPresenterImpl.onResponse(ItemPresenterImpl.java:62)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
My thinking is that the view I'm trying to set isn't "Active" (if thats the right word) at the time it receives the data, because when I run the debugger with a break point at the method that receives the data in the Fragment, the mOverViewHeading TextView id is null, even though I have the findViewById in the onCreate, also tried placing it in the onCreateView() but both times failed. I also tried placing the findViewById in the same method that gets called when the response is successful but before I try setting the setText() on the TextView.
Thank you
OverviewListItemFragment I assume this is not your added fragment instance, but the class.
I suggest the following changes: remove static from setData and your TextView, leave it, if you really know how it works. I don't think it is necessary or recommendable.
private OverviewListItemFragment mFrag; //declare globally
mFrag = new OverviewListItemFragment();
//if you do not want to add it now, ignore the following line
getSupportFragmentManager().beginTransaction().add(R.id.yourContainer, mFrag, "mFrag").commit();
now call mFrag.setData everytime you want to set your data. Check if your mFrag is null, then reinitialize, and maybe re-add, or whatever you want to do.
Edit: Now that I know that you use a ViewPager, I suggest the following:
Do the above. I don't think it is recommendable to have static methods in this Context. You get an error because you are trying to reach a TextView in your Fragment. This was initialized in a ViewPager/PagerAdapter, and the PagerAdapter holds the reference to the used instance of your fragment.
You can access your used fragment through
Fragment mFragment = pagerAdapter.getFragment(0); //frag at position 0
with some casting, you will be able to find your (now NOT static) method:
((OverviewListItemFragment)pagerAdapter.getFragment(0)).setData(YOUR_DATA);
Please add some try/catch. check if your fragment is null, because it is possible that your fragment is recycled in the FragmentPagerAdapter, because it reached the offset. Another way to achieve this, would be to store your required data, and update it everytime your fragment gets visible as described here.
Edit 2: Obviously, You'll need some changed in your Adapter:
I would recommend creating an array containing your fragment in the constructor:
//global in your adapter:
private Fragment[] fragments;
public CustomPagerAdapter(FragmentManager fm) {
super(fm);
fragments = new GameFragment[4];
fragments[0] = new MyFragment();
fragments[1] = new SecondFragment();
....
}
public Fragment getItem(int position) {
return fragments[position];
}
public Fragment getFragment(int position) {
return fragments[position];
}

How to update All Pages in Page Viewer?

I have a Page Viewer with three pages with ArrayLists in them, represented as "Tomorrow" "Today" and "Yesterday". I also have a Drawer that allows to change settings of the Lists.
When the Drawer closes, I want the ListsViews (or the entire page fragment) to update to show three new ArrayLists that were created after the new settings were applied.
So far, I managed to be able to update "Yesterday" and "Tomorrow" (When sliding to yesterday, tomorrow updates and vice versa), I think that is because "Today" never gets destroyed.
Either way, I would really like to see all three update as soon as the Drawer closes.
Here is the code for my Adapter:`
private class MyPagerAdapter extends FragmentPagerAdapter {
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
ListFragmentOfTomorrow torrowFragment =new ListFragmentOfTomorrow();
ListFragmentOfToday todayFragment = new ListFragmentOfToday();
ListFragmentOfYesterday yestFragment = new ListFragmentOfYesterday();
public MyPagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos)
{
switch (pos) {
case 0:
torrowFragment.newInstance(tomorrowArrayList, MainActivity.this);
registeredFragments.put(0, torrowFragment);
return torrowFragment;
case 1:
todayFragment.newInstance(todayArrayList, MainActivity.this);
registeredFragments.put(1, todayFragment);
return todayFragment;
case 2:
yestFragment.newInstance(yesterdayArrayList, MainActivity.this);
registeredFragments.put(2, yestFragment);
return yestFragment;
default:
todayFragment.newInstance(todayArrayList, MainActivity.this);
registeredFragments.put(3, todayFragment);
return todayFragment;
}
}
#Override
public int getCount() {
return 3;
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}`
This is the code for one of the page Fragment (all three are basically the same):
public class ListFragmentOfToday extends Fragment
{
static ExpandListAdapter ExpAdapter;
static ExpandableListView expndList;
static Context context;
static ArrayList<Game> todayArrayList;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_list_of_today, container, false);
expndList = new ExpandableListView(context);
expndList = (ExpandableListView)v.findViewById(R.id.FragmentedExpandableListView);
ExpAdapter = new ExpandListAdapter(context,todayArrayList);
expndList.setAdapter(ExpAdapter);
return v;
}
public static ListFragmentOfToday newInstance(ArrayList<Game> todayArrayListIn, Context contextIn)
{
ListFragmentOfToday todayFragment = new ListFragmentOfToday();
context = contextIn;
todayArrayList = todayArrayListIn;
return todayFragment;
}
public void RefreshList(ArrayList<Game> todayArrayListIn)
{
todayArrayList=todayArrayListIn;
ExpAdapter.notifyDataSetChanged();
}
}
This is the code for when the Drawer closes:
#Override
public void onDrawerClosed(View drawerView)
{
//Here, the new ArrayLists are created(...)
ListFragmentOfTomorrow tomorrowFragmentToUpdate = (ListFragmentOfTomorrow)pagerAdapter.getRegisteredFragment(0);
tomorrowFragmentToUpdate.RefreshList(updatedTomorrowArrayList);
ListFragmentOfToday todayFragmentToUpdate = (ListFragmentOfToday)pagerAdapter.getRegisteredFragment(1);
todayFragmentToUpdate.RefreshList(updatedTodayArrayList);
ListFragmentOfYesterday yesterdayFragmentToUpdate = (ListFragmentOfYesterday)pagerAdapter.getRegisteredFragment(2);
yesterdayFragmentToUpdate.RefreshList(updatedYesterdayArrayList);
}
Question: How can I get all three pages to show the new updated arraylists as soon as the drawer closes?
As a new developer and a new StackOverflow user, I would also like to get any feedback on my code writing and my question format. Thank you.
Thank you Thomas! That worked. I tried notifyDataSetChanged() and getItemPosition(Object object), but never together.
dhke - I saw the instantiating fragments when I was looking for an answer, but understood the difference to newInstance()...

Android: Access a fragment instance from MainActivity

I've started coding a small app using Android Studio's pre-defined tabbed Layout with Fragments (SectionsPagerAdapter, ViewPager).
I've got a task running in the MainActivity.class main/Ui thread which at one point shows a dialog with the onClick method
#Override
public void onClick(DialogInterface dialog, int which) {
category = eventsToDisplay.get(which);
averageFragment.category = category;
dialog.dismiss();
}
But I can't get the averageFragment.category = category; assignment to work.
In the MainActivity's onCreate method I call averageFragment = (AverageFragment) getSupportFragmentManager().findFragmentByTag(AverageFragment.tag); but this gives me a NullPointerException.
I have already tried the following solutions (most of which are from this website):
getSupportFragmentManager().findFragmentById(R.id.fragment_average)
getSupportFragmentManager().findFragmentByTag(AverageFragment.tag) <-- basically a static variable created upon instantiating the fragment.
mSectionsPageAdapter.getItem(1)
all of which give me either a NPE or IllegalStateException.FragmentNotAttachedToView.
Other relevant code:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
switch (position) {
case 0:
return InspectionFragment.newInstance(position + 1);
case 1:
return AverageFragment.newInstance(position + 1);
case 2:
return RegulationsFragment.newInstance(position + 1);
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
Any ideas on how to access the fragment from the main activity?
Check the location where you assign the instance of your adapter to the pager. The exception your getting means that the fragment hasn't loaded to the view yet, which is likely given that you're calling your assignment:
averageFragment = (AverageFragment) getSupportFragmentManager().findFragmentByTag(AverageFragment.tag);
from the onCreate() method. Try moving this assignment to the onResume(), which should ensure that your fragment has been loaded into the view and is accessible through the supportFragmentManager. Also make sure this assignment is occurring after you set the pager's adapter within the lifecycle of your activity.

Passing data between two Fragments in a VIewPager (Android) (NullPointerException)

So basically I have 2 Fragments - FragmentConverter and FragmentFavourites, and I have one MainActivity. I'm trying to pass 4 arrays from the first fragment to the second one using an Interface called Communicator. The specific snippets are show below:
public interface Communicator {
public void respond(String[] names, String[] codes, String[] symbols, int[] images);
}
This is a method inside FragmentFavourites:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
String[] checkedNames = new String[counter];
String[] checkedCodes = new String[counter];
String[] checkedSymbols = new String[counter];
int[] checkedImages = new int[counter];
comm = (Communicator) getActivity();
int index = 0;
if (item.getItemId() == R.id.action_save){
for (int i=0;i<checked.size();i++){
if (checked.get(i) == true){
checkedNames[index] = names[i];
checkedCodes[index] = codes[i];
checkedSymbols[index] = symbols[i];
checkedImages[index] = images[i];
index++;
}
}
comm.respond(checkedNames, checkedCodes, checkedSymbols, checkedImages);
}
return super.onOptionsItemSelected(item);
}
This is the implemented interface method inside MainActivity:
#Override
public void respond(String[] names, String[] codes, String[] symbols,
int[] images) {
// TODO Auto-generated method stub
FragmentConverter frag = (FragmentConverter) fragmentPagerAdapter.getItem(1);
frag.changeData(names, codes, symbols, images);
}
And this is a method that collects the data in FragmentConverter:
public void changeData(String[] names, String[] codes, String[] symbols, int[] images){
this.names = names;
this.codes = codes;
this.symbols = symbols;
this.images = images;
Log.d("TEST", symbols.length + names.length + codes.length + images.length + "");
tvOneRate.setText(names[1]);
}
Now the problem is that whenever I try to change a ui component inside FragmentConverter, I get a NullPointerException, though the Log.d statement returns the correct results.
EDIT1: getItem() method of FragmentPagerAdapter:
#Override
public Fragment getItem(int i) {
// TODO Auto-generated method stub
Fragment frag = null;
if (i == 0){
frag = new FragmentFavourites();
}
if (i == 1){
frag = new FragmentConverter();
}
return frag;
}
EDITED:
When you call fragmentPagerAdapter.getItem(1) you are getting a new instance of the fragment so you are referring to a different object. this is why the view is null and you get the NullPointerException. If you need an adapter for only 2 fragments, you can try with something like that:
public class YourPagerAdapter extends android.support.v4.app.FragmentPagerAdapter {
private FragmentFavourites mFragFavourites;
private FragmentConverter mFragConverter;
public YourPagerAdapter() {
// ... your code above
this.mFragFavourites = new FragmentFavourites();
this.mFragConverter = new FragmentConverter();
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return mFragFavourites;
case 1:
return mFragConverter;
default:
return null;
}
}
}
As above carlo.marinangeli has suggested when you call fragmentPagerAdapter.getItem(1) you are getting a new instance of the fragment so you are referring to a different object
So to get same object from you adapter you need to store your object. you can try following method in your adapter -
public Fragment getFragmentAtPosition(int position) {
return registeredFragments.get(position);
}
where registeredFragments is -
private SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
and fill this sparseArray in getItem method like below -
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
fragment = FragmentPost.newInstance(position);
registeredFragments.put(position, fragment);
return fragment;
}
return null;
}
By using fragmentPagerAdapter.getItem(pos) method I was referring to a new object every time the respond() method was called. I fixed it by using findFragmentByTag() method instead:
#Override
public void respond(String[] names, String[] codes, String[] symbols,
int[] images) {
FragmentManager manager = getSupportFragmentManager();
FragmentConverter frag = (FragmentConverter) manager.findFragmentByTag("android:switcher:" + pager.getId() + ":" + 1);
frag.changeData(names, codes, symbols, images);
}
you can get that error because you are assuming that you have got the FragmentConverter and the views associated to it.
Without a logcat it becomes a little bit difficult to help you but basically what I would like to do in a situation like this is to pass everything through the activity without letting know the existence of the other fragment to the fragments.
F1 modifies a state object into the activity
F2 has to register as a
listener to the activity (be aware that the fragment can be attached
and detached in the view pager)
The Activity as soon it receives an updated, looks for all the registered listeners and if there is someone it delivers the updated

Is there a way to call a function in a parent class in java?

I'm making a base class for my androids screen, it is has a list control. Is there a way for when the base class's onListItemClick gets called, saying a list item was selected. It could call a function in the parent class??
Code:
public class cHome extends cBase {
String[] MyItems={
"Gate Directions",
"Food & Beverges",
"Shjops",
"Banking",
"Official Agencies",
"Amenities & Services",
"Restrooms"
};
public void onCreate(Bundle icicle) {
super.onCreate(icicle, MyItems);
// Display=MyItems;
}
Code:
public class cBase extends ListActivity {
String[] items={"CASUAL","DRESSES","CAREER","OUTWEAR","FOOTWEAR",
"JEWELRY","ACCESSORIES"};
String[] Display;
public void onCreate(Bundle icicle, String[] items2) {
Display=items2;
super.onCreate(icicle);
setContentView(R.layout.baselayout);
setListAdapter(new IconicAdapter(this));
// selection=(TextView)findViewById(R.id.selection);
// set values in header
// set header
TextView mFlight = (TextView)findViewById(R.id.idFlyerFlightNumber);
mFlight.setText( cGlobals.mFlightNumber);
TextView mDes = (TextView)findViewById(R.id.idFlyerDestanation);
mDes.setText( cGlobals.mDestanation);
}
class IconicAdapter extends ArrayAdapter {
Activity context;
IconicAdapter(Activity context) {
super(context, R.layout.row, Display);
this.context=context;
}
public View getView(int position, View convertView,
ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View row=inflater.inflate(R.layout.row, null);
TextView label=(TextView)row.findViewById(R.id.label);
label.setText(Display[position]);
ImageView icon=(ImageView)row.findViewById(R.id.icon);
// String[] items={"CASUAL","DR ESSES","CAREER","OUTWEAR","FOOTWEAR",
// "JEWELRY","ACCESSORIES"};
switch(position)
{
case 0:
// icon.setImageResource(R.drawable.formobile_items);
break;
case 1:
// icon.setImageResource(R.drawable.fashion_dress);
break;
case 2:
// icon.setImageResource(R.drawable.fashion_career);
break;
case 3:
// icon.setImageResource(R.drawable.fashion_outwear);
break;
case 4:
// icon.setImageResource(R.drawable.fashion_footwear);
break;
case 5:
// icon.setImageResource(R.drawable.fashion_jewelry);
break;
case 6:
// icon.setImageResource(R.drawable.fashion_accessories);
break;
}
return(row);
}
}
}
If I understand your question, what you want is to have a way for the base class to invoke a method on a class that extends it.
One way to accomplish this is to establish a "contract" that dictate what methods an extending class must implement. You do that with either an abstract class or an interface. The base class then knows what methods WILL be available to it when a class extends it, and can make the call.
public abstract class BaseThing {
public void foo() {
bar();
}
public abstract bar();
}
then:
public ParentThing extends BaseThing {
public void bar() {
System.out.println( "Hey, look at that. It worked!" );
}
}
You can override onListItemClick in your child class and just call super.onListItemClick on it. Or don't override it and onListItemClick method of base class will be called automatically when item in the list selected.

Categories