我在我的应用中使用了导航抽屉。有两个片段。一个用于配置文件,另一个用于反馈。在配置文件片段中,我需要每5秒调用一次函数。所以,我使用了一个处理程序。这里,onStart每5秒调用一次该函数。我认为,这是更改片段时应用崩溃的主要原因。如果我评论onStart和onPause,一切都会好起来的。我该如何处理这个问题?
public class ProfileFragment extends Fragment {
private ListView listView;
TextView textView;
Handler h = new Handler();
int delay = 5000; // 5 seconds
Runnable runnable;
public ProfileFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_profile, container, false);
textView = (TextView) view.findViewById(R.id.textViewUsername);
listView = (ListView) view.findViewById(R.id.listView);
//sendRequest();
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("Profile");
}
@Override
public void onStart() {
//start handler as activity become visible
h.postDelayed(new Runnable() {
public void run() {
//do something
sendRequest();
runnable=this;
h.postDelayed(runnable, delay);
}
}, delay);
super.onStart();
}
@Override
public void onPause() {
h.removeCallbacks(runnable); //stop handler when activity not visible
super.onPause();
}
private void sendRequest(){
StringRequest stringRequest = new StringRequest(Config.LOCATION_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("location", response.toString());
showJSON(response);
//Toast.makeText(getContext().getApplicationContext(), "Data loaded successfully!", Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext().getApplicationContext(),error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this.getActivity().getApplicationContext());
requestQueue.add(stringRequest);
}
private void showJSON(String json){
ParseJSON pj = new ParseJSON(json);
pj.parseJSON();
CustomList cl = new CustomList(this.getActivity(), ParseJSON.ids,ParseJSON.busNames,ParseJSON.busLocations,ParseJSON.times);
listView.setAdapter(cl);
}
}
答案 0 :(得分:0)
我建议你使用TimerTask类而不是处理程序来完成一段时间后要重复的任务:
<ListView ItemsSource="{Binding obsCommonList}" HasUnevenRows="True" BackgroundColor="Black" SeparatorVisibility="None" SelectedItem="{Binding SelectedProp,Mode=TwoWay}">
<ListView.Behaviors>
<b:EventToCommandBehavior EventName="ItemTapped" Command="{Binding ItemTappedCommand}" EventArgsParameterPath="Item"/>
</ListView.Behaviors>
希望这有帮助。