0

les comento que vengo realizando un proyecto a partir de una tabbed activity, y que cada pestaña esta basado en un fragment, en una de las pestañas estoy mostrando tres diferentes graficas usando la libreria MPAndroidChart. Lo que hago es recibir datos por bluetooth con mi actividad principal y graficar estos datos en tiempo real llamando un metodo que se encuentra en uno de los fragments. El problema que tengo es que me sale un error a la hora de ejecutar la aplicacion respecto al usar el metodo del fragment, pienso que es incorrecta la manera de llamar este metodo del fragment desde mi actividad principal. Les dejo una parte del codigo de mi actividad principal y asi tambien del fragment, ademas del error que me surge. Este es el codigo donde realizo la llamada al metodo desde mi actividad principal.

private void beginListenForData() {
    final byte delimiter = 10; //This is the ASCII code for a newline character
    stopWorker = false;
    readBufferPosition = 0;
    readBuffer = new byte[1024];
    workerThread = new Thread(new Runnable() {
        public void run() {
            while(!Thread.currentThread().isInterrupted() && !stopWorker) {
                try {
                    int bytesAvailable = mmInputStream.available();
                    if(bytesAvailable > 0) {
                        byte[] packetBytes = new byte[bytesAvailable];
                        mmInputStream.read(packetBytes);
                        for(int i=0;i<bytesAvailable;i++) {
                            byte b = packetBytes[i];
                            if(b == delimiter) {
                                byte[] encodedBytes = new byte[readBufferPosition];
                                System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                                final String data = new String(encodedBytes, "US-ASCII");
                                readBufferPosition = 0;
                                mViewPager.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        if(firstData){                                     
                                            firstData = false;
                                        }else {
                                            String aux="";
                                            char [] dataArray = data.toCharArray();
                                            if(dataArray[0]=='*'){
                                                for(int i=1;i<dataArray.length;i++){
                                                    if(dataArray[i]=='*'){
                                                        ConnectionSQLiteHelper connPeakDate = new ConnectionSQLiteHelper( getApplicationContext(), "db_batmon", null, 1 );
                                                        SQLiteDatabase dbPeakDate = connPeakDate.getWritableDatabase();
                                                        ContentValues datePeak = new ContentValues();
                                                        datePeak.put(Utilities.PEAK_DATE,aux);
                                                        long res =dbPeakDate.insert(Utilities.TABLE_PEAK_DATE,Utilities.ID_PEAK_DATE,datePeak);
                                                        Toast.makeText(getApplicationContext(),"Peak Event: "+res+" date: "+aux, Toast.LENGTH_LONG).show();
                                                        dbPeakDate.close();
                                                        connPeakDate.close();
                                                    }else{
                                                        aux += dataArray[i];
                                                    }
                                                }
                                            }else {
                                                if (dataArray[0]=='#') {
                                                    Toast.makeText(getApplicationContext(),"The SD memory has been cleaned", Toast.LENGTH_LONG).show();
                                                }else{
                                                    long systemTime = System.currentTimeMillis();
                                                    int pointer = 0;
                                                    int pointData = 0;
                                                    while (pointer < dataArray.length) {
                                                        if (dataArray[pointer] == ';' && pointData < inputData.length) {
                                                            inputData[pointData] = Float.valueOf( aux );
                                                            pointer++;
                                                            pointData++;
                                                            aux = "";
                                                        } else {
                                                            aux += dataArray[pointer];
                                                            pointer++;
                                                        }
                                                    }
                                                    ConnectionSQLiteHelper connHistory = new ConnectionSQLiteHelper( getApplicationContext(), "db_batmon", null, 1 );
                                                    SQLiteDatabase dbHistory = connHistory.getWritableDatabase();
                                                    ContentValues valHistory = new ContentValues();
                                                    valHistory.put( Utilities.DATE_TIME,systemTime );
                                                    valHistory.put( Utilities.VOLTAGE_BATTERY, inputData[0] );
                                                    valHistory.put( Utilities.CURRENT_BATTERY, inputData[1] );
                                                    float power = Math.round((inputData[0]*inputData[1]*100.0)/100.0);
                                                    valHistory.put(Utilities.POWER_BATTERY,power);
                                                    valHistory.put( Utilities.CURRENT_GENERATOR, inputData[2] );
                                                    valHistory.put( Utilities.CURRENT_AC, inputData[3] );
                                                    valHistory.put( Utilities.CURRENT_LIGHTS, inputData[4] );
                                                    valHistory.put( Utilities.TEMP_BATTERY, inputData[5] );
                                                    valHistory.put( Utilities.TEMP_GENERATOR, inputData[6] );
                                                    valHistory.put( Utilities.TEMP_STARTER, inputData[7] );
                                                    valHistory.put( Utilities.TEMP_PCB, inputData[8] );
                                                    dbHistory.insert( Utilities.TABLE_HISTORY, Utilities.ID_HISTORY, valHistory );
                                                    dbHistory.close();
                                                    connHistory.close();
                                                    ChartsFragment.updateFragmentChart(inputData[0],inputData[1]);//,power );
                                                }
                                            }
                                        }
                                    }
                                });
                            } else {
                                readBuffer[readBufferPosition++] = b;
                            }
                        }
                    }
                }
                catch (IOException ex) {
                    stopWorker = true;
                }
            }
        }
    });
    workerThread.start();
}

Este el metodo del fragment

public static void updateFragmentChart(float voltage,float current,float power) {
    voltageData = voltageChart.getData();
    if (voltageData != null) {
        ILineDataSet voltageSet = voltageData.getDataSetByIndex( 0 );
        if (voltageSet == null) {
            voltageSet = createVoltageSet();
            voltageData.addDataSet( voltageSet );
        }

        voltageData.addEntry( new Entry( voltageSet.getEntryCount(), voltage ), 0 );
        voltageData.notifyDataChanged();
        voltageChart.notifyDataSetChanged();
        voltageChart.setVisibleXRangeMaximum( 100 );
        voltageChart.moveViewToX( voltageData.getEntryCount() );
    }
    currentData = currentChart.getData();
    if (currentData != null) {
        ILineDataSet currentSet = currentData.getDataSetByIndex( 0 );
        if (currentSet == null) {
            currentSet = createCurrentSet();
            currentData.addDataSet( currentSet );
        }
        currentData.addEntry( new Entry( currentSet.getEntryCount(), current ), 0 );
        currentData.notifyDataChanged();
        currentChart.notifyDataSetChanged();
        currentChart.setVisibleXRangeMaximum( 100 );
        currentChart.moveViewToX( currentData.getEntryCount() );
    }
    powerData = powerChart.getData();
    if (powerData != null) {
        ILineDataSet powerSet = powerData.getDataSetByIndex( 0 );
        if (powerSet == null) {
            powerSet = createPowerSet();
            powerData.addDataSet( powerSet );
        }
        powerData.addEntry( new Entry( powerSet.getEntryCount(), power ), 0 );
        powerData.notifyDataChanged();
        powerChart.notifyDataSetChanged();
        powerChart.setVisibleXRangeMaximum( 100 );
        powerChart.moveViewToX( powerData.getEntryCount() );
    }
}

Este es error que me sale.

02-08 09:38:16.586 15224-15224/com.example.avendano.batmon E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.avendano.batmon, PID: 15224 java.lang.NullPointerException: Attempt to invoke virtual method 'com.github.mikephil.charting.data.ChartData com.github.mikephil.charting.charts.LineChart.getData()' on a null object reference at com.example.avendano.batmon.ChartsFragment.updateFragmentChart(ChartsFragment.java:310) at com.example.avendano.batmon.BatMon$1$1.run(BatMon.java:245) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:145) at android.app.ActivityThread.main(ActivityThread.java:6934) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 02-08 09:38:22.712 15224-15235/com.example.avendano.batmon W/SQLiteConnectionPool: A SQLiteConnection object for database '+data+data+com_example_avendano_batmon+databases+db_batmon' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed. 02-08 09:38:26.967 15224-15224/com.example.avendano.batmon I/Process: Sending signal. PID: 15224 SIG: 9

Alguien que me pueda ayudar con este problema por favor. Gracias de antemano

1 respuesta 1

0

Entre tanta vuelta que le di a mi codigo, el problema fue que en el metodo updateFragmentChart(), la asignacion a partir de getData() en voltageData, currentData y powerData generaban un valor nulo. Es asi que quitanto estas lineas he obtenido el resultado deseado, quedando el codigo de la siguiente manera:

public static void updateFragmentChart(float voltage,float current,float power) {
if (voltageData != null) {
    ILineDataSet voltageSet = voltageData.getDataSetByIndex( 0 );
    if (voltageSet == null) {
        voltageSet = createVoltageSet();
        voltageData.addDataSet( voltageSet );
    }

    voltageData.addEntry( new Entry( voltageSet.getEntryCount(), voltage ), 0 );
    voltageData.notifyDataChanged();
    voltageChart.notifyDataSetChanged();
    voltageChart.setVisibleXRangeMaximum( 100 );
    voltageChart.moveViewToX( voltageData.getEntryCount() );
}
if (currentData != null) {
    ILineDataSet currentSet = currentData.getDataSetByIndex( 0 );
    if (currentSet == null) {
        currentSet = createCurrentSet();
        currentData.addDataSet( currentSet );
    }
    currentData.addEntry( new Entry( currentSet.getEntryCount(), current ), 0 );
    currentData.notifyDataChanged();
    currentChart.notifyDataSetChanged();
    currentChart.setVisibleXRangeMaximum( 100 );
    currentChart.moveViewToX( currentData.getEntryCount() );
}
if (powerData != null) {
    ILineDataSet powerSet = powerData.getDataSetByIndex( 0 );
    if (powerSet == null) {
        powerSet = createPowerSet();
        powerData.addDataSet( powerSet );
    }
    powerData.addEntry( new Entry( powerSet.getEntryCount(), power ), 0 );
    powerData.notifyDataChanged();
    powerChart.notifyDataSetChanged();
    powerChart.setVisibleXRangeMaximum( 100 );
    powerChart.moveViewToX( powerData.getEntryCount() );
}

}

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.