我有一个Android ListView,但是每次我要刷新列表时,我都必须保留该应用程序。我有两个问题,请:
1(如何自动刷新它?
2(在将项目添加到数据库中时如何接收通知?
因此,它只是测试是否添加了一个项目,我会收到通知,当我单击它时,我将能够看到项目列表。
这是我的代码:
public class MainActivity extends Activity {
ListView SubjectFullFormListView;
ProgressBar progressBar;
String HttpURL = "http://254.221.325.11/test/Subject.php";
ListAdapter adapter ;
List<Subject> SubjectFullFormList;
EditText editText ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
SubjectFullFormListView = (ListView) findViewById(R.id.SubjectFullFormListView);
editText = (EditText)findViewById(R.id.edittext1);
progressBar = (ProgressBar) findViewById(R.id.ProgressBar1);
new ParseJSonDataClass(this).execute();
}
private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> {
public Context context;
String FinalJSonResult;
public ParseJSonDataClass(Context context) {
this.context = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0) {
HttpServiceClass httpServiceClass = new HttpServiceClass(HttpURL);
try {
httpServiceClass.ExecutePostRequest();
if (httpServiceClass.getResponseCode() == 200) {
FinalJSonResult = httpServiceClass.getResponse();
if (FinalJSonResult != null) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonResult);
JSONObject jsonObject;
Subject subject;
SubjectFullFormList = new ArrayList<Subject>();
for (int i = 0; i < jsonArray.length(); i++) {
subject = new Subject();
jsonObject = jsonArray.getJSONObject(i);
subject.Subject_Name = jsonObject.getString("SubjectName");
subject.Subject_Full_Form = jsonObject.getString("SubjectFullForm");
SubjectFullFormList.add(subject);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
Toast.makeText(context, httpServiceClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
SubjectFullFormListView.setVisibility(View.VISIBLE);
adapter = new ListAdapter(SubjectFullFormList, context);
SubjectFullFormListView.setAdapter(adapter);
}
}
}
我找到了一个解决方案,但我不知道如何以及在哪里插入它:
final Handler handler = new Handler();
Runnable refresh = new Runnable() {
@Override
public void run() {
new JSONParse().execute();
handler.postDelayed(this, 60 * 1000);
}
};
handler.postDelayed(refresh, 60 * 1000);
谢谢。
->编写一个可运行的线程,一段时间后定期调用列表的API,并且在其响应上更改适配器中的列表,并调用notifydatasetchanged((。
。->通过使用FCM,您可以获取解决方案。通知。
(OR)
->您可以将实时DB(例如Firebase DB或Realm等(用于此方法。当项目添加到列表中并且您不需要线程刷新列表时,此DB会通知您。