每 2 秒刷新一次从 JSON 响应中填充的 listView
Posted
技术标签:
【中文标题】每 2 秒刷新一次从 JSON 响应中填充的 listView【英文标题】:Refresh listView populated from JSON response every 2 seconds 【发布时间】:2019-05-31 18:16:44 【问题描述】:我正在开发一个 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));
);
【问题讨论】:
【参考方案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);
【讨论】:
以上是关于每 2 秒刷新一次从 JSON 响应中填充的 listView的主要内容,如果未能解决你的问题,请参考以下文章