0

I have a method that receive each interaction from another class, a JSONObject- This JSONObject is kept each time to extract some parameters and re-send to add(new Entry...). then begin process, receiving again new JSONObject with updated data and again extract and so on...

I need that when I receive each time this JSONObject, can be extracted the parameters but not add inmediatly to "temperaturas and dates by add(new Entry..)" , I need this paramteres been kept in a "List" or "MAP" in order to eliminate the duplicate paramateres, after this I will send it to "add(new Entry...." Why?

each time JSONOBJECTS RECEIVED

# first time
{"Id_temp":"1","temperatura":"20","Insertado_temp":"2016-08-16 12:30:29"}

# second time
{"Id_temp":"1","temperatura":"20","Insertado_temp":"2016-08-16 12:30:29"}

# third time
{"Id_temp":"2","temperatura":"25","Insertado_temp":"2016-08-16 15:48:53"}

# Fourth time
{"Id_temp":"4","temperatura":"50","Insertado_temp":"2016-08-16 18:17:33"}

# Fith time
{"Id_temp":"1","temperatura":"20","Insertado_temp":"2016-08-16 12:30:29"}

# An so on ...

Because as I show here I am receiving some duplicated data inside of JSON.

this is the code(UPDATED):

public class GraficaBarometro extends AppCompatActivity implements OnLoopjCompletedBarometro {

private DrawerLayout drawerLayout;

private OnLoopjCompletedBarometro loopjListener;

// Progress Dialog Object
ProgressDialog prgDialog;
// Error Msg TextView Object
TextView errorMsg;
// Email Edit View Object

private String temeperatura;

private Timestamp timestamp;


List<Entry> presiones = new ArrayList<>();
List<Entry> temperaturas = new ArrayList<>();
List<String> dates = new ArrayList<>();



LineChart mChart;

LoopjTasksBarometro loopjTasks;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.actividad_grafica_barometro);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    String idObjeto = (String) getIntent().getExtras().getSerializable("IdentidadEnviada");

    loopjTasks = new LoopjTasksBarometro(this, this);
    loopjTasks.CaptarParametros(idObjeto);


    mChart = (LineChart) findViewById(R.id.chartbarometro);

    int currentTime = (int) System.currentTimeMillis();
    timestamp = new Timestamp(currentTime);

    // no description text
    mChart.setDescription("");
    mChart.setNoDataTextDescription("You need to provide data for the chart.");

    // enable touch gestures
    mChart.setTouchEnabled(true);

    mChart.setDragDecelerationFrictionCoef(0.9f);

    // enable scaling and dragging
    mChart.setDragEnabled(true);
    mChart.setScaleEnabled(true);
    mChart.setDrawGridBackground(true);
    mChart.setHighlightPerDragEnabled(true);

    // limit the number of visible entries
    mChart.setVisibleXRangeMaximum(5);

    // if disabled, scaling can be done on x- and y-axis separately
    mChart.setPinchZoom(true);

    // set an alternative background color
    mChart.setBackgroundColor(Color.LTGRAY);


    mChart.animateX(2500);

// to draw X-axis for our graph;

    XAxis xAxis = mChart.getXAxis();
    xAxis.setTextSize(11f);
    xAxis.setEnabled(true);
    xAxis.setPosition(com.github.mikephil.charting.components.XAxis.XAxisPosition.BOTTOM);
    //xAxis.setAxisMaxValue(125f);
    xAxis.setAxisMinValue(0f);
    xAxis.setTextColor(Color.DKGRAY);
    xAxis.setDrawGridLines(false);
    xAxis.setDrawAxisLine(true);

    // to draw axis line

    //modify leftYaxis range similarly others
    YAxis leftAxis = mChart.getAxisLeft();
    leftAxis.setTextColor(ColorTemplate.getHoloBlue());
    leftAxis.setAxisMaxValue(50f);
    leftAxis.setAxisMinValue(10f);
    leftAxis.setDrawGridLines(false);
    leftAxis.setGranularityEnabled(true);


    YAxis rightAxis = mChart.getAxisRight();
    rightAxis.setTextColor(Color.RED);
    rightAxis.setAxisMaxValue(50f);
    rightAxis.setAxisMinValue(10f);
    rightAxis.setDrawGridLines(false);
    rightAxis.setDrawZeroLine(false);
    rightAxis.setGranularityEnabled(false);


}


private void agregarToolbar() {
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    final ActionBar ab = getSupportActionBar();
    if (ab != null) {
        // Poner ícono del drawer toggle
        ab.setHomeAsUpIndicator(R.drawable.drawer_toggle);
        ab.setDisplayHomeAsUpEnabled(true);
    }

}

private void prepararDrawer(NavigationView navigationView) {
    navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem) {
                    menuItem.setChecked(true);
                    seleccionarItem(menuItem);
                    drawerLayout.closeDrawers();
                    return true;
                }
            });

}


private void seleccionarItem(MenuItem itemDrawer) {
    Fragment fragmentoGenerico = null;

    FragmentManager fragmentManager = getSupportFragmentManager();


    switch (itemDrawer.getItemId()) {



        case R.id.item_web:

            startActivity(new Intent(this, WebOficial.class));
            break;

        //fragmentoGenerico = new BlankFragment();


        case R.id.item_categorias:
            startActivity(new Intent(this, ActividadListaObjeto.class));
            break;

        case R.id.item_acceso:
            startActivity(new Intent(this, MainActivity.class));
            break;
    }
    if (fragmentoGenerico != null) {
        fragmentManager
                .beginTransaction()
                .replace(R.id.contenido_principal, fragmentoGenerico)
                .commit();

        /*
        if(fragmentTransaction) {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.content_frame, fragment)
                    .commit();
           */

    }

    // Setear titulo actual
    setTitle(itemDrawer.getTitle());
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_actividad_principal, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            drawerLayout.openDrawer(GravityCompat.START);
            return true;
    }
    return super.onOptionsItemSelected(item);
}


private void setData() {

    LineDataSet set1, set2;

    // create a dataset and give it a type
    //modifications with colour and stuf
    set1 = new LineDataSet(temperaturas, "temperatura");

    set1.setAxisDependency(YAxis.AxisDependency.LEFT);
    set1.setColor(ColorTemplate.getHoloBlue());
    set1.setCircleColor(Color.WHITE);
    set1.setLineWidth(2f);
    set1.setCircleRadius(2f);
    set1.setFillAlpha(65);
    set1.setFillColor(ColorTemplate.getHoloBlue());
    set1.setHighLightColor(Color.rgb(244, 117, 117));
    set1.setDrawCircleHole(false);


    //set1.setFillFormatter(new MyFillFormatter(0f));
    //set1.setDrawHorizontalHighlightIndicator(false);
    //set1.setVisible(false);
    //set1.setCircleHoleColor(Color.WHITE);

    // create a dataset and give it a type
    // similar above
    set2 = new LineDataSet(presiones, "presion");
    set2.setAxisDependency(YAxis.AxisDependency.RIGHT);
    set2.setColor(Color.RED);
    set2.setCircleColor(Color.WHITE);
    set2.setLineWidth(2f);
    set2.setCircleRadius(2f);
    set2.setFillAlpha(65);
    set2.setFillColor(Color.RED);
    set2.setDrawCircleHole(false);
    set2.setHighLightColor(Color.rgb(244, 117, 117));
    //set2.setFillFormatter(new MyFillFormatter(900f));


    mChart.getXAxis().setValueFormatter(new AxisValueFormatter() {
        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            return dates.get((int) value);
        }

        @Override
        public int getDecimalDigits() {
            return 0;
        }
    });

    ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
    dataSets.add(set1); // add the datasets
    dataSets.add(set2);


    // create a data object with the datasets
    LineData data = new LineData(dataSets);
    data.setValueTextColor(Color.BLACK);
    data.setValueTextSize(9f);

    // set data
    Log.i("Lists Sizedata", temperaturas.size() + " and " + presiones.size());
    mChart.setData(data);
    // move to the latest entry
    mChart.moveViewToX(data.getEntryCount());


}

@Override
public void onLoopjTaskCompletedBarometro(JSONObject parametrosdht11, int i) {
    String temperatura = null;
    String presion = null;
    String fecha = null;
    String Id = null;



    try {


        temperatura = parametrosdht11.getString("temperatura");
        presion = parametrosdht11.getString("presion");
        fecha = parametrosdht11.getString("Insertado_temp");
        Id = parametrosdht11.getString("Id_temp");




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


    temperaturas.add(new Entry(Float.valueOf(i), Float.valueOf(temperatura)));
    presiones.add(new Entry(Float.valueOf(i), Float.valueOf(presion)));
    dates.add(fecha); // reduce the string to just 12:13 etc





    //rrefresh we don't need to refresh since we are setting data after completing task
    mChart.notifyDataSetChanged();
    // mChart.setVisibleXRangeMaximum(12);

    //Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " + usuarioiJSONbject);
    Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " + "temperatura: " + temperatura + " presion: "
            + presion + " Fecha Inserción: " + fecha);

}



@Override
public void onLoopCompleteBarometro() {
    setData();
    // it takes time to recieve time. so we set the map after loop is complete okay?
    //mChart.setVisibleXRangeMaximum(5);
}
}

Any Help will be welcome.

Jaap
  • 81,064
  • 34
  • 182
  • 193
Oscar C.
  • 167
  • 1
  • 2
  • 12
  • 1
    Check if temperaturas already contains processing value before adding it, if (!temperaturas.contains... ) -> so you can add this item – lubilis Sep 08 '16 at 10:09
  • "temperaturas" is declared out of method, at the begining of class son have not initial value. " List temperaturas = new ArrayList<>();" So I think have no processing value., – Oscar C. Sep 08 '16 at 10:21
  • If you're not looping and temperaturas.size() will be at max == 1, where are the duplicates? are they in temperatura variable? (seems strange since you're getting single attribute value from one row in json) – lubilis Sep 08 '16 at 10:28
  • Data comes from Interface "(JSONObject parametrosdht11, int i)" because the data comes from a joining different Mysql tables in one, the interface receive some data duplicated. as I show in here the Json data. – Oscar C. Sep 08 '16 at 10:35
  • Then go for the Set. It will help you to remove duplicate. – Shadow Droid Sep 08 '16 at 10:48

3 Answers3

0

In order to eliminate duplicate entries in your list you need to add your data in SET not in a List or ArrayList. As Set did not allow to add duplicate entries. And this will also make your work easy. Also check out this link to get better idea about Set. What is the difference between Set and List?

Hope so, this might help!

Community
  • 1
  • 1
  • Sets not allows duplicated. but I have tow questions: – Oscar C. Sep 08 '16 at 11:03
  • If set receive a duplicated then send back and error or just overwrite? and what it is better to use in this case, HashSet or LinkedHashSet? – Oscar C. Sep 08 '16 at 11:07
  • In Set it will not overwrite the object it will reject the object if it come again because its the same object already added. For second question: for ordered list you should use LinkedHashSet. – Abdullah Mehmood Sep 08 '16 at 11:19
  • I would high appreciate if you could write exemple code based on my exemple in order to confirm correct answer so in this way others can learn from your solution. – Oscar C. Sep 08 '16 at 11:24
  • OK i will write but first i have some question. Why you using seperate List for temperaturas and dates. Why not we use one single object and set all data in it and then add this single object in List or Set? – Abdullah Mehmood Sep 08 '16 at 11:40
  • I was fighting with library mpandroidchart with variable X data on, in my case , and I tried to configurate the X Axis, the only way I got it was making it in this way since this is to be used in a Chart, this is because I need to first store data of JSON loop object to eliminate duplicates before sending it to add.(Entry..) which is the way MPAndroidchart . works.. In X is date and time when data was collected and Y is temperature. – Oscar C. Sep 08 '16 at 11:50
  • I have updated code with full code. In my updated code you can see that I am using three params, 1) temperature, other is pressure and third one is date since it is a doble linechart (x =date and Y = temperature and Pressure). In order to simplify I just wrote temperature and date. – Oscar C. Sep 08 '16 at 12:05
  • I have added my answer sorry for the late as i am busy in some other work. Please check and let me know :) – Abdullah Mehmood Sep 08 '16 at 13:26
  • The problem about this solution is that import com.github.mikephil.charting.data.Entry needed for chart works with java.util.list but LinkedHashSet need java.lang.Object. Then in the way you wrote, it is direct way, can not be implemented. – Oscar C. Sep 08 '16 at 13:57
0

To eliminate duplicate values i think you just do the following changes in your code:

    Set<Entry> presiones = new LinkedHashSet<>();
    Set<Entry> temperaturas = new LinkedHashSet<>();
    Set<String> dates = new LinkedHashSet<>();

Now you just add data in these objects and these will not allow to add duplicate values.

  • The problem about this solution is that import com.github.mikephil.charting.data.Entry needed for chart works with java.util.list but LinkedHashSet need java.lang.Object. Then in the way you wrote, it is direct way, can not be implemented. – Oscar C. Sep 08 '16 at 13:56
0

Here is the solution which finally works for me.

The initial problem comes because In server I JOINED 3 tables, so this created a duplicated data which will be sent to APP.

Because I am using MPAndroidChart, I need List<Entry> for each "Y" Axis to create a DataSet and List<String> for X Axis when you need an special format using method "setValueFormatter". These are special issues for MPAndroidChat.

Ok, from here I need to eliminate duplicates. So then I am going to declare a HashSet in onCreate:

"mediciones = new HashSet<>();"

This will be used to filter data using equals and HashCode which will be created on another class "Medicion"

public class Medicion {
private static final String TAG = "Medicion";

private String temperatura, presion, fecha, id;

public Medicion(String temperatura, String presion, String fecha, String id) {
    this.temperatura = temperatura;
    this.presion = presion;
    this.fecha = fecha;
    this.id = id;
}

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Medicion medicion = (Medicion) o;

    return id.equals(medicion.id);
}

@Override
public int hashCode() {
    int result = id.hashCode();

    return result;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getFecha() {
    return fecha;
}

public void setFecha(String fecha) {
    this.fecha = fecha;
}

public String getPresion() {
    return presion;
}

public void setPresion(String presion) {
    this.presion = presion;
}

public String getTemperatura() {
    return temperatura;
}

public void setTemperatura(String temperatura) {
    this.temperatura = temperatura;
}

}

Once we have it then we go back to the main Activity and we create an HashSet Object of "Medicion" and we pass the data filetered to the List

@Override
public void onLoopjTaskCompletedBarometro(ArrayList<JSONObject> arrayJSONObjects) {

    String temperatura = null;
    String presion = null;
    String fecha = null;
    String Id = null;
    String altitud = null;
    JSONObject date = null;

    int index = 0;

    for (JSONObject jsonObject : arrayJSONObjects) {

        try {
            Id = jsonObject.getString("Id_temp");
            temperatura = jsonObject.getString("temperatura");
            fecha = jsonObject.getString("Insertado_temp");
            presion = jsonObject.getString("presion");
            altitud = jsonObject.getString("altitud");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Medicion medicion =  new Medicion(temperatura, presion, fecha, Id);

        if (!mediciones.contains(medicion)) {
            mediciones.add(medicion);


        temperaturas.add(new Entry(Float.valueOf(index), Float.valueOf(medicion.getTemperatura())));
        presiones.add(new Entry(Float.valueOf(index), Float.valueOf(medicion.getPresion())));
        dates.add(fecha); // reduce the string to just 12:13 etc
        index++;
    }
    }

    for (Medicion temporaryMed : mediciones) {
        Log.i(UtilitiesGlobal.TAG, "onLoopjTaskCompletedBarometro: listado sin dobles "
                + temporaryMed.getId());
        Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj "
                + "temperatura: " + temporaryMed.getTemperatura()
                + " presion: " + temporaryMed.getPresion()
                + " Fecha Inserción: " + temporaryMed.getFecha());
    }

So finally we have the chart with non duplicated data on YAxis enter image description here

Oscar C.
  • 167
  • 1
  • 2
  • 12