-1

当我做第一条记录时,它通常发生在 ListNote 上,但是当我点击按钮保存第二条记录时,应用程序在出错后关闭(应用程序突然关闭)


public class ListNote extends Activity {

    DatabaseHelper dbhelper;
    SQLiteDatabase db;
    protected Cursor cursor;
    protected ListAdapter adapter;
    Moyenne moyenne;
    public static ListView liste;
    AddNote addNote;
    protected TextView mat;
    protected TextView coefi;
    protected TextView somCoefi;
    protected TextView somNote;
    protected TextView per;
    protected TextView datRecu;
    protected TextView datCompo;
    protected TextView notval;
    protected TextView typNot;
    protected TextView ansco;
    protected TextView moye;
    protected int matId;
    protected int perId;
    protected int anId;
    protected String matMat;
    protected String perPer;
    protected String anAn;

    ArrayList<String> listNotCoef;
    ArrayList<Double> listCoef;
    Double somCoef = 0.0;
    Double somNot = 0.0;
    Double moyNot = 0.0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.note_liste);
        setTitle(R.string.note_title);
        Log.i("Listnote oncreat", "OK 1");
        // --------------- note_moy_item-----------------
        moye = (TextView) findViewById(R.id.note_moy_item);
        somNote = (TextView) findViewById(R.id.som_note_item);
        mat = (TextView) findViewById(R.id.note_mat_item);
        somCoefi = (TextView) findViewById(R.id.som_coef_item);
        per = (TextView) findViewById(R.id.note_per_item);
        ansco = (TextView) findViewById(R.id.note_ansco_item);
        // --------------- note_list_item-----------------
        liste = (ListView) findViewById(R.id.listnote);
        datRecu = (TextView) findViewById(R.id.note_recu_item);
        datCompo = (TextView) findViewById(R.id.note_compo_item);
        typNot = (TextView) findViewById(R.id.note_type_item);
        notval = (TextView) findViewById(R.id.note_val_item);
        coefi = (TextView) findViewById(R.id.note_coef_item);
        Log.i("Listnote oncreat", "OK 8");
        // ------------------ affichage Matiere periode et année scolaire
        // -------------------------
        // ------------------ recuperation des données venant de l'activity
        // précedente --------------------------
        matId = getIntent().getIntExtra("MATIERE_ID", 0);
        Bundle extra = getIntent().getExtras();
        matMat = extra.getString("MATIERE_MAT");

        anId = getIntent().getIntExtra("ANSCO_ID", 0);
        Bundle extra1 = getIntent().getExtras();
        anAn = extra1.getString("ANSCO_AN");

        perId = getIntent().getIntExtra("PERIODE_ID", 0);
        Bundle extra2 = getIntent().getExtras();
        perPer = extra2.getString("PERIODE_PER");
        Log.i("Listnote oncreat", "OK 9");
        mat.setText(" " + matMat);
        per.setText(" " + perPer);
        ansco.setText(anAn);
        Log.i("Listnote oncreat", "Mat: " + matMat + " Periode: " + perPer);

        // Gestion des moy, som not som coef
        somCoef = 0.0;
        somNot = 0.0;
        moyNot = 0.0;
        sommeNote();
        sommeCoef();
        CalcMoyenne();
        somNote.setText("" + roundTwoDecimals(somNot));
        somCoefi.setText("" + somCoef);
        moye.setText("" + roundTwoDecimals(moyNot));
        LoadListNote();

        liste.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {

                try {
                    Intent intent = new Intent(getApplicationContext(),
                            ModifNote.class);

                    SQLiteCursor cr = (SQLiteCursor) parent
                            .getItemAtPosition(position);
                    String typnot = cr.getString(cr
                            .getColumnIndex(DatabaseHelper.TYPENOTE));
                    Double valnot = cr.getDouble(cr
                            .getColumnIndex(DatabaseHelper.VALNOTE));
                    Double coefnot = cr.getDouble(cr
                            .getColumnIndex(DatabaseHelper.COEFNOTE));
                    String datR = cr.getString(cr
                            .getColumnIndex(DatabaseHelper.DATERECU));
                    String dateC = cr.getString(cr
                            .getColumnIndex(DatabaseHelper.DATECOMPO));
                    Note not = new Note(typnot, valnot, coefnot, datR, dateC,
                            matId, perId, anId);
                    not.setIdNote((int) id);
                    Log.i("Listnote onclic", "OK 1");

                    intent.putExtra("PERIODE_ID", perId);
                    intent.putExtra("PERIODE_PER", perPer);
                    intent.putExtra("ANSCO_ID", anId);
                    intent.putExtra("ANSCO_AN", anAn);
                    intent.putExtra("MATIERE_ID", matId);
                    intent.putExtra("MATIERE_MAT", matMat);

                    intent.putExtra("NOTE_ID", not.getIdNote());
                    intent.putExtra("NOTE_TYPE", typnot);
                    intent.putExtra("NOTE_VAL", valnot);
                    intent.putExtra("NOTE_COEF", coefnot);
                    intent.putExtra("NOTE_RECU", datR);
                    intent.putExtra("NOTE_COMPO", dateC);
                    cr.close();
                    startActivity(intent);
                    finish();
                } catch (Exception ex) {
                    Alerts.CatchError(ListNote.this, ex.toString());
                }
                //
            }

        });

    }

    @Override
    // Création du menu principal
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_list, menu);
        return true;
    }

    @Override
    // Selection d'un item du menu
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.moyenne_menu_add:
            Intent intent = new Intent(getApplicationContext(), AddNote.class);
            intent.putExtra("PERIODE_ID", perId);
            intent.putExtra("PERIODE_PER", perPer);
            intent.putExtra("ANSCO_ID", anId);
            intent.putExtra("ANSCO_AN", anAn);
            intent.putExtra("MATIERE_ID", matId);
            intent.putExtra("MATIERE_MAT", matMat);
            startActivity(intent);
            finish();
            break;
        case R.id.moyenne_menu_sup:
            // databaseHelper.Truncate();
            // DataBind();
            break;
        }
        return true;
    }

    public void LoadListNote() {
        dbhelper = new DatabaseHelper(this);
        db = dbhelper.getWritableDatabase();
        boolean ok = true;
        try {
            cursor = db.rawQuery("Select " + DatabaseHelper.IDNOTE
                    + " as _id , " + DatabaseHelper.VALNOTE + ", "
                    + DatabaseHelper.TYPENOTE + ", " + DatabaseHelper.COEFNOTE
                    + ", " + DatabaseHelper.DATERECU + ", "
                    + DatabaseHelper.DATECOMPO + " from "
                    + DatabaseHelper.TABLE_NOTE + " where "
                    + DatabaseHelper.NOTEIDAN + " = ? and "
                    + DatabaseHelper.NOTEIDPER + " = ? and "
                    + DatabaseHelper.NOTEIDMAT + " = ? order by _id",
                    new String[] { "" + anId, "" + perId, "" + matId });
            startManagingCursor(cursor);
            String[] from = new String[] { DatabaseHelper.VALNOTE,
                    DatabaseHelper.TYPENOTE, DatabaseHelper.COEFNOTE,
                    DatabaseHelper.DATERECU, DatabaseHelper.DATECOMPO };
            int[] to = new int[] { R.id.note_val_item, R.id.note_type_item,
                    R.id.note_coef_item, R.id.note_recu_item,
                    R.id.note_compo_item };
            Log.i("LISTNote 2", "OK");
            SimpleCursorAdapter sca = new SimpleCursorAdapter(this,
                    R.layout.note_list_item, cursor, from, to);

            liste.setAdapter(sca);
            Log.i("LISTNote 3", "OK");

        } catch (Exception ex) {
            ok = false;
            AlertDialog.Builder b = new AlertDialog.Builder(this);
            b.setMessage(ex.toString());
            b.show();
        } finally {
            if (ok) {

                // cursor.close();
                db.close();
                dbhelper.close();
            }
        }

    }

    public double getNumber(String s) {
        double n = Double.parseDouble(s);
        return n;
    }

    private void sommeNote() {
        boolean ok = true;
        dbhelper = new DatabaseHelper(getApplicationContext());
        try {
            Log.i("sommeNote 1", "OK");
            listNotCoef = dbhelper.getAllNote(anId, perId, matId);
            Log.i("sommeNote 2", "OK");
            // int nbNot = db.getNoteByMatCount();
            somNot = 0.0;
            Double notM = 0.0;
            Double coefN = 0.0;
            Log.i("sommeNote 3", "OK");
            Double mulNotCoef = 0.0;

            for (int i = 0; i < listNotCoef.size(); i++) {
                String value = listNotCoef.get(i);
                int index = value.indexOf("|");
                notM = Double.valueOf(value.substring(0, index));
                coefN = Double.valueOf(value.substring(index + 1));
                mulNotCoef = notM * coefN;
                Log.i("sommeNote ", "Note: " + notM + " Coef: " + coefN);
                somNot = somNot + mulNotCoef;
                Log.i("sommeNote pour", "Som Note: " + somNot);
            }
            Log.i("sommeNote 4", "Som Note: " + somNot);
            // somNote.setText(String.valueOf(somNot));
            // somNote.setText("" + roundTwoDecimals(somNot));

        } catch (Exception ex) {
            ok = false;
            AlertDialog.Builder b = new AlertDialog.Builder(this);
            b.setMessage(ex.toString());
            b.show();
        } finally {
            if (ok) {

                // cursor.close();
                dbhelper.close();
            }
        }

    }

    private void sommeCoef() {
        boolean ok = true;
        dbhelper = new DatabaseHelper(getApplicationContext());
        try {
            Log.i("sommeCoef 1", "OK");
            listCoef = dbhelper.getAllCoef(anId, perId, matId);
            Log.i("sommeCoef 2", "OK");
            // int nbNot = db.getNoteByMatCount();
            somCoef = 0.0;
            Double notM = 0.0;
            Log.i("sommeCoef 3", "OK");
            for (int i = 0; i < listCoef.size(); i++) {
                notM = listCoef.get(i);
                somCoef = somCoef + notM;
                Log.i("sommeCoef 4", "Som Coef: " + somCoef);
            }
            Log.i("sommeCoef 5", "Som Coef: " + somCoef);
            // somNote.setText(String.valueOf(somNot));
            // somCoefi.setText("" + somCoef);

        } catch (Exception ex) {
            ok = false;
            AlertDialog.Builder b = new AlertDialog.Builder(this);
            b.setMessage(ex.toString());
            b.show();
        } finally {
            if (ok) {

                // cursor.close();
                dbhelper.close();
            }
        }

    }

    private void CalcMoyenne() {
        try {
            if (somCoef > 0) {
                moyNot = somNot / somCoef;
            } else if (somCoef == 0) {
                moyNot = 0.0;
            }

        } catch (Exception ex) {
            AlertDialog.Builder b = new AlertDialog.Builder(this);
            b.setMessage(ex.toString());
            b.show();
        }

    }

    double roundTwoDecimals(double d) {
        DecimalFormat twoDForm = new DecimalFormat("#.##");
        return Double.valueOf(twoDForm.format(d));
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(getApplicationContext(),
                    ListMatiere.class);
            intent.putExtra("PERIODE_ID", perId);
            intent.putExtra("PERIODE_PER", perPer);
            intent.putExtra("ANSCO_ID", anId);
            intent.putExtra("ANSCO_AN", anAn);
            startActivity(intent);
            finish();
        }
        return false;

    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        liste.setAdapter(null);
        db.close();
        dbhelper.close();
        cursor.close();
        super.onPause();
    }

    @Override
    protected void onStop() {
        liste.setAdapter(null);
        db.close();
        dbhelper.close();
        cursor.close();
        super.onStop();
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        LoadListNote();
        super.onStart();
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        LoadListNote();
        super.onResume();

    }

    @Override
    protected void onDestroy() {
        liste.setAdapter(null);
        db.close();
        dbhelper.close();
        cursor.close();
        super.onDestroy();
    }
}

我的数据库助手的一部分

// --------------------NOTES---------------------------
    //Store Notes
    public void insererNote(String typeNote, Double valNote, Double coefNote,
            String dateRecu, String dateCompo, int idMat, int idPer, int idAnsco) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(VALNOTE, valNote);
        values.put(TYPENOTE, typeNote);
        values.put(COEFNOTE, coefNote);
        values.put(DATERECU, dateRecu);
        values.put(DATECOMPO, dateCompo);
        values.put(NOTEIDMAT, idMat);
        values.put(NOTEIDPER, idPer);
        values.put(NOTEIDAN, idAnsco);
        db.insert(TABLE_NOTE, VALNOTE, values);
        Log.i("insererNote ", "OK");
        db.close();
    }

//Get notes

    public Cursor getNoteByMat(int idan, int idper, int idmat) {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cur = db.rawQuery("Select " + IDNOTE + " as _id , " + VALNOTE
                + ", " + TYPENOTE + ", " + COEFNOTE + ", " + DATERECU + ", "
                + DATECOMPO + " from " + TABLE_NOTE + " where " + NOTEIDAN
                + " = ? and " + NOTEIDPER + " = ? and " + NOTEIDMAT
                + " = ? order by _id", new String[] { String.valueOf(idan), String.valueOf(idper),
                String.valueOf(idmat) });

        // Cursor cur= db.rawQuery("SELECT * FROM "+TABLE_NOTE,null);

        return cur;
    }

//      get the mark with it coefficient for calculation

    public ArrayList<String> getAllNote(int idan, int idper, int idmat) {
        ArrayList<String> notes = new ArrayList<String>();
        Log.i("GetAllNote 1 ", "OK");
        // Select All Query
        String selectQuery = "Select " + VALNOTE + ", "+ COEFNOTE +" from " + TABLE_NOTE
                + " where " + NOTEIDAN + " = ? and " + NOTEIDPER + " = ? and "
                + NOTEIDMAT + " = ?";
        Log.i("GetAllNote 2 ", "ids"+idan+idper+idmat);
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, new String[] { String.valueOf(idan),
                String.valueOf(idper), String.valueOf(idmat) });

        Log.i("GetAllNote 3 ", "OK");
        // looping through all rows and adding to list

        while (cursor.moveToNext()) {
            notes.add(cursor.getString(0) +"|"+ cursor.getString(1));
        }

        Log.i("GetAllNote 4 ", "OK");
        // closing connection
        cursor.close();
        db.close();
        Log.i("GetAllNote 5 ", "OK");
        // returning lables
        return notes;
    }

//   get list of coef to sum 
    public ArrayList<Double> getAllCoef(int idan, int idper, int idmat) {
        ArrayList<Double> coef = new ArrayList<Double>();
        Log.i("GetAllCoef 1 ", "OK");
        // Select All Query
        String selectQuery = "Select " + COEFNOTE + " from " + TABLE_NOTE
                + " where " + NOTEIDAN + " = ? and " + NOTEIDPER + " = ? and "
                + NOTEIDMAT + " = ?";
        Log.i("GetAllCoef 2 ", "ids" + idan + idper + idmat);
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, new String[] { "" + idan,
                "" + idper, "" + idmat });

        Log.i("GetAllCoef 3 ", "OK");
        // looping through all rows and adding to list
//      cursor.moveToFirst();
        while (cursor.moveToNext()) {
            coef.add(Double.valueOf(cursor.getString(0)));
        }

        Log.i("GetAllCoef 4 ", "OK");
//      // closing connection
//      if (cursor!=null){
            cursor.close();
//           }
//          if (db!=null){
                db.close();
//            }


        // returning notes
        return coef;
    }

    public int getNoteByMatCount() {
        String countQuery = "SELECT  * FROM " + TABLE_NOTE;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        int rowCount = cursor.getCount();
        db.close();
        cursor.close();

        // return row count
        return rowCount;
    }

    public int UpdateNote(Note not) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(VALNOTE, not.getValNote());
        cv.put(TYPENOTE, not.getTypeNote());
        cv.put(COEFNOTE, not.getCoefNote());
        cv.put(DATERECU, not.getDateRecu());
        cv.put(DATECOMPO, not.getDateCompo());
        return db.update(TABLE_NOTE, cv, IDNOTE + "=?",
                new String[] { String.valueOf(not.getIdNote()) });
    }

    public void DeleteNote(Note not) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_NOTE, IDNOTE + "=?",
                new String[] { String.valueOf(not.getIdNote()) });
        db.close();

    }

在设备上调试后 Logcat 出现异常

 10-20 17:28:07.710: E/AndroidRuntime(18635): FATAL EXCEPTION: main
    10-20 17:28:07.710: E/AndroidRuntime(18635): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.activity/com.android.moyenne.note.ListNote}: java.lang.NumberFormatException
    10-20 17:28:07.710: E/AndroidRuntime(18635):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
    10-20 17:28:07.710: E/AndroidRuntime(18635):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
    10-20 17:28:07.710: E/AndroidRuntime(18635):    at android.app.ActivityThread.access$1500(ActivityThread.java:117)
    10-20 17:28:07.710: E/AndroidRuntime(18635):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
    10-20 17:28:07.710: E/AndroidRuntime(18635):    at android.os.Handler.dispatchMessage(Handler.java:99)
    10-20 17:28:07.710: E/AndroidRuntime(18635):    at android.os.Looper.loop(Looper.java:130)
    10-20 17:28:07.710: E/AndroidRuntime(18635):    at android.app.ActivityThread.main(ActivityThread.java:3687)
    10-20 17:28:07.710: E/AndroidRuntime(18635):    at java.lang.reflect.Method.invokeNative(Native Method)
    10-20 17:28:07.710: E/AndroidRuntime(18635):    at java.lang.reflect.Method.invoke(Method.java:507)
    10-20 17:28:07.710: E/AndroidRuntime(18635):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
    10-20 17:28:07.710: E/AndroidRuntime(18635):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
    10-20 17:28:07.710: E/AndroidRuntime(18635):    at dalvik.system.NativeStart.main(Native Method)
    10-20 17:28:07.710: E/AndroidRuntime(18635): Caused by: java.lang.NumberFormatException
    10-20 17:28:07.710: E/AndroidRuntime(18635):    at org.apache.harmony.luni.util.FloatingPointParser.parseDblImpl(Native Method)
    10-20 17:28:07.710: E/AndroidRuntime(18635):    at org.apache.harmony.luni.util.FloatingPointParser.parseDouble(FloatingPointParser.java:283)
    10-20 17:28:07.710: E/AndroidRuntime(18635):    at java.lang.Double.parseDouble(Double.java:318)
    10-20 17:28:07.710: E/AndroidRuntime(18635):    at java.lang.Double.valueOf(Double.java:356)
    10-20 17:28:07.710: E/AndroidRuntime(18635):    at com.android.moyenne.note.ListNote.roundTwoDecimals(ListNote.java:349)
    10-20 17:28:07.710: E/AndroidRuntime(18635):    at com.android.moyenne.note.ListNote.onCreate(ListNote.java:114)
    10-20 17:28:07.710: E/AndroidRuntime(18635):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
    10-20 17:28:07.710: E/AndroidRuntime(18635):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
    10-20 17:28:07.710: E/AndroidRuntime(18635):    ... 11 more
4

2 回答 2

1

正如您从异常堆栈跟踪中看到的那样,您在此处收到错误:

double roundTwoDecimals(double d) {
    DecimalFormat twoDForm = new DecimalFormat("#.##");
    return Double.valueOf(twoDForm.format(d));
}

这可能是因为 twoDForm.format(d) 返回类似 12,345.67 的内容,由于逗号分隔数千,因此无法解析。

您应该使用 Math.round(d*100)/100.0 进行舍入。

于 2013-10-20T18:06:33.387 回答
0

非常感谢#Ratzor,我使用 Math.round(d*100)/100.0 进行舍入,我的应用程序在设备上运行良好

double roundTwoDecimals(double d) {
        Double twoDForm = Math.round(d*100)/100.0;
        return Double.valueOf(twoDForm);
    }
于 2013-10-20T19:02:39.087 回答