开发者

Nullpointer on activities for a called method (for example activity: getListView or getAssets etc.)

The problem I am facing is stated below in code. I am trying to call a 'method' from another class, which is going good until it reaches a activity (like getListView() or getAssets())

Calling class:

public class Main extends Activity {
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);
    Utils ut = new Utils();
    ut.initiateMainMenu();
  }
}

Called class (method: initiateMainMenu):

public class Utils extends ListActivity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
      initiateMainMenu();
  }

  public void initiateMainMenu() {
    listView = getListView();
    assetManager = getAssets();
    etc...
  }
}

In the example above a nullpointer occurs when the first class (Main) is started with an intent.

The nullpointer is given on the following lines depending on which line comes first:

listView = getListView();
assetManager = getAssets();

The same nullpointer does not occur when class Utils is directly intended.

I hope the above description is suffient for so开发者_JAVA技巧lving my problem.

Kind regards, Conrad


If you are holding a list view in your main activity, instead of doing this, which seems really weird to me, add the list view to R.layout.main and extend your class from ListActivity. You can get rid of Utils, and have all the listview related code in Main.

Or maybe some more information about what you pretend to implement might help...

Ger


Well the solution is simple, Your context for Utils class is never initialized, i.e. Utils class's onCreate method is never called or is out of focus or due to some other reason your ListView is never initialized.

You could do following :

  1. Inverse calls and hold handle for list, may be using static keyword.
  2. Or may be try changing code to getApplicationContext.getListView() / Utils.this.getListView of your initiateMainMenu();

I dont know to what extend this would work, but the basic cause behind this issue is uninitialized listView resulting in NULL.


The difficulty I was facing was not entirely described because my Java knowledge was not sufficient for identifying it as a problem.

What I was doing was using three Activities that inherit from each other. Namely Activity, MenuActivity (my own extended one) and ListActivity. The quick and dirty solution I am now using is a duplicate class. One class holds MenuActivity extending Activity and the other holds MenuActivity extending ListActivity.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜