我正在开发一个Android应用,其中一个片段具有一个列表视图,该列表视图由PHP服务器的JSON响应填充。列表视图将根据需要显示,并且每当查看片段时都会更新。但是,这也是一个问题,因为只有在更改视图时列表才会更新,并且我希望listView每隔几毫秒清除并更新一次。
我的片段代码是:
public class eventFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
ListView eventView;
ArrayList<Events> eventList;
EventListAdapter adapter;
String streamName;
String applicationType = "live";
private static String value;
String url = "http://192.168.43.149/testing/eventStream.php";
private OnFragmentInteractionListener mListener;
public eventFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment eventFragment.
*/
// TODO: Rename and change types and number of parameters
public static eventFragment newInstance(String param1, String param2) {
eventFragment fragment = new eventFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_event, container, false);
eventView = (ListView) view.findViewById(R.id.listView);
eventList = new ArrayList<Events>();
JSONObject streamInfo = new JSONObject();
try {
streamInfo.put("applicationType", applicationType);
postJSONObject(url,streamInfo);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
public void postJSONObject(final String myurl, final JSONObject parameters) {
class postJSONObject extends AsyncTask<Void, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
//dialog[0] = new ProgressDialog(getActivity());
//dialog[0].setMessage("Loading, please wait");
//dialog[0].setTitle("Connecting server");
//dialog[0].show();
//dialog[0].setCancelable(false);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
//Toast.makeText(getContext().getApplicationContext(), s, Toast.LENGTH_LONG).show();
loadIntoEventView(s);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected String doInBackground(Void... voids) {
HttpURLConnection conn = null;
try {
StringBuffer response = null;
URL url = new URL(myurl);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(parameters.toString());
writer.close();
out.close();
int responseCode = conn.getResponseCode();
System.out.println("responseCode" + responseCode);
switch (responseCode) {
case 200:
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (conn != null) {
try {
conn.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return null;
}
}
postJSONObject postJSONObject = new postJSONObject();
postJSONObject.execute();
}
private void loadIntoEventView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
eventList.clear();
final String[] events = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
events[i] = obj.getString("title");
Events video = new Events();
video.setTitle(events[i]);
//vidoe.setDescription(obj.getString("channelDescriptipn"));
//channel.setDateCreated(obj.get("createdOn"));
//vidoe.setImage(obj.getString("logoLocation"));
eventList.add(video);
}
//ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1);
EventListAdapter adapter = new EventListAdapter(getActivity(), R.layout.eventparsedata, eventList);
eventView.setAdapter(adapter);
eventView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
streamName = Arrays.asList(events).get(position);
Intent intent = new Intent(getActivity(), StreamPlayerActivity.class);
intent.putExtra("videoname", streamName);
startActivity(intent);
System.out.println("arr: " + Arrays.asList(events).get(position));
}
});
}
}
答案 0 :(得分:1)
如果您想每x秒执行任何操作,则可以使用此代码(在本示例中,x为1000毫秒= 1秒)
在您的片段类中定义此:
private Handler handler = new Handler();
Runnable updatePage = new Runnable() {
@Override
public void run() {
// do what you want in here (calling your web service request)
handler.postDelayed(updatePage,1000);
}
};
并像这样使用它(将其放入onCreateView方法中):
handler.postDelayed(updatePage,1000);