0

I want to use the same onOptionsItemSelected logic for multiple activities (I want to reduce code redundancy), so I thought I could create a BaseActivity and then extend. However, one of my activities extend already ListActivity, so this would be not a proper solution. How can I achieve this?

Any help would be greatly appreciated.

user3475602
  • 1,217
  • 2
  • 21
  • 43
  • 1
    Don't use a ListActivity. It's just a regular Activity with some niceties tacked on that you could instead implement yourself. – Mike M. Oct 13 '14 at 06:43
  • Thank you for your help! Do you have an example on how I could implement this by myself? – user3475602 Oct 13 '14 at 06:46
  • 1
    [This post](http://stackoverflow.com/questions/2242136/how-can-i-implement-a-listview-without-listactivity-use-only-activity) shows the minimal changes you'd have to make. You pretty much just need to keep a ListView variable (like you would for a Button or a TextView), and call your methods (`setAdapter()`, `setOnItemClickListener()`, etc.) on that, rather than using the ListActivity's methods. – Mike M. Oct 13 '14 at 06:53
  • Thank you! I tried it as suggested, but I got a `java.lang.NullPointerException`, because I called `lv.setAdapter(adapter);` instead of `setListAdapter(adapter);`. Do I need to use a different method? `lv.setListAdapter(adapter);` is not available. – user3475602 Oct 13 '14 at 07:38
  • 1
    That's the correct method. Make sure you're calling `findViewById()` to get `lv`, and that it isn't null. – Mike M. Oct 13 '14 at 07:46

1 Answers1

1

you can have a

public class BaseActivity extends Activity 

and then

public class SomeActivity extends BaseActivity

you can have methods in your base activity for eg. you can have a show toast method

protected void showToast(String message){
    Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}

which can be called in every activity that extends base activity .

so if youve already extended a listActivity you may need to rethink . Probably if you show me exactly what youre looking for i might be able to see what exactly are you looking for.

And you dont need to extend it to list activity for a list you can see various tutorials.

go to this List View Tutorial and you can find what you need

BackStabber
  • 227
  • 1
  • 13
  • Thank you for your help! The problem is that I can't have `public class BaseActivity extends ListActivity`, because there are classes that do not need `ListActivity` logic. – user3475602 Oct 13 '14 at 06:51
  • only extend `baseactivity` with `activity` you can implement `listactivity` with a custom implementation that also extends activity (see link above) Please tick & upvote if you find the answer useful . – BackStabber Oct 13 '14 at 06:55