2
votes

First to explain how projects are setup:

  • Android Library project with two classes:
    • UserActivity - uses static field in HolderClass
    • HolderClass - this one has static field Data
  • Android Application that references Library project, has only one class:
    • StarterActivity - when app is started, in onCreate it sets static field Data to some value, and it starts UserActivity

Now, the problem is: sometimes I get java.lang.NullPointerException for that static field Data - as if I never initialized it (or value got deleted in meantime). It never happened on my test device, but I keep getting error reports from client devices. I can only guess how that happens - maybe user navigates away from app, then comes back and system recreates whole application context, but in that context HolderClass has empty static field Data?

My question:

Is initialization of that static field from Activity's onCreate wrong approach? Should I put data in ApplicationContext? Or do something else?

I am open for all suggestions.

P.S. If you have problem visualizing from description, here is how everything I've said would look in code:

// IN ANDROID APP PROJECT
public class StarterActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 

        // just start activity in library
        Intent myIntent = new Intent(this, AutolaunchActivity.class);
        startActivityForResult(myIntent, 1);    
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // exit when activity from library exits
        finish();       
    }
}


// IN LIBRARY PROJECT

public class HolderClass {
    public static String Data;
}

public class UserActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 

        // init layout  
    }

    public void someButtonClicked() {
        HolderClass.Data.trim();
    }
}
2
is it possible to show some code?NG.
Post the error report to see what exactly you are getting.Cameron
I've extracted important lines and posted code example.nikib3ro

2 Answers

1
votes

The usual ways of sharing data between activities is documented here. The intermittent nature of the error suggests a timing problem to me. Are you using threads in some of your initialization? Also, do you know if the NPE happening in StarterActivity or UserActivity?

0
votes

OK, this was basically the problem of global variables - in the end I've solved it by reading this answer: How to declare global variables in Android?