Android sqlite testinsert - >错误“列不是唯一的”

时间:2014-01-16 23:29:46

标签: android sql sqlite

我想测试活动中的插入和删除功能。 插入工作(testdata在表中),但抛出异常删除函数不起作用。 所以测试没有通过。 我在Logcat中有“列不唯一”错误,如果我在insert()上设置断点 - TestActivity和debug的功能,“评估期间的错误”和“assertNotNull无法解析”的出现者。 我正在使用Activity(SourceActivity),TestActivity(SourceActivityTest)和Helper(RegisterHelper)。 SourceActivity:

    public class SourceActivity extends Activity {
    private String sortRuleGerman="< a,A < b,B < c,C < d,D < e,E < f,F < g,G < h,H < i,I"
            +"< j,J < k,K < l,L < m,M < n,N < o,O < p,P < q,Q < r,R"
            +"< s,S < t,T < u,U < v,V < w,W < x,X < y,Y < z,Z";
    private String returnSourceIdentifier="testReturnValue";
    private RegisterHelper helper;
    private SQLiteDatabase registerDB;

    public SQLiteDatabase getRegisterDB(){ return registerDB; }
    private static final String TAG = SourceActivity.class.getSimpleName();

    private AutoCompleteTextView autocompleteTvIdentifiers;
    private ArrayAdapter<String> adapter;
    private TextView tv_autoren;
    private TextView tv_titelquelle;
    private TextView tv_herkunft;
    private TextView tv_pubdat;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_source);

        if(helper == null)
            helper = new RegisterHelper(this);



        Button btReturn = (Button) this.findViewById(R.id.bt_quellezurueck);
        btReturn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
//              
                // identifier auch für Callback speichern!
                returnSourceIdentifier = autocompleteTvIdentifiers.getText().toString();
                //insert ausführen
                SourceActivity.this.insert(
                        returnSourceIdentifier,
                        tv_autoren.getText().toString(),
                        tv_titelquelle.getText().toString(),
                        tv_herkunft.getText().toString(),
                        tv_pubdat.getText().toString());
                SourceActivity.this.callback();
                SourceActivity.this.finish();
            }
        });
        tv_autoren= (TextView) this.findViewById(R.id.tv_autoren);
        tv_titelquelle = (TextView) this.findViewById(R.id.tv_titelquelle);
        tv_herkunft = (TextView) this.findViewById(R.id.tv_herkunft);
        tv_pubdat = (TextView) this.findViewById(R.id.tv_pubdat);



        autocompleteTvIdentifiers = (AutoCompleteTextView) this.findViewById(R.id.autocomplete_identifier);

        //adapter = new ArrayAdapter<String>(this, R.layout.list_item, sourceIdentifiers);
        //this.sortArrayAdapter();

        autocompleteTvIdentifiers.setAdapter(adapter);
        initializeAdapterFromDB();

}
    private void sortArrayAdapter() {
        try {
            adapter.sort(new RuleBasedCollator(sortRuleGerman));
        } catch (ParseException pe){
            Log.e(TAG,"AdapterArray sortieren-"+ pe.toString());

        }
    }

    private void initializeAdapterFromDB(){
        String selectSQL ="SELECT shortdesc " + "FROM Sources ORDER BY shortdesc";
        //Datenbank öffnen:
        registerDB = helper.getReadableDatabase();
        try{
            Cursor cursor = registerDB.rawQuery(selectSQL,null);
            //die neue Liste aus der Datenbank:
            String[] identifiers = new String[cursor.getCount()];
            int index = 0;
            while(cursor.moveToNext()){
                String temp = cursor.getString(0);
                identifiers[index] = temp;
                Log.d(TAG, "Stichwort" + index + "; \"" + temp + "\"");
                index++;
            }
            cursor.close();
            //Adapter aus DB initialisieren:
            adapter = new ArrayAdapter<String> (this, R.layout.list_item);
        }
        catch (Exception e){
            Log.e(TAG, "Fehler beim Lesen der Kurzbezeichner. " + e.toString());
        }finally {
            //Datenbank wieder schliessen:
            registerDB.close();
        }
    }



    public boolean insert(String identifier, String authors, String titel, String publisher, String text){
        String insertSQL="INSERT INTO Sources VALUES('" + identifier +"', '" + authors + "', '" + titel +"', '" +publisher +"','" + text + "');";
        //Datenbank beschaffen
        registerDB = helper.getWritableDatabase();
        try{
            registerDB.execSQL(insertSQL);
            adapter.add(returnSourceIdentifier);
            this.sortArrayAdapter();
            Log.d(TAG, "Quelle zu \"" + returnSourceIdentifier + "\" in DB gespeichert");
            return true;
        } catch(Exception e) {
            Log.e(TAG, "Fehler beim Speichern einer " + "Literaturquelle. " + e.toString());
        } finally {
            // ... und wieder schließen:
            registerDB.close();
        }
        return false;
    }

    private void callback(){
        Intent pushIntent = this.getIntent();
        Bundle intentBundle = pushIntent.getExtras();
        if(intentBundle == null)
            Log.d(TAG,"Keine Extras im Push-Intent");
        else{
            String intentParam = intentBundle.getString(KeywordActivity.SOURCE_IDENTIFIER);
        if(intentParam  == null)
            Log.d(TAG,"No Key=\"" + KeywordActivity.SOURCE_IDENTIFIER + "\" in intentBundle");
        else
            Log.d(TAG,"Key=\"" + KeywordActivity.SOURCE_IDENTIFIER + "\" /value=\"" + intentParam + "\" received.");
        }
        pushIntent.putExtra(KeywordActivity.SOURCE_IDENTIFIER, returnSourceIdentifier);
        this.setResult(Activity.RESULT_OK, pushIntent);
        Log.d(TAG,"SourceIdentifier\"" + returnSourceIdentifier + "\" returned.");


    public boolean delete(String whereCondition){
        String deleteSQL;
        if (whereCondition == null)
            deleteSQL="DELETE FROM Sources";
        else deleteSQL="DELETE FROM Sources WHERE"+ whereCondition;
        try {
            registerDB.execSQL(deleteSQL);
            return true;
        }catch (Exception e){
            Log.e(TAG, e.toString());
            return false;
        }
    }
    @Override
    protected void onStop(){
        super.onStop();
        registerDB.close();
    }


}

SourceActivityTest:

public class SourceActivityTest extends
            ActivityInstrumentationTestCase2<SourceActivity> {
                private SourceActivity activity;
                private String[] testData ={"tword1","tword2","ttitel1","tword3","tDate"};

                public SourceActivityTest(){
                    super(SourceActivity.class);
                }

                @Override
                protected void setUp() throws Exception{
                super.setUp();
                activity=this.getActivity();
                }

                public void testPreconditions(){
                    assertNotNull(activity.getRegisterDB());

                }
                public void testInsert(){
                    assertTrue(activity.insert (testData[0], testData[1], testData[2], testData[3], testData[4])); 
                    assertTrue(activity.delete (" shortdesc='" + testData[0] + "'")); 
                }


}

RegisterHelper:

public class RegisterHelper extends SQLiteOpenHelper {

    private static final String DB_NAME = "Register";
    private static final int DB_VERSION = 1;
    private static final String TAG = RegisterHelper.class.getSimpleName();
    private final String CREATE_SOURCES = "CREATE TABLE Sources  ( shortdesc TEXT PRIMARY KEY , autoren TEXT NOT NULL , titel TEXT NOT NULL , verlag_ort_url TEXT NOT NULL , publikationsdatum TEXT );";
    private final String CREATE_TIPWORDS = "CREATE TABLE Tipwords ( _id INTEGER PRIMARY KEY , stichwort TEXT NOT NULL , quelle TEXT NOT NULL , fundstelle TEXT NOT NULL , text TEXT NOT NULL , CONSTRAINT QuellFK FOREIGN KEY (quelle) REFERENCES Quellen(kurzbezeichnung) ON DELETE RESTRICT ON UPDATE CASCADE );";

    public RegisterHelper(Context context){
    super(context, DB_NAME, null, DB_VERSION);  
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try{
            db.execSQL(CREATE_SOURCES);
            db.execSQL(CREATE_TIPWORDS);
        } catch(SQLException sqle){
            // android.database.SQLException importieren!
        Log.d(TAG, "DB erzeugt in: \""+ db.getPath() + "\"");
        }


    }

    @Override //Callback Methode
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }

}

编辑: 这是Test insert()的LogCat:

01-17 12:38:14.508: I/TestRunner(1135): started:     testInsert(android.and05_lektion3.test.SourceActivityTest)
01-17 12:38:14.558: I/ActivityManager(289): START u0 {act=android.intent.action.MAIN flg=0x10000000 cmp=android.and05_lektion3/.SourceActivity} from pid 1135
01-17 12:38:16.817: D/SourceActivity(1135): Stichwort0; "tword1"
01-17 12:38:18.367: I/Choreographer(1135): Skipped 352 frames!  The application may be doing too much work on its main thread.
01-17 12:38:19.108: I/Choreographer(289): Skipped 31 frames!  The application may be doing too much work on its main thread.
01-17 12:38:19.907: E/SourceActivity(1135): Fehler beim Speichern einer Literaturquelle. android.database.sqlite.SQLiteConstraintException: column shortdesc is not unique (code 19)
01-17 12:38:20.407: I/TestRunner(1135): failed: testInsert(android.and05_lektion3.test.SourceActivityTest)
01-17 12:38:20.407: I/TestRunner(1135): ----- begin exception -----
01-17 12:38:20.528: I/TestRunner(1135): junit.framework.AssertionFailedError
01-17 12:38:20.528: I/TestRunner(1135):     at junit.framework.Assert.fail(Assert.java:48)
01-17 12:38:20.528: I/TestRunner(1135):     at junit.framework.Assert.assertTrue(Assert.java:20)
01-17 12:38:20.528: I/TestRunner(1135):     at junit.framework.Assert.assertTrue(Assert.java:27)
01-17 12:38:20.528: I/TestRunner(1135):     at android.and05_lektion3.test.SourceActivityTest.testInsert(SourceActivityTest.java:26)
01-17 12:38:20.528: I/TestRunner(1135):     at java.lang.reflect.Method.invokeNative(Native Method)
01-17 12:38:20.528: I/TestRunner(1135):     at java.lang.reflect.Method.invoke(Method.java:511)
01-17 12:38:20.528: I/TestRunner(1135):     at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:214)
01-17 12:38:20.528: I/TestRunner(1135):     at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:199)
01-17 12:38:20.528: I/TestRunner(1135):     at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:192)
01-17 12:38:20.528: I/TestRunner(1135):     at  junit.framework.TestCase.runBare(TestCase.java:134)
01-17 12:38:20.528: I/TestRunner(1135):     at junit.framework.TestResult$1.protect(TestResult.java:115)
01-17 12:38:20.528: I/TestRunner(1135):     at junit.framework.TestResult.runProtected(TestResult.java:133)
01-17 12:38:20.528: I/TestRunner(1135):     at junit.framework.TestResult.run(TestResult.java:118)
01-17 12:38:20.528: I/TestRunner(1135):     at junit.framework.TestCase.run(TestCase.java:124)
01-17 12:38:20.528: I/TestRunner(1135):     at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:190)
01-17 12:38:20.528: I/TestRunner(1135):     at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:175)
01-17 12:38:20.528: I/TestRunner(1135):     at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555)
01-17 12:38:20.528: I/TestRunner(1135):     at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1661)
01-17 12:38:20.528: I/TestRunner(1135): ----- end exception -----
01-17 12:38:20.627: I/TestRunner(1135): finished: testInsert(android.and05_lektion3.test.SourceActivityTest)

提前致谢!

0 个答案:

没有答案