Android的:如何让我的检索(从MySQL)JSON解析加入到ListView控件的数据刷新自我的每一分钟 [英] Android: How to make my retrieved (from mysql) JSON parsed data added to ListView refresh it self every minute

查看:125
本文介绍了Android的:如何让我的检索(从MySQL)JSON解析加入到ListView控件的数据刷新自我的每一分钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的code,有一个从MySQL数据库(6弦)通过PHP获取数据的Andr​​oid应用程序,直接到ListView一个活动。

数据取精的作品,我只需要在ListView为自动刷新自我,也警惕新的数据是由声音和振动获取用户。

应该心存感激解决的办法,先谢谢了。

P.S:我知道,我使用的是德precated方法是从API 22等。

 < PHP    定义(HOST,my_hostname ..');
    定义('USERNAME','MySQL用户名');
    定义('密码','MySQL的密码');
    定义(DB,MySQL数据库名称');    $ CON = mysqli_connect(主机,用户名,密码,DB)或死亡(无法    连接');    $的SQL =选择订单*;    $解析度= mysqli_query($ CON,$ SQL);    $结果=阵列();   而($行= mysqli_fetch_array($水库)){
   array_push($结果,
   阵列('用户'=> $行[0],城市= GT; $行[1],'街头'=> $行[2]
   streetnumber'=> $行[3],'电话'=> $行[4],'名'=> $行[5]));
   }   回声json_en code(阵列(结果=> $结果));   mysqli_close($ CON);   ?>

和Android的工作室活动

 进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.support.v7.app.ActionBarActivity;
进口android.view.Menu;
进口android.view.MenuItem;
进口android.widget.ListAdapter;
进口android.widget.ListView;
进口android.widget.SimpleAdapter;进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.apache.http.params.BasicHttpParams;
进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;进口java.io.BufferedReader中;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口的java.util.ArrayList;
进口的java.util.HashMap;
公共类ViewOrdersActivity扩展ActionBarActivity {    串myJSON;    私有静态最后弦乐TAG_RESULTS =结果;
    私有静态最后弦乐TAG_USER =用户;
    私有静态最后弦乐TAG_CITY =城市;
    私有静态最后弦乐TAG_STREET =街;
    私有静态最后弦乐TAG_STREETNUMBER =streetnumber;
    私有静态最后弦乐TAG_PHONE =手机;
    私有静态最后弦乐TAG_NAME =名;    JSONArray订单= NULL;    ArrayList的<&HashMap的LT;字符串,字符串>> ordersList;    ListView控件列表;    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_view_orders);
        名单=(ListView控件)findViewById(R.id.listView);
        ordersList =新的ArrayList<&HashMap的LT;字符串,字符串>>();        的getData();    }    保护无效showList(){
        尝试{
            JSONObject的jsonObj =新的JSONObject(myJSON);
            订单= jsonObj.getJSONArray(TAG_RESULTS);            的for(int i = 0; I< ORDERS.length();我++){
                JSONObject的C = ORDERS.getJSONObject(I)
                字符串用户= c.getString(TAG_USER);
                字符串城市= c.getString(TAG_CITY);
                串街道= c.getString(TAG_STREET);
                字符串streetnumber = c.getString(TAG_STREETNUMBER);
                字符串手机= c.getString(TAG_PHONE);
                字符串名称= c.getString(TAG_NAME);
                HashMap的<字符串,字符串>订单=新的HashMap<字符串,字符串>();                orders.put(TAG_USER,用户);
                orders.put(TAG_CITY,市);
                orders.put(TAG_STREET,街道);
                orders.put(TAG_STREETNUMBER,streetnumber);
                orders.put(TAG_PHONE,电话);
                orders.put(TAG_NAME,名);
                ordersList.add(订单);
            }            ListAdapter适配器=新SimpleAdapter(
                    ViewOrdersActivity.this,ordersList,R.layout.list_item,
                    新的String [] {TAG_USER,TAG_CITY,TAG_STREET,TAG_STREETNUMBER,TAG_PHONE,TAG_NAME},
                    新的INT [] {R.id.user,R.id.city,R.id.street,R.id.streetnumber,R.id.phone,R.id.name}
            );            list.setAdapter(适配器);
            list.invalidateViews();        }赶上(JSONException E){
            e.printStackTrace();
        }    }
    公共无效的getData(){
        类GetDataJSON扩展的AsyncTask<弦乐,太虚,字符串> {
            @覆盖
            保护字符串doInBackground(字符串... PARAMS){                DefaultHttpClient的HttpClient =新DefaultHttpClient(新BasicHttpParams());
                HttpPost httppost =新HttpPost(HTTP://myweb/folder/myphpfile.php);                httppost.setHeader(内容类型,应用/ JSON);                为InputStream的InputStream = NULL;
                字符串结果= NULL;
                尝试{
                    HTT presponse响应= httpclient.execute(httppost);
                    HttpEntity实体= response.getEntity();                    的InputStream = entity.getContent();
                    // JSON默认为UTF-8
                    读者的BufferedReader =新的BufferedReader(新的InputStreamReader(InputStream中,UTF-8),8);
                    StringBuilder的SB =新的StringBuilder();                    串线= NULL;
                    而((行= reader.readLine())!= NULL)
                    {
                        sb.append(行+\\ n);
                    }
                    结果= sb.toString();
                }赶上(例外五){
                    //哎呀
                }
                最后{
                    尝试{如果(InputStream的!= NULL)inputStream.close();}赶上(例外挤){}
                }
                返回结果;
            }            @覆盖
            保护无效onPostExecute(字符串结果){
                myJSON =结果;
                showList();
            }        }        GetDataJSON G =新GetDataJSON();
        g.execute();
    }    @覆盖
    公共布尔onCreateOptionsMenu(菜单菜单){
        //充气菜单;如果是present这增加了项目操作栏。
        。getMenuInflater()膨胀(R.menu.menu_main,菜单);
        返回true;
    }    @覆盖
    公共布尔onOptionsItemSelected(菜单项项){
        //处理动作栏项目点击这里。操作栏会
        //自动处理上点击主页/向上按钮,只要
        //你在AndroidManifest.xml中指定一个父活动。
        INT ID = item.getItemId();        // noinspection SimplifiableIfStatement
        如果(ID == R.id.action_settings){
            返回true;
        }        返回super.onOptionsItemSelected(项目);
    }
}


解决方案

 公共无效refreshlistview(){
 CountDownTimer mCountDownTimer =新CountDownTimer(60000,1000){
        公共无效onTick(长millisUntilFinished){        }
        公共无效onFinish(){
          //不要在这里刷新          //然后再调用它 - 递归
          refreshlistview();
        }
    };
 }

您可以使用定时器并刷新每1分钟= 60000毫秒

要比较的数据,我看到你用你的showlist一个HashMap()
所以使它返回一个HashMap,你可以调用它,每当你需要获取新的数据,并通过新老一这种方法,如果返回true,则数据被其他人平等的,你可以通知该数据已更改用户并重新设置的ListView适配器

 公开的HashMap<字符串,字符串>比较(地图<字符串,字符串>的时候,地图<字符串,字符串>新)
{
    对于(字符串我:old.keySet())
    {
        如果(old.get(ⅰ)!= new.get(ⅰ)){
            返回false;
        }
    }
 返回true;
}

In the code below, there's one activity that is fetching data from a mysql database (6 strings) via php to the android app and straight to a ListView.

The data fetch works fine, I just need the ListView to "automatically" refresh it self and also alert to the user that new data was fetched by sound and vibration.

Will be thankful for a solution, thanks in advance.

P.S: I know that I'm using deprecated methods that are from API 22 etc..

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

   ?>

And the 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);
    }
}

解决方案

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

you can use timer and refresh every 1 mins = 60000 millisecond

to compare data i see you're using a hashmap on your showlist() so make it to return a hashmap and you can call it whenever you need to fetch new data and pass the old and new one to this method if it return true then the data is equal else you can inform the user that the data has been changed and set listview adapter again

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

这篇关于Android的:如何让我的检索(从MySQL)JSON解析加入到ListView控件的数据刷新自我的每一分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆