threads-in-adnroid2

To begin with, in the last post we talked a little bit about the asynctask. The main purpose of that for us, was to help us to understand how does it work and use it for a real time plotting. We had a great result doing that with the help of some code on the web and some of our ideas. Below, you can see the XML of the main activity.

<pre><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ap="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <!-- l -->
    <!-- Aquí empieza la gráfica -->
    <!-- l -->
    <com.androidplot.xy.XYPlot
        android:id="@+id/pot"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"

        ap:domainLabel="Domain"
        ap:rangeLabel="Range"
        ap:graphMarginTop="20dp"
        ap:graphMarginLeft="15dp"
        ap:graphMarginBottom="25dp"
        ap:graphMarginRight="10dp"

        ap:gridBackgroundColor="#000000"/>
    <!-- l -->
    <!-- En la pagina inferior vienen los atributos que se pueden configurar -->
    <!--https://github.com/halfhp/androidplot/blob/master/androidplot-core/src/main/res/values/attrs.xml -->
    <!-- Aquí finaliza la gráfica -->
    <!-- l -->

</RelativeLayout></pre>

What we did was to set up the basic layout of a graph in Android Plot. Don´t forget that it is necessary to add the library from Android Plot in the section or file (Build:Gradle (App) ) so that the graph can be shown. After that, we used some code of the last post ( Threads in Android) but just the section of the Async Task. You can see the code of the java file, which is the main activity.

<pre>package com.example.android.refreshinrealtimeachart;

//Graficar en tiempo real usando AndroidPlot y asynctask
//Combinación de programas aquí
//Uar el asynctask y un thread sleep dentro de doInBackGround

//Enlaces importantes:
// http://stackoverflow.com/questions/31511865/android-plot-how-to-refresh-in-real-time-a-chart 10/13/2016

public class MainActivity extends ActionBarActivity {

    private XYPlot plot;
    private Number[] grafica = {1, 3, 2, 4, 3, 2}; //Tamaño 6

    RefreshScreen RefreshTask; //Clase creada para refrescar gráfica usando asyncTask

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        plot = (XYPlot) findViewById(R.id.pot);
        DaleFormatoAndroidPlot ();
        ActivaTareaAsincrona ();
    }

    private class RefreshScreen extends AsyncTask<Void, Number, Void> {

        @Override
        protected Void doInBackground(Void... params) {
           int i = 0 ;
            try {
                do{
                   for (int a = 0; a < grafica.length - 1; a++) {
                    //movemos todos los numeros una posicion a la izquierda
                    grafica[a] = grafica[a + 1];
                     }
                //El ultimo numero haremos que sea aleatorio
                grafica[grafica.length - 1] = Math.floor(Math.random() * 10 + 1);
                publishProgress(grafica);
                Thread.sleep(1000); //Refresh rate 1 segundo
                    i++; //Si quito este i++ el ciclo se vuelve infinito.
                }while(i<=20); //Con esto se controla el numero de segundos que se quiere graficar
            }catch (Exception e) {

            }
            return null;
    }

        @Override
        protected void onProgressUpdate(Number... values) {

            //Cargamos el nuevo array en la clase XYSERIES / Cuantitativo
            XYSeries series = new SimpleXYSeries(
                    Arrays.asList(grafica),
                    SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "Series");

            //Le damos formato de líneas / Cualitativo
            //Enlace colores posibles para la línea, curva, area bajo la curva, etc
            //https://material.google.com/style/color.html#color-color-palette
            LineAndPointFormatter seriesFormat = new LineAndPointFormatter(Color.parseColor("#00E5FF"),Color.parseColor("#E91E63"),
                    Color.parseColor("#69F0AE"),null);
            seriesFormat.setPointLabelFormatter(new PointLabelFormatter());

            //Limpiamos la gráfica
            plot.clear();
            //Añadimos la nueva gráfica
            plot.addSeries(series, seriesFormat);
            plot.redraw();
        }
    }

    private void ActivaTareaAsincrona(){

        RefreshTask= new RefreshScreen ();
        RefreshTask.execute();
    }

    private void DaleFormatoAndroidPlot (){

        //Cargamos el nuevo array en la clase XYSERIES
        XYSeries series = new SimpleXYSeries(
                Arrays.asList(grafica),
                SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "Series");
        //Le damos formato de líneas
        //Enlace colores posibles para la línea, curva, area bajo la curva, etc
        LineAndPointFormatter seriesFormat = new LineAndPointFormatter(Color.parseColor("#00E5FF"),Color.parseColor("#E91E63"),
                Color.parseColor("#69F0AE"),null);
        seriesFormat.setPointLabelFormatter(new PointLabelFormatter());
        //Limpiamos la gráfica
        plot.clear();
        //Añadimos la nueva gráfica
        plot.addSeries(series, seriesFormat);
        plot.redraw();
    }
}</pre>

It is very important to highlight that within the doInBackground() methodthe number that is in the first position of the vector is shifted out and then a random number is added to the last position. After that, the whole vector (grafica) is sent to onProgressUpdate() to refresh the interface. It is also very important to point out that some lines have to be implemented to redraw the graph, otherwise it will not be refreshed. These lines are implemented within onProgressUpdate() and some of them are : plot.clear(), plot.addSeries() and plot.redraw().  XYSeries and LineAndPointFormatter have also to be uploaded before everything.

Something also important is in the part of the do-while because it controls if the loop is going to be infinite or if you want to perform the shifting a specific amount of times.

The result of this code can be seen in the following screenshot.

screenshot_2016-10-16-09-25-54

Sources and helpful material :

[1] http://stackoverflow.com/questions/31511865/android-plot-how-to-refresh-in-real-time-a-chart

[2] https://material.google.com/style/color.html#color-color-palette

[3] http://androidplot.com/

[4] http://wptrafficanalyzer.in/blog/android-dynamic-chart-using-achartengine/

Anuncios