尝试在图书列表应用程序项目中的空对象引用上调用虚拟方法?
Attempt to invoke virtual method on a null object reference in book listing app project?
我正在将我的项目作为 networking.I 的大胆课程的一部分,我在 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)
您没有收到包裹。请在访问其方法之前检查是否为 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);
要在 Activity 中接收 Bundle,这意味着当您启动此 Activity 时,您必须将该 Bundle 添加到 Intent 中。您必须手动指定要传递给起始 Activity 的内容。看了你的post我可以想象你的MainActivity是你第一个启动的activity,对吗?
传递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);
}
});
启动错误Activity
我的第一个答案是正确的:您正在从 MainActivity
开始启动您的应用程序。所以 SearchBarActivity
中的代码(你做的 putString
等等)永远不会执行。该代码必须首先执行,以便它可以启动 MainActivity
将您的包传递给它。
您的问题出在您的 AndroidManifest.xml
上。您必须按如下方式更改您的启动器 activity:
<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>
我正在将我的项目作为 networking.I 的大胆课程的一部分,我在 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)
您没有收到包裹。请在访问其方法之前检查是否为 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);
要在 Activity 中接收 Bundle,这意味着当您启动此 Activity 时,您必须将该 Bundle 添加到 Intent 中。您必须手动指定要传递给起始 Activity 的内容。看了你的post我可以想象你的MainActivity是你第一个启动的activity,对吗?
传递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);
}
});
启动错误Activity
我的第一个答案是正确的:您正在从 MainActivity
开始启动您的应用程序。所以 SearchBarActivity
中的代码(你做的 putString
等等)永远不会执行。该代码必须首先执行,以便它可以启动 MainActivity
将您的包传递给它。
您的问题出在您的 AndroidManifest.xml
上。您必须按如下方式更改您的启动器 activity:
<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>