java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myexample/com.example.myexample.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
我的主要活动看起来像这样:
public class MainActivity extends AppCompatActivity implements RecyclerView.OnScrollChangeListener {
private List<School> listSchools;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
//Volley Request Queue
private RequestQueue requestQueue;
//The request counter to send ?page=1, ?page=2 requests
private int requestCount = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
if (recyclerView != null) {
recyclerView.setHasFixedSize(true);
}
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Initializing our superheroes list
listSchools = new ArrayList<>();
requestQueue = Volley.newRequestQueue(this);
//Calling method to get data to fetch data
getData();
//Adding an scroll change listener to recyclerview
recyclerView.setOnScrollChangeListener(this);
//initializing our adapter
adapter = new SchoolRecyclerAdapter(listSchools, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
if (fab != null) {
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
//Request to get json from server we are passing an integer here
//This integer will used to specify the page number for the request ?page = requestcount
//This method would return a JsonArrayRequest that will be added to the request queue
private JsonArrayRequest getDataFromServer(int requestCount) {
//Initializing ProgressBar
//JsonArrayRequest of volley
//Returning the request
return new JsonArrayRequest(Configu.DATA_URL + String.valueOf(requestCount),
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
//Calling method parseData to parse the json response
parseData(response);
//Hiding the progressbar
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//If an error occurs that means end of the list has reached
Toast.makeText(MainActivity.this, "No More Items Available", Toast.LENGTH_SHORT).show();
}
});
}
//This method will get data from the web api
private void getData() {
//Adding the method to the queue by calling the method getDataFromServer
requestQueue.add(getDataFromServer(requestCount));
//Incrementing the request counter
requestCount++;
}
//This method will parse json data
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
//Creating the school object
School school = new School();
JSONObject json;
try {
//Getting json
json = array.getJSONObject(i);
//Adding data to the superhero object
school.setImageUrl(json.getString(Configu.TAG_IMAGE_URL));
school.setName(json.getString(Configu.TAG_NAME));
school.setCity(json.getString(Configu.TAG_CITY));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding the school object to the list
listSchools.add(school);
}
//Notifying the adapter that data has been added or changed
adapter.notifyDataSetChanged();
}
//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
if (recyclerView.getAdapter().getItemCount() != 0) {
int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
return true;
}
return false;
}
//Overriden method to detect scrolling
@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
//Ifscrolled at last then
if (isLastItemDisplaying(recyclerView)) {
//Calling the method getdata again
getData();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}}}
我的清单如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myexample">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
非常感谢您的帮助。
答案 0 :(得分:0)
您没有在范围内初始化学校列表。请尝试这样:
public class MainActivity extends AppCompatActivity implements RecyclerView.OnScrollChangeListener {
private List<School> listSchools;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
//Volley Request Queue
private RequestQueue requestQueue;
//The request counter to send ?page=1, ?page=2 requests
private int requestCount = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
if (recyclerView != null) {
recyclerView.setHasFixedSize(true);
}
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Initializing our superheroes list
listSchools = new ArrayList<>();
requestQueue = Volley.newRequestQueue(this);
//Calling method to get data to fetch data
getData(listSchools);
//Adding an scroll change listener to recyclerview
recyclerView.setOnScrollChangeListener(this);
//initializing our adapter
adapter = new SchoolRecyclerAdapter(listSchools, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
if (fab != null) {
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
//Request to get json from server we are passing an integer here
//This integer will used to specify the page number for the request ?page = requestcount
//This method would return a JsonArrayRequest that will be added to the request queue
private JsonArrayRequest getDataFromServer(int requestCount, List<School> listSchools) {
//Initializing ProgressBar
//JsonArrayRequest of volley
//Returning the request
return new JsonArrayRequest(Configu.DATA_URL + String.valueOf(requestCount),
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
//Calling method parseData to parse the json response
parseData(response, listSchools);
//Hiding the progressbar
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//If an error occurs that means end of the list has reached
Toast.makeText(MainActivity.this, "No More Items Available", Toast.LENGTH_SHORT).show();
}
});
}
//This method will get data from the web api
private void getData(List<School> listSchools) {
//Adding the method to the queue by calling the method getDataFromServer
requestQueue.add(getDataFromServer(requestCount, listSchools));
//Incrementing the request counter
requestCount++;
}
//This method will parse json data
private void parseData(JSONArray array, List<School> listSchools) {
for (int i = 0; i < array.length(); i++) {
//Creating the school object
School school = new School();
JSONObject json;
try {
//Getting json
json = array.getJSONObject(i);
//Adding data to the superhero object
school.setImageUrl(json.getString(Configu.TAG_IMAGE_URL));
school.setName(json.getString(Configu.TAG_NAME));
school.setCity(json.getString(Configu.TAG_CITY));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding the school object to the list
listSchools.add(school);
}
//Notifying the adapter that data has been added or changed
adapter.notifyDataSetChanged();
}
//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
if (recyclerView.getAdapter().getItemCount() != 0) {
int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
return true;
}
return false;
}
//Overriden method to detect scrolling
@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
//Ifscrolled at last then
if (isLastItemDisplaying(recyclerView)) {
//Calling the method getdata again
getData();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}}}