【问题标题】:Attempt to invoke virtual method on a null object reference in book listing app project?尝试在图书列表应用程序项目中调用空对象引用的虚拟方法?
【发布时间】:2017-09-18 11:56:09
【问题描述】:

我正在将我的项目作为我的 udacity 网络课程的一部分。我在(com.example.android.flavor.MainActivity.onCreate(MainActivity.java:54)). 我不知道如何解决这个问题。

MainActivity.java

public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<BookList>> {
public static final String LOG_TAG = MainActivity.class.getName();

/**
 * Constant value for the Book loader ID. We can choose any integer.
 * This really only comes into play if you're using multiple loaders.
 */
private Adapter mAdapter;
private static final int BOOK_LOADER_ID = 1;

private String GOOGLE_BOOK_URL;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //Fetching the bundle from the searchbar activity
    Bundle searchBundle = getIntent().getExtras();
    String searchQuery = searchBundle.getString("searchQuery");
    searchQuery = searchQuery.replaceAll("","+");
    Log.v("replace",searchQuery);

    //Make a new String builder to produce URL
    StringBuilder searchUrlBuilder = new StringBuilder();
    searchUrlBuilder.append("https://www.googleapis.com/books/v1/volumes?q=" + searchQuery +
    "&maxResults= 20");
    Log.v("URL", String.valueOf(searchUrlBuilder));
    //GOOG...URL assumes value of searchUrlBuilder
    GOOGLE_BOOK_URL = String.valueOf(searchUrlBuilder);


    // Find a reference to the {@link ListView} in the layout
    final ListView bookListView = (ListView) findViewById(R.id.listview_book);

    // Create a new adapter that takes an empty list of earthquakes as input
    mAdapter = new BookListAdapter(this, new ArrayList<BookList>());

    // Set the adapter on the {@link ListView}
    // so the list can be populated in the user interface
    bookListView.setAdapter((ListAdapter) mAdapter);

    //Get a reference to the LoaderManager, in order to interact with loaders.
    LoaderManager loaderManager = getLoaderManager();

    // Initialize the loader. Pass in the int ID constant defined above and pass in null for
    // the bundle. Pass in this activity for the LoaderCallbacks parameter (which is valid
    // because this activity implements the LoaderCallbacks interface).
    loaderManager.initLoader(BOOK_LOADER_ID, null,  this);
}

@Override
public Loader<List<BookList>> onCreateLoader(int i, Bundle bundle) {
    //Create a new Loader for the given URL this is where GOOGLE_BOOKS_REQUEST_URL was
    return new BookLoader(this, GOOGLE_BOOK_URL);
}

@Override
public void onLoadFinished(Loader<List<BookList>> loader, List<BookList> books) {
    //Clear the adapter of previous data
    books.clear();

    if (books != null && !books.isEmpty()) {
        books.addAll(books);
    }
}

@Override
public void onLoaderReset(Loader<List<BookList>> loader) {
    // Loader reset, so we can clear out our existing data.

}

}

Logcat:

enter code here

09-18 17:05:58.961 23093-23093/com.example.android.flavor E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            Process: com.example.android.flavor, PID: 23093
                                                                            java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.flavor/com.example.android.flavor.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
                                                                                at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5443)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
                                                                             Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
                                                                                at com.example.android.flavor.MainActivity.onCreate(MainActivity.java:54)
                                                                                at android.app.Activity.performCreate(Activity.java:6259)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490) 
                                                                                at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354) 
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                at android.os.Looper.loop(Looper.java:148) 
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5443) 

【问题讨论】:

  • 请把您的字符串包放在其中的邮政编码
  • 嘿@firegloves 你能说得更具体点吗,我不知道你在问什么?
  • 要在 Activity 中接收 Bundle,这意味着当您启动此 Activity 时,您必须已将该 Bundle 添加到 Intent。您必须手动指定要传递给起始 Activity 的内容。阅读您的帖子我可以想象您的 MainActivity 是您第一次启动的活动,对吗?
  • 说角色太长了。我可以用我的“回答你的问题按钮”回复你吗?
  • 编辑您的问题

标签: java android eclipse nullpointerexception adapter


【解决方案1】:

要在 Activity 中接收 Bundle,这意味着当您启动此 Activity 时,您必须已将该 Bundle 添加到 Intent。您必须手动指定要传递给起始 Activity 的内容。阅读您的帖子,我可以想象您的 MainActivity 是您第一次启动的活动,对吗?

传递Bundle的方法错误

您将错误的 Bundle 传递给 Activity。试试这个:

final Intent openResultActivity = new Intent(this,MainActivity.class);
        final EditText searchQuery = (EditText) findViewById(R.id.search_edit_text);

        Button searchButton=(Button)findViewById(R.id.search_button);
        searchButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                final String searchQueryString=searchQuery.getText().toString();
                Log.v("SearchinSBA",searchQueryString);

                Bundle bundle=new Bundle();
                bundle.putString("searchQuery",searchQueryString);
                openResultActivity.putExtras(bundle);
                startActivity(openResultActivity);
            }
        });

错误的 LaunchActivity

我的第一个答案是正确的:您从MainActivity 开始启动您的应用程序。所以SearchBarActivity 中的代码(你在putString 等处做的那个)永远不会被执行。必须首先执行该代码,以便它可以启动 MainActivity 并将您的包传递给它。

您的问题在于您的AndroidManifest.xml。您必须按如下方式更改您的启动器活动:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.flavor">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name">
        </activity>
        <activity android:name=".SearchBarActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

【讨论】:

  • 你能在帖子中查看我的答案吗?
  • 你能看看它吗,因为即使在你编辑之后它仍然不起作用?
【解决方案2】:

您没有收到捆绑包。请在访问其方法之前检查是否为 null

String searchQuery;
if(searchBundle!=null){
   searchQuery = searchBundle.getString("searchQuery");
}

或者如果你传递的包不正确,请这样做

Intent intent = new Intent(YourActivityName.this, MainActivity.class);
Bundle bundle = new Bundle();
bundle.putString("searchQuery", yourSearchQuery);
intent.putExtras(bundle);
startActivity(intent);

【讨论】:

  • 现在我在初始化 searchQuery 时遇到错误。还有其他建议吗?
猜你喜欢
  • 2023-03-13
  • 2019-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-24
  • 2021-08-02
相关资源
最近更新 更多