Android - NullPointerEx。由Android库类中的getPackageName()引起的

时间:2017-01-27 20:09:43

标签: java android gradle nullpointerexception android-library

我正在开展一个项目,我必须从普通'app'模块中的MainActivity在Android库中启动一个Activity。

MainActivity如下所示:

public class MainActivity extends ActionBarActivity implements BackendResponse {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

// Here I start an AsyncTask
public void tellJoke(View view) {
    BackendConnector backendConnector = new BackendConnector();
    backendConnector.execute();
}

// And here is the Callback 
@Override
public void response(String joke) {
    /*
        Down here is the problematic line (PresenterActivity is imported)
    */
    Intent jokeIntent = new Intent(this, PresenterActivity.class); // <--- line 18
    if (joke == null) joke = getString(R.string.emergency_joke); 

    jokeIntent.putExtra(getString(R.string.intent_key), joke);

    startActivity(jokeIntent);
}

在'app'模块的 build.gradle 文件中设置了依赖关系

android {
    // compileSdkVersion etc
}
dependency {
    compile project(':jokepresenter') // <--- 
}

在整个项目的 settings.gradle 文件中包含了库

include ':app', ':jokepresenter'

Logcat 如下所示:

FATAL EXCEPTION: main 
    Process: com.udacity.gradle.builditbigger, PID: 2723
    java.lang.NullPointerException: 
    Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
    // ...
    at com.udacity.gradle.builditbigger.MainActivity.response(MainActivity.java:18)
    at com.udacity.gradle.builditbigger.BackendConnector.onPostExecute(BackendConnector.java:53)
    at com.udacity.gradle.builditbigger.BackendConnector.onPostExecute(BackendConnector.java:17)
    // ...

1 个答案:

答案 0 :(得分:0)

好的,我明白了。

问题是回调方法或在AsyncTask中更具体。

@Override
protected void onPostExecute(String joke) {
    response = new MainActivity(); // <--- ¯\_(ツ)_/¯
    response.response(joke);
}

因为我创建了一个新的MainActivity,所以代表了 no Context

Intent jokeIntent = new Intent(this, PresenterActivity.class);

ContextWrapper 中的 NullPointerException 在尝试调用

时会导致 NullPointerException
return mBase.getPackageName(); 

mBase 被设置为活动上下文,当然 null