Android每10秒选择查询JSON无限循环

标签 android mysql

<分区>

早上好,大家好,我是android JAVA新手,在网上搜索了一下,找到了java android通过json和php查询mysql数据库的类,现在正在尝试,就是每 10 秒无限循环咨询一次。 在网上搜索,注释下面的代码,但不知道如何实现... 任何帮助,评论,不胜感激,问候

这是类的代码:

public class VerA extends ActionBarActivity {

String myJSON;

private static final String TAG_RESULTS="result";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "nombre";
private static final String TAG_ADD ="telefono";
private Handler mHandler;
private int mInterval = 8000; // 5 seconds by default, can be changed later


JSONArray peoples = null;

ArrayList<HashMap<String, String>> personList;

ListView list;




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    list = (ListView) findViewById(R.id.listView);
    personList = new ArrayList<HashMap<String,String>>();
    mHandler = new Handler();
    startRepeatingTask();
    getData();



}




protected void showList(){
    try {
        JSONObject jsonObj = new JSONObject(myJSON);
        peoples = jsonObj.getJSONArray(TAG_RESULTS);

        for(int i=0;i<peoples.length();i++){
            JSONObject c = peoples.getJSONObject(i);
            String id = c.getString(TAG_ID);
            String name = c.getString(TAG_NAME);
            String address = c.getString(TAG_ADD);

            HashMap<String,String> persons = new HashMap<String,String>();

            persons.put(TAG_ID,id);
            persons.put(TAG_NAME,name);
            persons.put(TAG_ADD,address);

            personList.add(persons);
        }

        ListAdapter adapter = new SimpleAdapter(
                VerA.this, personList, R.layout.list_item,
                new String[]{TAG_ID,TAG_NAME,TAG_ADD},
                new int[]{R.id.id, R.id.name, R.id.address}
        );

        list.setAdapter(adapter);

    } 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://tuescuelanoticias.x10.mx/selectAllJSON.php");

            // Depends on your web service
            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();
}


///course method, which should refresh the query on the base dedatos every 8 seconds

Runnable mStatusChecker = new Runnable() {
    @Override
    public void run() {
        getData();
        mHandler.postDelayed(mStatusChecker, mInterval);
    }
};
void startRepeatingTask() {
    mStatusChecker.run();
}
}

更新代码:

 public class VerA extends ActionBarActivity {

String myJSON;
private static final String TAG_RESULTS="result";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "nombre";
private static final String TAG_ADD ="telefono";
Handler handler = new Handler();
JSONArray peoples = null;

ArrayList<HashMap<String, String>> personList;

ListView list;




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    list = (ListView) findViewById(R.id.listView);
    personList = new ArrayList<HashMap<String,String>>();
    getData();
    handler.postDelayed(runnable, 8000);


}



  // METODO QUE MUESTRA LA LISTA O LA MATRIZ
protected void showList(){
    try {
        JSONObject jsonObj = new JSONObject(myJSON);
        peoples = jsonObj.getJSONArray(TAG_RESULTS);

        for(int i=0;i<peoples.length();i++){
            JSONObject c = peoples.getJSONObject(i);
            String id = c.getString(TAG_ID);
            String name = c.getString(TAG_NAME);
            String address = c.getString(TAG_ADD);

            HashMap<String,String> persons = new HashMap<String,String>();

            persons.put(TAG_ID,id);
            persons.put(TAG_NAME,name);
            persons.put(TAG_ADD,address);

            personList.add(persons);
        }

        ListAdapter adapter = new SimpleAdapter(
                VerA.this, personList, R.layout.list_item,
                new String[]{TAG_ID,TAG_NAME,TAG_ADD},
                new int[]{R.id.id, R.id.name, R.id.address}
        );

        list.setAdapter(adapter);

    } catch (JSONException e) {
        e.printStackTrace();
    }

}


   ///METODO QUE EXTRAE LOS DATOS DE EL JASON PHP
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://tuescuelanoticias.x10.mx/selectAllJSON.php");

            // Depends on your web service
            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();
}


  ///LOS METODOS SIGUIENTES MUESTRAN LA OPCION DE MENU Y CONFIGRUACIO
@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);

}

  ///DISQUE PARA QUE SE REFRESQUE CADA 8 SEGUNDOS, AL PARECER SI TRAE LOS         DATOS PERO NO LOS DIBUJA
 private Runnable runnable = new Runnable() {
public void run() {
    showList();
        // Do some updates
        handler.postDelayed(this, 8000);

}
  };


 }

或者如何在我的代码中实现 AnsyTask

最佳答案

基本上,您正在寻找每 10 秒检查一次数据库的服务。如果有新数据,它将获取该数据。为此,您可以使用服务创建一个扩展服务类覆盖 onstartCommand() 方法的类,并在此方法中编写您的网络请求代码,不要忘记用户线程,否则服务将花费更多时间。如果你想创建一个不可销毁的服务,如果你重新启动你的手机也不会被杀死,那么你应该返回 Service.START_STICKY。

AlarmManager alarmManager=(AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),100000,                                                                 pendingIntent);

通过这种方式,您可以每隔 10 秒进行一次网络调用。但是在几秒钟内执行服务并不是一个好习惯,因为它会耗尽你的电池。

关于Android每10秒选择查询JSON无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34567101/

相关文章:

java - 检测Android是否通过USB连接电脑

android - 如何让我的 SharedPreferences 对象在应用程序关闭后保存数据?

android - 如何在 android 中的网格 recyclerview 中做反向爆炸过渡动画

mysql - 如何获取所有学生和作业的列表以及成绩?

mysql - 从一张表中获取两列数据

mysql - 轻松删除 SQL 表中的重复条目

android - 了解 OBDII 协议(protocol)的数据

javascript - 如何修复 router.get 中相互依赖的两个 Knex MySQL 查询

php - 用PHP输出UTF-8特殊字符

javascript - 使用移动网络应用程序进行网络抓取?