在下面的代码中,有一个活动是通过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);
}
}
答案 0 :(得分:0)
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;
}
答案 1 :(得分:0)
这个问题可以通过两种方式完成,一种是TimerTask类,另一种是Handler类。我更喜欢Handler,所以我发布了如何使用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。
通过在主线程中创建处理程序,您可以确保发布到处理程序的所有内容也在主线程中运行。