2

Good morning, and greetings to all, I am new to android JAVA, and searching the Internet, I found a class for java android to query a database in mysql through JSON and PHP, now I'm trying,It is to consult in an endless cycle every 10 seconds. Searching the internet, comment the following code, but do not know how to implement it ... Any help, comments, be well appreciated, Greetings

This is the code of the class:

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

update 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";
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);

}
  };


 }

or how can I implement AnsyTask in my code

  • 2
    Stack Overflow is not "code writer" service. Also it is even unclear, what you want. – Tsyvarev Jan 02 '16 at 15:07
  • http://stackoverflow.com/questions/6242268/repeat-a-task-with-a-time-delay – K Neeraj Lal Jan 02 '16 at 15:16
  • Excuse misuse. I am trying, is that real-time display to update or alter any records, DB, reflected immediately on the APP. or run the method showList in an infinite loop 10 to 5 seconds – JESUS ESPINOSA Jan 02 '16 at 15:19
  • Did you check the above link? – K Neeraj Lal Jan 02 '16 at 15:27
  • i try this http://www.tutorialandroid.com/basico/como-realizar-accion-tras-esperar-unos-segundos-con-postdelayed/ – JESUS ESPINOSA Jan 02 '16 at 22:43
  • hello, checking, checking out the link I provide me @ K Neeraj Lal, I stay the following code, but now when I run in the terminal sends the message that the application has stopped.. seee up – JESUS ESPINOSA Jan 03 '16 at 17:12
  • Bro your question is so hard to understand, but you seem to know english so Im confused – meda Jan 03 '16 at 17:17
  • Sorry I do not speak English, I try to write it is best to understand me...,i try to make a app to read data from a database in MySQL, THROUGH JSON and PHP to run the query every N seconds, and thus not be closing and opening the app to get the updated information ... – JESUS ESPINOSA Jan 03 '16 at 17:35
  • I'm trying to make a reader notices, a ListView with dynamic data from json and MySQL that automatically refresh every 8 seconds to display all the data from the database – JESUS ESPINOSA Jan 09 '16 at 15:14

1 Answers1

0

Basically you are looking for service that will check your database for every 10 seconds. And if there is a new data then it will fetch that data. For this you can use a service Create a class that extends Service class override onstartCommand() method and inside this method write your network request code don't forget to user threading otherwise service will take more time. If you want to create a non destroy-able service that will not be killed if you restarts your mobile then you should return 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);

By this way you can make a network call for each 10 seconds interval . But executing service in seconds is not a good practice because it will drain your battery.

Simon Dzn
  • 150
  • 1
  • 1
  • 8
  • thanks for your reply, Developer_Vaibhav, and Simon_Dzn, but I have more confused, searching the internet I found a link describing the problem more accurately, try instead to call the method showList, call getData and running the app, if modify the table from phpadmin, the modification is not seen in the app. The link you see the same problem: http://stackoverflow.com/questions/32424710/android-how-to-make-my-retrieved-from-mysql-json-parsed-data-added-to-listvie – JESUS ESPINOSA Jan 05 '16 at 15:04