Android:如何让我检索到的(来自 mysql)JSON 解析数据添加到 ListView 每分钟刷新一次
Posted
技术标签:
【中文标题】Android:如何让我检索到的(来自 mysql)JSON 解析数据添加到 ListView 每分钟刷新一次【英文标题】:Android: How to make my retrieved (from mysql) JSON parsed data added to ListView refresh it self every minute 【发布时间】:2015-12-02 04:27:09 【问题描述】:在下面的代码中,有一个活动是通过 php 从 mysql 数据库(6 个字符串)获取数据到 android 应用程序并直接到 ListView。
数据获取工作正常,我只需要 ListView 自行“自动”刷新它并提醒用户新数据是通过声音和振动获取的。
将感谢您的解决方案,在此先感谢。
P.S:我知道我正在使用 API 22 等已弃用的方法。
<?php
define('HOST','my_hostname..');
define('USERNAME','mysql username');
define('PASSWORD','mysql password');
define('DB','mysql db name');
$con = mysqli_connect(HOST,USERNAME,PASSWORD,DB) or die('Unable to
connect');
$sql = "select * from orders";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res))
array_push($result,
array('user'=>$row[0],'city'=>$row[1],'street'=>$row[2],
'streetnumber'=>$row[3],'phone'=>$row[4],'name'=>$row[5]));
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>
还有 Android Studio 活动
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
public class ViewOrdersActivity extends ActionBarActivity
String myJSON;
private static final String TAG_RESULTS="result";
private static final String TAG_USER = "user";
private static final String TAG_CITY = "city";
private static final String TAG_STREET ="street";
private static final String TAG_STREETNUMBER ="streetnumber";
private static final String TAG_PHONE ="phone";
private static final String TAG_NAME ="name";
JSONArray ORDERS = null;
ArrayList<HashMap<String, String>> ordersList;
ListView list;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_orders);
list = (ListView) findViewById(R.id.listView);
ordersList = new ArrayList<HashMap<String,String>>();
getData();
protected void showList()
try
JSONObject jsonObj = new JSONObject(myJSON);
ORDERS = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<ORDERS.length();i++)
JSONObject c = ORDERS.getJSONObject(i);
String user = c.getString(TAG_USER);
String city = c.getString(TAG_CITY);
String street = c.getString(TAG_STREET);
String streetnumber = c.getString(TAG_STREETNUMBER);
String phone = c.getString(TAG_PHONE);
String name = c.getString(TAG_NAME);
HashMap<String,String> orders = new HashMap<String,String>();
orders.put(TAG_USER, user);
orders.put(TAG_CITY, city);
orders.put(TAG_STREET, street);
orders.put(TAG_STREETNUMBER, streetnumber);
orders.put(TAG_PHONE, phone);
orders.put(TAG_NAME, name);
ordersList.add(orders);
ListAdapter adapter = new SimpleAdapter(
ViewOrdersActivity.this, ordersList, R.layout.list_item,
new String[]TAG_USER, TAG_CITY, TAG_STREET, TAG_STREETNUMBER, TAG_PHONE, TAG_NAME,
new int[]R.id.user, R.id.city, R.id.street,R.id.streetnumber, R.id.phone , R.id.name
);
list.setAdapter(adapter);
list.invalidateViews();
catch (JSONException e)
e.printStackTrace();
public void getData()
class GetDataJSON extends AsyncTask<String, Void, String>
@Override
protected String doInBackground(String... params)
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://myweb/folder/myphpfile.php");
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line + "\n");
result = sb.toString();
catch (Exception e)
// Oops
finally
tryif(inputStream != null)inputStream.close();catch(Exception squish)
return result;
@Override
protected void onPostExecute(String result)
myJSON=result;
showList();
GetDataJSON g = new GetDataJSON();
g.execute();
@Override
public boolean onCreateOptionsMenu(Menu menu)
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
@Override
public boolean onOptionsItemSelected(MenuItem item)
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings)
return true;
return super.onOptionsItemSelected(item);
【问题讨论】:
Repeat a task with a time delay? 的可能重复项 【参考方案1】:这个问题可以通过两种方式完成,一种是 TimerTask 类,另一种是 Handler 类。我更喜欢 Handler one,所以我发布了如何使用 Handler
http://developer.android.com/reference/java/util/TimerTask.html
final Handler handler = new Handler()
handler.postDelayed( new Runnable()
@Override
public void run()
YOUR_ADAPTER_GOES_HERE.notifyDataSetChanged();
//dont forget to call getData();
handler.postDelayed( this, 60 * 10000 ); //ensure to run after 10 minutes
, 60 * 10000 );
您只能在主 (UI) 线程中更新 UI。
通过在主线程中创建处理程序,您可以确保您发布到处理程序的所有内容也在主线程中运行。
【讨论】:
嗨,rewrihitesh,我看到了一个带有类似评论的线程,我有一个问题:我不仅需要每 X 秒刷新一次数据,我还需要一个新插入数据的指示器只是为了通知/提醒 AppUser 插入了新数据,他应该检查一下,毕竟这是一部不是 24/7 在客户眼前的电话。所以我的问题是,我该如何解决这个问题?【参考方案2】: public void refreshlistview()
CountDownTimer mCountDownTimer = new CountDownTimer(60000, 1000)
public void onTick(long millisUntilFinished)
public void onFinish()
//do refresh here
//then call it again - Recursive
refreshlistview();
;
您可以使用计时器并每 1 分钟刷新一次 = 60000 毫秒
为了比较数据,我看到你在你的 showlist() 上使用了一个 hashmap 所以让它返回一个hashmap,你可以在需要获取新数据时调用它,并将旧的和新的传递给这个方法,如果它返回true,那么数据是相等的,否则你可以通知用户数据已被更改并再次设置 listview 适配器
public HashMap<String,String> compare(Map<String, String> old,Map<String,String> new)
for (String i : old.keySet())
if (old.get(i) != new.get(i))
return false;
return true;
【讨论】:
有一个问题,用户必须在插入新数据时得到通知,将新数据粘贴到旧数据上不会总是告诉我是否插入了新数据 您需要为此比较适配器数据,在获取新适配器之前保留旧适配器并比较它们并在需要时显示消息 你有没有机会告诉我如何实现那个伙伴?【参考方案3】:Android WorkManager api 是最好的解决方案work manager
【讨论】:
以上是关于Android:如何让我检索到的(来自 mysql)JSON 解析数据添加到 ListView 每分钟刷新一次的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Java Android App 中使用从 Webserver 检索到的 JSON 来动态创建和使用对象
Android应用程序解码来自PHP MySql数据库的JSON响应,没有特殊字符
如何将检索到的数据从 v-for 绑定到 Vuejs 中的数据对象?