Java 每2秒刷新从JSON响应填充的listView
我正在开发一个android应用程序,其中一个片段有一个listview,该listview由来自PHP服务器的JSON响应填充。列表视图会根据需要显示,并且当前会在查看片段时更新。但是,这也是一个问题,因为列表仅在视图更改时更新,我希望listView每隔几毫秒清除并更新一次 我的片段代码是:Java 每2秒刷新从JSON响应填充的listView,java,android,json,listview,fragment,Java,Android,Json,Listview,Fragment,我正在开发一个android应用程序,其中一个片段有一个listview,该listview由来自PHP服务器的JSON响应填充。列表视图会根据需要显示,并且当前会在查看片段时更新。但是,这也是一个问题,因为列表仅在视图更改时更新,我希望listView每隔几毫秒清除并更新一次 我的片段代码是: public class eventFragment extends Fragment { // TODO: Rename parameter arguments, choose names that
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));
}
});
}
}
public类eventFragment扩展了片段{
//TODO:重命名参数参数,选择匹配的名称
//片段初始化参数,例如ARG_ITEM_NUMBER
私有静态最终字符串ARG_PARAM1=“PARAM1”;
私有静态最终字符串ARG_PARAM2=“PARAM2”;
//TODO:重命名和更改参数类型
私有字符串mParam1;
私有字符串mParam2;
ListView事件视图;
ArrayList事件列表;
事件列表适配器;
字符串流名称;
字符串applicationType=“live”;
私有静态字符串值;
字符串url=”http://192.168.43.149/testing/eventStream.php";
私有OnFragmentInteractionListener mListener;
公共事件片段(){
//必需的空公共构造函数
}
/**
*使用此工厂方法创建的新实例
*使用提供的参数创建此片段。
*
*@param param1参数1。
*@param param2参数2。
*@return fragment eventFragment的新实例。
*/
//TODO:重命名和更改参数的类型和数量
公共静态eventFragment newInstance(字符串param1,字符串param2){
eventFragment=新的eventFragment();
Bundle args=新Bundle();
args.putString(ARG_PARAM1,PARAM1);
args.putString(ARG_PARAM2,PARAM2);
fragment.setArguments(args);
返回片段;
}
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
如果(getArguments()!=null){
mParam1=getArguments().getString(ARG_PARAM1);
mParam2=getArguments().getString(ARG_PARAM2);
}
}
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
//为该碎片膨胀布局
视图=充气机。充气(R.layout.fragment\u事件,容器,错误);
eventView=(ListView)view.findViewById(R.id.ListView);
eventList=新的ArrayList();
JSONObject streamInfo=新的JSONObject();
试一试{
streamInfo.put(“applicationType”,applicationType);
postJSONObject(url、streamInfo);
}捕获(JSONException e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
返回视图;
}
//TODO:重命名方法、更新参数并将方法挂接到UI事件中
public void onButtonPressed(Uri){
if(mListener!=null){
onFragmentInteraction(uri);
}
}
@凌驾
公共void-onAttach(上下文){
super.onAttach(上下文);
if(OnFragmentInteractionListener的上下文实例){
mListener=(OnFragmentInteractionListener)上下文;
}否则{
抛出新的RuntimeException(context.toString()
+“必须实现OnFragmentInteractionListener”);
}
}
@凌驾
公共无效连接(){
super.onDetach();
mListener=null;
}
/**
*此接口必须由包含以下内容的活动实现
*片段,以允许通信此片段中的交互
*该活动以及其中可能包含的其他片段
*活动。
*
*有关更多信息,请参阅Android培训课程。
*/
FragmentInteractionListener上的公共接口{
//TODO:更新参数类型和名称
void onFragmentInteraction(Uri);
}
public void postJSONObject(最终字符串myurl,最终JSONObject参数){
类postJSONObject扩展了AsyncTask{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
//对话框[0]=新建ProgressDialog(getActivity());
//对话框[0]。设置消息(“正在加载,请稍候”);
//对话框[0]。设置标题(“连接服务器”);
//对话框[0]。显示();
//对话框[0]。可设置可取消(false);
}
@凌驾
受保护的void onPostExecute(字符串s){
super.onPostExecute(s);
试一试{
//Toast.makeText(getContext().getApplicationContext(),s,Toast.LENGTH_LONG.show();
载入事件视图;
}捕获(例外e){
e、 printStackTrace();
}
}
@凌驾
受保护的字符串背景(无效…无效){
HttpURLConnection conn=null;
试一试{
StringBuffer响应=null;
URL=新URL(myurl);
conn=(HttpURLConnection)url.openConnection();
连接设置读取超时(10000);
连接设置连接超时(15000);
conn.setRequestProperty(“内容类型”、“应用程序/json”);
连接设置输出(真);
conn.setRequestMethod(“POST”);
OutputStream out=新的BufferedOutputStream(conn.getOutputStream());
BufferedWriter writer=新的BufferedWriter(新的OutputStreamWriter(输出,“UTF-8”));
writer.write(parameters.toString());
writer.close();
out.close();
int responseCode=conn.getResponseCode();
System.out.println(“响应代码”+响应代码);
开关(响应代码){
案例200:
BufferedReader in=新的BufferedReader(新的InputStreamReader(conn.getInputStream());
字符串输入线;
响应=新的StringBuffer();
而((inputLine=in.readLine())!=null){
追加(inputLine);
}
in.close();
返回response.toString();
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);
}
};
handler.postDelayed(updatePage,1000);