Refresh query of a JSON every X seconds

1

The following Activity gets the data of a file in PHP that generates a JSON with the data obtained from MYSQL , I am new in this JAVA ANDROID , and I have little experience in PHP , I barely defend myself, but I'm trying to learn little by little.

The problem with my Activity is that every time it refreshes, the scroll bar is thrown up, so what I think can solve this problem is implement a method that is consulting every N second through JSON in the background and if it detects that the content of the table is different from the previous table launch the GETDATA , for it I imagine many unorthodox ways I guess, how to create a copy of the same table in mysql or something similar and compare the arrangements in JAVA, which is complicated for me because I just understand the code and features of JAVA ANDROID , any help suggestion, comment whether good or bad will be well appreciated greetings.

Here the code

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";
 JSONArray peoples = null;
 ArrayList<HashMap<String, String>> personList;
 ListView list;

Handler myHandler = new Handler();
final Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    list = (ListView) findViewById(R.id.listView);

    /// AQUI REFRESCO LA LISTA ENTOCES SI YO INGRESO UN DATO NUEVO EN LA BASE DE DATOS ESTE SE MEUSTRA
    //EL PROBLEMA ES QUE EL SCROLL BAR SUBE CADA 10 SEGUNDOS
    myHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            personList = new ArrayList<HashMap<String, String>>();
            getData();
            handler.postDelayed(this, 10000);
        }
    }, 0);

}

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

    return super.onOptionsItemSelected(item);

 }

}
    
asked by JESUS ESPINOSA 18.01.2016 в 02:26
source

2 answers

4

You can add another list of ArrayList > temporary to store the contents of your previous list and after the call to compare the size of the list if it is greater means that there were changes and therefore you have to update your table (ListView), otherwise it does not require updating; Another possibility is in your web service to send a property "count" with the amount of data that is sent and to get the response from the server only verify if the amount is different and update the list, this would save the iteration of the whole list to check the size of the lists NOTE: this will only update when fields have been added or deleted.

Modified code:

    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";
    JSONArray peoples = null;
    ArrayList<HashMap<String, String>> personList;
    ArrayList<HashMap<String,String>> personListTemp;
    ListView list;

    Handler myHandler = new Handler();
    final Handler handler = new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      list = (ListView) findViewById(R.id.listView);
      personListTemp = new ArrayList<HashMap<String, String>>();

/// AQUI REFRESCO LA LISTA ENTOCES SI YO INGRESO UN DATO NUEVO EN LA BASE DE DATOS ESTE SE MEUSTRA
//EL PROBLEMA ES QUE EL SCROLL BAR SUBE CADA 10 SEGUNDOS
myHandler.postDelayed(new Runnable() {
    @Override
    public void run() {
        personList = new ArrayList<HashMap<String, String>>();
        getData();
        handler.postDelayed(this, 10000);
    }
}, 0);

}

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

if(personList.size() != personListTemp.size() ){
        personListTemp = personList;
        ListAdapter adapter = new SimpleAdapter(
                VerA.this, personListTemp, 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();
}

return super.onOptionsItemSelected(item);

}

}
    
answered by 18.01.2016 / 17:48
source
1

How about, I understand that @AngelRuizC's response has been great for you. But checking your code I have noticed some things that catch my attention. Your query to the server is to list a series of elements somewhere, that is, a GET as standardized by the HTTP protocol; but I notice in your snippet of code that the query to the server is done through a HttpPost I would recommend that for this type of processes (HHTP processes GET / POST / etc.) You will create a class that has those methods that are easily reusable, for example to make a GET to any server you can have a function like this:

public static InputStream getJsonFromServer(String _url) {
    try {
        URL url = new URL(_url);
        URLConnection urlConnection = url.openConnection();
        return urlConnection.getInputStream();
    }catch(Exception e) {
        return null;
    }
}

Suppose that the utility class is called Http Connections, you would simplify your code to the following, in the PHP call

InputStream jsonStream = ConexionesHttp.getJsonFromServer("http://tuescuelanoticias.x10.mx/selectAllJSON.php");

Then a InputStream can be paired to String in the following way

 String jsonStr = new Scanner(jsonStream , "UTF-8").useDelimiter("\A").next();

This way every time you need to make an http query at another point you do not have to rewrite it. I hope you help greetings!

    
answered by 22.01.2016 в 15:44