问题描述
我有这个片段,我在那里编辑文本,一个按钮和一个回收者视图。当我第一次单击按钮时,它具有预期的行为,但是,如果我更改了编辑文本的内容,然后再次单击该按钮,则不会更新我的回收站视图。我究竟做错了什么?由于我要重复此过程 点击一次即可进行Api通话
片段
public class SearchFragment extends Fragment implements View.OnClickListener {
private RestaurantAdapter mAdapter;
private RecyclerView mRecyclerView;
protected static List<Restaurant_> restaurantsList;
private Context context;
private static OnRestaurantClickedListener listener;
private FirebaseAuth mAuth;
private EditText keyword;
private FusedLocationProviderClient mFusedLocationClient;
public SearchFragment() {
}
public static OnRestaurantClickedListener getListener() {
return listener;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getContext();
mAuth = FirebaseAuth.getInstance();
restaurantsList = new ArrayList<>();
mAdapter = new RestaurantAdapter(context,restaurantsList,getActivity());
}
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
View mContentView = inflater.inflate(R.layout.fragment_search,container,false);
mRecyclerView = mContentView.findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new linearlayoutmanager(mContentView.getContext()));
mRecyclerView.setAdapter(mAdapter);
keyword = mContentView.findViewById(R.id.keyword);
keyword.setonEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView,int actionId,KeyEvent keyEvent) {
if ((keyEvent != null && keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER) || (actionId == EditorInfo.IME_ACTION_SEARCH))
getRestaurants();
return false;
}
});
ImageButton searchButton = mContentView.findViewById(R.id.search);
searchButton.setonClickListener(this);
return mContentView;
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
listener = (OnRestaurantClickedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnButtonClicked");
}
}
@SuppressLint("MissingPermission")
private void getRestaurants() {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());
mFusedLocationClient.getLastLocation().addOnSuccessListener(getActivity(),new OnSuccessListener<Location>() {
@Override
public void onSuccess(final Location location) {
if (location != null) {
SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(context);
String sort = mSettings.getString("sort","rating");
String order = mSettings.getString("order","desc");
double radius = Double.parseDouble(mSettings.getString("radius","10"));
radius = radius * 1000;
RetrofitZomato.getApi().searchByName(keyword.getText().toString(),location.getLatitude(),location.getLongitude(),20,radius,sort,order,getActivity().getResources().getString(R.string.user_key))
.enqueue(new Callback<SearchResponse>() {
@Override
public void onResponse(Call<SearchResponse> call,Response<SearchResponse> response) {
if (restaurantsList.size() != 0) {
restaurantsList.clear();
mAdapter.notifyDataSetChanged();
}
List<Restaurant> restaurants = response.body().getRestaurants();
for (int i = 0; i < restaurants.size(); i++) {
double distance = calculatedistance(Double.parseDouble(restaurants.get(i).getRestaurant().getLocation().getLatitude()),Double.parseDouble(restaurants.get(i).getRestaurant().getLocation().getLongitude()),location.getLongitude());
distance = (double) Math.round(distance * 100d) / 100d;
restaurants.get(i).getRestaurant().setdistance(distance);
restaurantsList.add(restaurants.get(i).getRestaurant());
mAdapter.notifyItemInserted(i);
}
}
@Override
public void onFailure(Call<SearchResponse> call,Throwable t) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Couldn't find any nearby restaurants");
AlertDialog mDialog = builder.create();
mDialog.show();
}
});
}
}
}).addOnFailureListener(getActivity(),new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getActivity(),"It wasn't possible to determine your location",Toast.LENGTH_LONG).show();
}
});
}
private double calculatedistance(double latRestaurant,double lonRestaurant,double myLat,double myLon) {
if ((myLat == latRestaurant) && (myLon == lonRestaurant)) {
return 0;
} else {
double theta = myLon - lonRestaurant;
double dist = Math.sin(Math.toradians(myLat)) * Math.sin(Math.toradians(latRestaurant))
+ Math.cos(Math.toradians(myLat)) * Math.cos(Math.toradians(latRestaurant)) * Math.cos(Math.toradians(theta));
dist = Math.acos(dist);
dist = Math.todegrees(dist);
dist = dist * 60 * 1.1515;
dist = dist * 1.609344;
return dist;
}
}
@Override
public void onClick(View view) {
int id = view.getId();
if (id == R.id.search) {
getRestaurants();
}
}
// @Override
// public void onActivityCreated(@Nullable Bundle savedInstanceState) {
// super.onActivityCreated(savedInstanceState);
// searchviewmodel = viewmodelProviders.of(this).get(Searchviewmodel.class);
// // Todo: Use the viewmodel
// }
}
解决方法
请注意,每进行一次getRestaurants
呼叫,您就在呼叫getFusedLocationProviderClient
和addOnSuccessListener
,并保持旧的注册和离开……也许这些多个侦听器实例是这种行为的原因吗? / p>
将此行移动到onAttach
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());
一次致电。然后让您的SearchFragment
实现OnSuccessListener
并设置为FusedLocationProviderClient
。您的点击应会触发对新位置的请求,并且您当前使用getLastLocation
编写的代码也可以在onAttach
编辑:真实答案-评论副本
尝试在方法结束时(在for循环之后)删除mAdapter.notifyItemInserted(i);
行并将mAdapter.notifyDataSetChanged();
从if
条件中移出。我的代码中没有可疑的东西,看起来还不错...