这是我应用新的排序方法时遇到的错误。默认情况下,它可以进行排序和工作,并显示排序得很好,但是在选项菜单上单击主活动中的排序,尝试对数据进行重新排序,然后按顺序重新显示排序的数据
E / UncaughtException:java.lang.NullPointerException:尝试调用 虚方法 android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView $ Adapter)' 在空对象引用上 在com.djwubwubwhaleproductions.projects.fragments.HomeFragment.showList(HomeFragment.java:297) 在com.djwubwubwhaleproductions.projects.fragments.HomeFragment.sortByPrice(HomeFragment.java:192) 在com.djwubwubwhaleproductions.nextedevents.MainActivity.onOptionsItemSelected(MainActivity.java:218) 在android.app.Activity.onMenuItemSelected(Activity.java:3450) 在android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:436) 在android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:196) 在android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:109) 在android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:109) 在android.support.v7.app.ToolbarActionBar $ 2.onMenuItemClick(ToolbarActionBar.java:64) 在android.support.v7.widget.Toolbar $ 1.onMenuItemClick(Toolbar.java:204) 在android.support.v7.widget.ActionMenuView $ MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:781) 在android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:840) 在android.support.v7.view.menu.SubMenuBuilder.dispatchMenuItemSelected(SubMenuBuilder.java:90) 在android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158) 在android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991) 在android.support.v7.view.menu.MenuPopup.onItemClick(MenuPopup.java:128) 在android.widget.AdapterView.performItemClick(AdapterView.java:318) 在android.widget.AbsListView.performItemClick(AbsListView.java:1158) 在android.widget.AbsListView $ PerformClick.run(AbsListView.java:3127) 在android.widget.AbsListView $ 3.run(AbsListView.java:4042) 在android.os.Handler.handleCallback(Handler.java:790) 在android.os.Handler.dispatchMessage(Handler.java:99) 在android.os.Looper.loop(Looper.java:164) 在android.app.ActivityThread.main(ActivityThread.java:6494) 在java.lang.reflect.Method.invoke(本机方法) 在com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run(RuntimeInit.java:438) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
代码
public class HomeFragment extends Fragment {
private static final String TAG = "ViewDatabase";
private View viewInflate;
public static Event[] events = new Event [100];
private myAsyncTaskNoDialog task;
private SwipeRefreshLayout swipeRefresh;
private RecyclerView mRecyclerView;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
public static int count;
public static int eventRef;
public double mDistance;
private MainActivity main;
private int run;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
viewInflate = inflater.inflate(R.layout.fragment_list_swipe, null);
FirebaseFirestore firestore = FirebaseFirestore.getInstance();
FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
.setTimestampsInSnapshotsEnabled(true)
.build();
return viewInflate;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(task != null)
task.cancel(true);
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
mRecyclerView = viewInflate.findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
swipeRefresh = viewInflate.findViewById(R.id.swipe_refresh);
swipeRefresh.setClickable(true);
Handler h = new Handler();
h.postDelayed(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
if (events[0]== null) {
getData();
}else {
showRefresh(false);
showList();
}
}
}, 500);
}
public void showRefresh(boolean show) {
swipeRefresh.setRefreshing(show);
swipeRefresh.setEnabled(show);
}
@AddTrace(name = "Firestore data collection", enabled = true)
public void getData() {
showRefresh(true);
db.collection("Events").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
count = 0;
for (QueryDocumentSnapshot document : task.getResult()) {
if (uLocation!=null) {
CalcDistance(document.getGeoPoint("Address").getLatitude(), document.getGeoPoint("Address").getLongitude());
}
//set events
events[count] = new Event(
document.getId(),
document.getString("Category"),
document.getGeoPoint("Address").getLongitude(),
document.getGeoPoint("Address").getLatitude(),
getAddress(document.getGeoPoint("Address").getLatitude(), document.getGeoPoint("Address").getLongitude()),
document.getString("Description"),
document.getString("Name"),
document.getTimestamp("Time"),
Double.parseDouble(document.getString("Entrance Cost")),
mDistance);
count++;
FirebaseCrash.log("Data collection");
}
} else {
Log.e(TAG, "Error getting documents: ", task.getException());
}
showRefresh(false);
sortByTime();
}
});
}
@AddTrace(name = "Calculating Distances", enabled = true)
public void CalcDistance(double a, double b){
float [] results = new float [1];
Location.distanceBetween(uLocation.getLatitude(), uLocation.getLongitude(), b, a, results);
mDistance = results[0] / 1000;
String temp = String.format("%.1f", mDistance);
temp = temp.replace(",",".");
mDistance = Double.parseDouble(temp);
}
@AddTrace(name = "Sorting by Distance", enabled = true /* optional */)
public void sortByDistance() {
int n = count;
int k;
for (int m = n; m >= 0; m--) {
for (int i = 0; i < n - 1; i++) {
k = i + 1;
if (events[i].getDistance() > events[k].getDistance()) {
Event temp;
temp = events[i];
events[i] = events[k];
events[k] = temp;
}
}
}
showList();
}
@AddTrace(name = "Sorting by Price", enabled = true /* optional */)
public void sortByPrice() {
int n = count;
int k;
for (int m = n; m >= 0; m--) {
for (int i = 0; i < n - 1; i++) {
k = i + 1;
if (events[i].getPrice() > events[k].getPrice()) {
Event temp;
temp = events[i];
events[i] = events[k];
events[k] = temp;
}
}
}
showList();
}
@AddTrace(name = "Sorting by Time", enabled = true /* optional */)
public void sortByTime() {
int n = count;
int k;
for (int m = n; m >= 0; m--) {
for (int i = 0; i < n - 1; i++) {
k = i + 1;
if (events[i].getDateAndTime().getSeconds() > events[k].getDateAndTime().getSeconds()) {
Event temp;
temp = events[i];
events[i] = events[k];
events[k] = temp;
}
}
}
showList();
}
@AddTrace(name = "Sorting by Name", enabled = true /* optional */)
public void sortByName() {
int n = count;
int k;
for (int m = n; m >= 0; m--) {
for (int i = 0; i < n - 1; i++) {
k = i + 1;
if (events[i].getDistance() > events[k].getDistance()) {
Event temp;
temp = events[i];
events[i] = events[k];
events[k] = temp;
}
}
}
showList();
}
public String getAddress (double latitude,double longitude){
Geocoder geocoder;
List<Address> addresses = null;
geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "Error getting Street Address: ");
}
String address = addresses.get(0).getAddressLine(0);
if (addresses == null){
address="";
}
return address;
}
@AddTrace(name = "Displaying the data in the main activity", enabled = true)
private void showList() {
RecyclerAdapter adapter = new RecyclerAdapter(count, R.layout.event_entry);
adapter.setOnRecyclerAdapterListener(new RecyclerAdapter.OnRecyclerAdapterListener() {
@Override
public void onRecyclerAdapterCreated(RecyclerAdapter adapter, RecyclerAdapter.ViewHolder v, final int position) {
TextView tvTitle = v.view.findViewById(R.id.tvTitle);
tvTitle.setText((events[position].getEvent_name()));
long timestampString = events[position].getDateAndTime().getSeconds();
String value = new java.text.SimpleDateFormat("EEE dd MMM yyyy - HH:mm").
format(new java.util.Date(timestampString * 1000));
TextView tvSubtitle = v.view.findViewById(R.id.tvSubtitle);
tvSubtitle.setText(value);
String price = "R";
price = price + events[position].getPrice();
if (events[position].getPrice()>0){
TextView tvPrice = v.view.findViewById(R.id.price);
tvPrice.setText(price);
}else {
TextView tvPrice = v.view.findViewById(R.id.price);
tvPrice.setText("Free");
}
TextView tvCategory = v.view.findViewById(R.id.tvCategory);
String category = events[position].getCategory();
category = category.replace(category.substring(category.length()-1), "");
tvCategory.setText(category);
TextView tvDistance = v.view.findViewById(R.id.distance);
if (uLocation != null) {
String mDistance = String.valueOf(events[position].getDistance()) + "Km";
tvDistance.setText(mDistance);
}else if (uLocation == null) {
tvDistance.setVisibility(View.INVISIBLE);
}
v.view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getActivity(), DetailActivity.class);
i.putExtra("Event", events[position].getEvent_name());
eventRef = position;
getActivity().startActivity(i);
}
});
}
});
mRecyclerView.setAdapter(adapter);
}
}