Skip to content

8. Week 8 (30 Oct to 5 Nov)

HuixianZhang edited this page Nov 9, 2017 · 2 revisions

Problems with Fragment

We came to know that fragments are mainly used when you want your app to behave differently in mobiles and tables. We are facing problem in replacing a fragment with another.

'FragmentBack ff = (FragmentBack) fm_top.findFragmentById(R.id.fragment_top);`

The code above should return object of type FragmentBack, but it is returning FragmentFront, thus causing the error:

Caused by: java.lang.ClassCastException: layout.FragmentFront cannot be cast to layout.FragmentBack at com.gtatiya.mywordcard.Main2Activity.setBackCard(Main2Activity.java:109)

Solution - use ViewFlipper

"ViewFlipper in android is an extension of ViewAnimator class, which animates between two or more views that have been added to it. Only one child is shown at a time and the user can flip to view the other child views."

Source:

SQLite inset only when not exists

Every times the app starts, it inserts data into SQLite Database. But, it is not required to insert data every time app start. It should only insert data when the app is launched for the first time. Thus, we include code to check whether "VocabTable" table exits. If it does, then there is no need to insert data, else it will insert data.

Code:

boolean isInserted = myDB.checkTable("VocabTable");
        if (isInserted == true){
            Toast.makeText(MainActivity.this, "Table Exists", Toast.LENGTH_LONG).show();
        } else{
            Toast.makeText(MainActivity.this, "Table not Exists", Toast.LENGTH_LONG).show();
            text2SQLite();
        }

public boolean checkTable(String tableName){
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '" + TABLE_NAME + "'", null);
        if(cursor!=null) {
            if(cursor.getCount()>0) {
                cursor.close();
                return true;
            }
            cursor.close();
        }
        return false;
    }

Source: https://stackoverflow.com/questions/3058909/how-does-one-check-if-a-table-exists-in-an-android-sqlite-database