gpt4 book ai didi

php - Android:如何使我检索到的(从 mysql 中)JSON 解析数据添加到 ListView 每分钟刷新一次

转载 作者:行者123 更新时间:2023-11-29 03:29:22 27 4
gpt4 key购买 nike

在下面的代码中,有一个 Activity 通过 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 Activity

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 {
try{if(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);
}
}

最佳答案

这道题可以通过两种方式完成,一种是通过 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。

通过在主线程中创建处理程序,您可以确保您发布到处理程序的所有内容也在主线程中运行。

关于php - Android:如何使我检索到的(从 mysql 中)JSON 解析数据添加到 ListView 每分钟刷新一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32424710/

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