gpt4 book ai didi

java - 每 2 秒刷新一次从 JSON 响应填充的 listView

转载 作者:行者123 更新时间:2023-12-02 10:24:44 25 4
gpt4 key购买 nike

我正在开发一个 Android 应用程序,其中一个 fragment 有一个 ListView ,该 ListView 由来自 PHP 服务器的 JSON 响应填充。 ListView 根据需要显示,并且当前在查看 fragment 时更新。然而,这也是一个问题,因为列表仅在 View 更改时更新,并且我希望 listView 每隔几毫秒清除并更新一次。

我的 fragment 代码是:

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));


}


});


}


}

最佳答案

如果您想每 x 秒执行任何操作,您可以使用此代码(在本例中,x 为 1000 毫秒 = 1 秒)

在 fragment 类中定义它:

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);

关于java - 每 2 秒刷新一次从 JSON 响应填充的 listView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54051411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com