0

I published my app 2 months ago and sometimes, I am geting some reports about bugs.

Here is the error report:

java.lang.RuntimeException: Unable to start activity    ComponentInfo{mdpi.android/mdpi.android.User_Registration_Country_Choosing}: java.lang.IllegalStateException: database not open
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: database not open
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1232)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1191)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1273)
at mdpi.android.database.LocalDatabase.getAllCountrys(LocalDatabase.java:310)
at    mdpi.android.User_Registration_Country_Choosing.onCreate(User_Registration_Country_Choosing.java:81)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
... 11 more

The strange thing is that when I am testing the app, I am newer getting this error...

Do you have an ideo what can be the problem???

Thank you.

Here is th code of User_Registration_country_Choosing

public class User_Registration_Country_Choosing extends Activity implements TextWatcher {


public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); 

    setContentView(R.layout.choosecountry);

//      Disable the Strict mode
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    Country = (EditText) findViewById(R.id.CountryName);
    Country.requestFocus();

    Bundle b                        = this.getIntent().getExtras();    
    user =  new User_Database(0, null, null, null, null, null, null, null, null, null);
    registrationConfirmPassword     = b.getString("registrationConfirmPassword");
    user                            = b.getParcelable("user");


    InputMethodManager inputManager = (InputMethodManager)
            getSystemService(Context.INPUT_METHOD_SERVICE); 
    try{
    inputManager.showSoftInput(Country, InputMethodManager.SHOW_IMPLICIT);
    }
    catch (Exception e)
    {}

    Country.addTextChangedListener(this);
    String ChooseCountry = "'%%'";
    List<Country> values = LocalDatabase.getAllCountrys(ChooseCountry);

    ListView lv = (ListView)findViewById(R.id.listView1);
    lv.setAdapter(new ArrayAdapter<Country>(
            this,R.layout.country_list_black_text,R.id.list_content, values));

    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, final View view,
            int position, long id) {
            TextView textView = (TextView) view.findViewById(R.id.list_content);
            final String choosencountry = textView.getText().toString(); 
            Toast.makeText(mContext, "You choosed: "+choosencountry, Toast.LENGTH_LONG).show();
            user.setcountry(choosencountry);
            KeyboardDown();
            new Handler().postDelayed(new Runnable() {
                public void run() {

                    Intent myIntent = new Intent(view.getContext(), UserRegistration.class);
                    Bundle b                = new Bundle();
                    b.putParcelable("user", user);
                    b.putString("registrationConfirmPassword", registrationConfirmPassword);
                    myIntent.putExtras(b);
                    startActivityForResult(myIntent, 0);  
                    KeyboardDown(); 
                    finish(); 
                    }
                }, 3500);
            }
        });
  }

public void afterTextChanged(Editable arg0) {}

public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
        int arg3) { }

public void onTextChanged(CharSequence s, int start, int before, int count) {
    EditText Country;
    Country = (EditText) findViewById(R.id.CountryName);
    String country = Country.getText().toString();
    String ChooseCountry = "'"+country+"%'";
    List<Country> values = LocalDatabase.getAllCountrys(ChooseCountry);

    ListView lv = (ListView)findViewById(R.id.listView1);
    lv.setAdapter(new ArrayAdapter<Country>(
            this,R.layout.country_list_black_text,R.id.list_content, values));
}

public void KeyboardDown(){
    InputMethodManager inputManager = (InputMethodManager)
            getSystemService(Context.INPUT_METHOD_SERVICE); 
    try{
    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
               InputMethodManager.HIDE_NOT_ALWAYS);
    }
    catch (Exception e)
    {}
}
}

And here is the code of LocalDatabase.java

package mdpi.android.database;



public class LocalDatabase {

public LocalDatabase(Context context){
    databasetables = new DatabaseTables(context, NAME_Database, null, VERSION_BDD);
}

public void open(){
    Database = databasetables.getWritableDatabase();
}

public void close(){
    Database.close();
}

public SQLiteDatabase getBDD(){
    return Database;
}


public static long insertUser(User_Database user){
    ContentValues values = new ContentValues();
    values.put("ID", user.getuserId());
    values.put("email", user.getemail());
    values.put("password", user.getpassword());
    values.put("first_name", user.getfirstname());
    values.put("last_name", user.getlastname());
    values.put("street", user.getstreet());
    values.put("postal_code", user.getpostalcode());
    values.put("city", user.getcity());
    values.put("country", user.getcountry());
    values.put("alert_frequency", user.getalertfrequency());
    return Database.insert("user", null, values);
}

public static long insertSubmission(Submissions_Database submission){
    ContentValues values = new ContentValues();
    values.put("ID", submission.getID());
    values.put("hash", submission.getHashKey());
    values.put("journalId", submission.getJournalID());
    values.put("title", submission.getTitle());
    values.put("subtitle", submission.getSubTitle());
    values.put("date", submission.getDate());
    values.put("status", submission.getStatus());
    values.put("journal_title", submission.getJournalTitle());
    return Database.insert("submission", null, values);
}

public static long insertSubmissionLog(SubmissionLog_Database submissionLog){
    ContentValues values = new ContentValues();
    values.put("title", submissionLog.getTitle());
    values.put("hash", submissionLog.getHashKey());
    values.put("date", submissionLog.getDate());
    return Database.insert("submissionlog", null, values);
}

public static long insertSubscriptionsFromTheServer(Subscription_Database subscriptions){
    ContentValues values = new ContentValues();
    values.put("journalId", subscriptions.getJournalID());
    return Database.insert("subscriptions", null, values);
}

public static long insertSubscriptionsFromtTheJournalList(int journalId){
    ContentValues values = new ContentValues();
    values.put("journalId", journalId);
    return Database.insert("subscriptions", null, values);
}

public static long insertCountry(Country country){
    ContentValues values = new ContentValues();
    values.put("id", country.getid());
    values.put("name", country.toString());
    return Database.insert("country", null, values);    
}

public static long insertJournal(Journal_Database journals){
    ContentValues values = new ContentValues();
    values.put("journalId", journals.getJournalID());
    values.put("nameFull", journals.getNameFull());
    values.put("nameShort", journals.getNameShort());
    values.put("nameSystem", journals.getNameSystem());
    values.put("about", journals.getAbout());
    values.put("nameIso4", journals.getNameIso4());
    values.put("namePubmed", journals.getNamePubmed());
    values.put("namePubmedShort", journals.getNamePubmedShort());
    values.put("ISSNElectronic", journals.getISSNElectronic());
    values.put("coden", journals.getCoden());
    values.put("APCChf", journals.getAPCChf());
    values.put("APCCny", journals.getAPCCny());
    values.put("APCEngChf", journals.getAPCEngChf());
    values.put("APCEngCny", journals.getAPCEngCny());
    values.put("APCFormatChf", journals.getAPCFormatChf());
    values.put("SCITracked", journals.getSCITracked());
    values.put("impactFactor", journals.getImpactFactor());
    values.put("ImpactFactor5years", journals.getImpactFactor5years());
    values.put("ImpactFactorYear", journals.getImpactFactorYear());
    values.put("EstablishedYear", journals.getEstablishedYear());
    values.put("ShortDescription", journals.getShortDescription());
    values.put("AcceptedPapers", journals.getAcceptedPapers());
    values.put("StyleHeaderLight", journals.getStyleHeaderLight());
    values.put("StyleHeaderDark", journals.getStyleHeaderLight());
    values.put("CurrentIssue", journals.getCurrentIssue());
    values.put("FurthcomingIssue", journals.getForthcomingIssue());
    values.put("ContactEmail", journals.getContactEmail());
    values.put("ContactID", journals.getContactID());
    values.put("Pubfrequency", journals.getPubfrequency());
    values.put("PublicFlag", journals.getPublicFlag());
    values.put("ReviewRequestTime", journals.getReviewRequestTime());
    values.put("DOIAbbreviation", journals.getDOIAbbreviation());
    return Database.insert("journals", null, values);
}

public static void delateSubscribedJournal(int journalId){
    Database.execSQL("DELETE FROM subscriptions WHERE journalId ="+journalId);
}

public static void deleteSubmissionLog(){
    Database.execSQL("DELETE FROM submissionlog");
}

public static void deleteSubscriptions(){
    Database.execSQL("DELETE FROM subscriptions");
}

public static void deleteUser(){
    Database.execSQL("DELETE FROM user");
}

public static void deleteUserSubmissions(){
    Database.execSQL("DELETE FROM submission");
}

public static void deleteHistory(){ 
    Database.execSQL("DELETE FROM history");
}

public static void deleteJournals()
{
    Database.execSQL("DELETE FROM journals");
}

public static void deleteEditorialBoard()
{
    Database.execSQL("DELETE FROM editorialboard");
}

public static void deleteHighlights_News()
{
    Database.execSQL("DELETE FROM highlights_news");
}
public static void deleteHighlights_NewSpecialIssues()
{
    Database.execSQL("DELETE FROM highlights_new_special_issues");
}




public static List<Country> getAllCountrys(String ChooseCountry) {
    List<Country> countrys = new ArrayList<Country>();

    Cursor cursor = Database.query("country",
            CountryColName,"name like " + ChooseCountry, null, null, null, null);

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        Country country = cursorToCountry(cursor);
        countrys.add(country);
        cursor.moveToNext();
    }
    cursor.close();
    return countrys;
}

public static  String getChoosenCountryName(String countryIdString) {

    if (countryIdString!=null)
    {
    int countryIdInt=Integer.decode(countryIdString);

    Cursor cursor = Database.query("country",
            CountryColName,"id like " + countryIdInt, null, null, null, null);

    cursor.moveToFirst();
    String countryName = null;
    while (!cursor.isAfterLast()) {
        countryName = cursor.getString(0);      
        cursor.moveToNext();
    }
    cursor.close();
    return countryName;
    }
    return "";
}

public static  int getChoosenCountryId(String countryName) {
    Cursor cursor = Database.query("country",
            CountryColId,"name like "+"'"+countryName+"'", null, null, null, null);

    cursor.moveToFirst();
    int countryId = 0;
    while (!cursor.isAfterLast()) {
        countryId = cursor.getInt(0);
        cursor.moveToNext();
    }
    cursor.close();
    return countryId;
}

private static Country cursorToCountry(Cursor cursor) {
    Country country = new Country(0,null);
    country.setname(cursor.getString(0));
    return country;
}


public static long updateJournal(int journalId, String updateRow,String value){
    ContentValues values = new ContentValues();
    values.put(updateRow,value);
    return Database.update("journals", values, "journalId="+ journalId, null);
}


public static int CheckCountryPresence() {
    final SQLiteStatement stmt = 
    Database.compileStatement("SELECT COUNT(*) FROM COUNTRY");
    return (int) stmt.simpleQueryForLong();
}

public static int CheckOfficesPresence() {
    final SQLiteStatement stmt = 
    Database.compileStatement("SELECT COUNT(*) FROM OFFICES");
    return (int) stmt.simpleQueryForLong();
}

private static User_Database cursorToUser(Cursor cursor) {
    User_Database user = new User_Database(0, null, null, null, null, null, null, null, null, null);
    user.setuserId(cursor.getInt(0));
    user.setemail(cursor.getString(1));
    user.setpassword(cursor.getString(2));
    user.setfirstname(cursor.getString(3));
    user.setlastname(cursor.getString(4));
    user.setstreet(cursor.getString(5));
    user.setpostalcode(cursor.getString(6));
    user.setcity(cursor.getString(7));
    user.setcountry(cursor.getString(8));
    user.setalertfrequency(cursor.getString(9));
    return user;
}

public static User_Database getUserInformations() {
    User_Database user = new User_Database(0, null, null, null, null, null, null, null, null, null);
    Cursor cursor = Database.query("user",
            UserCol_All,"", null, null, null, null);

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        user = cursorToUser(cursor);
        cursor.moveToNext();
    }
    cursor.close();
    return user;
}





public static ArrayList<Submissions_Database> getAllSubmissions() {
    ArrayList<Submissions_Database> submissions = new ArrayList<Submissions_Database>();

    Cursor cursor = Database.query("submission",
            SubmissionCOL_All,"", null, null, null, "date DESC");
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        Submissions_Database submission = cursorToSubmissions(cursor);
        submissions.add(submission);
        cursor.moveToNext();
    }
    cursor.close();
    return submissions;
}

public static Submissions_Database getSelectedSubmission(String hashKey) {

    Cursor cursor = Database.query("submission",
            SubmissionCOL_All,"hash like "+"'"+hashKey+"'", null, null, null, null);
    Submissions_Database submission = new Submissions_Database(0, null, 0, null, null, null, 0, null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        submission = cursorToSubmissions(cursor);
        cursor.moveToNext();
    }
    cursor.close();
    return submission;
}

public static ArrayList<Submissions_Database> getAllSearchedSubmissions(String submissionName) {
    ArrayList<Submissions_Database> submissions = new ArrayList<Submissions_Database>();

    Cursor cursor = Database.query("submission",
            SubmissionCOL_All,
            "title like '%"+submissionName+"%'"
            +" OR subtitle like '%"+submissionName+"%'"
            +" OR id like '%"+submissionName+"%'",
            null, null, null, "date DESC", "10");
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        Submissions_Database submission = cursorToSubmissions(cursor);
        submissions.add(submission);
        cursor.moveToNext();
    }
    cursor.close();
    return submissions;
}

private static Submissions_Database cursorToSubmissions(Cursor cursor) {
    Submissions_Database submission = new Submissions_Database(0, null, 0, null, null, null, 0, null);
    submission.setJournalTitle(cursor.getString(0));

    String SubmissionJournalDate = "Unknown";
    SubmissionJournalDate = cursor.getString(1);

    if (SubmissionJournalDate ==null)
    {
        submission.setDate("Unknown");
    }
    else
    {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        try 
        {
            Date date = fmt.parse(SubmissionJournalDate);
            SimpleDateFormat fmtOut = new SimpleDateFormat("dd-MM-yyyy");
            submission.setDate(fmtOut.format(date));
        }
        catch(ParseException pe) 
        {
            submission.setDate("Unknown");   
        }
    }
    submission.setTitle(cursor.getString(2));
    submission.setID(cursor.getInt(3));
    submission.setHashKey(cursor.getString(4));
    submission.setStatus(cursor.getInt(5));
    return submission;
}

public static int getSubmissionsSize() {
    try{
    final SQLiteStatement stmt = Database
            .compileStatement("SELECT MAX(rowid) FROM submission");
    return (int) stmt.simpleQueryForLong();
    }
    catch (Exception e) {
        return 0;
    }
}


public static ArrayList<Journal_Database> getAllPublicJournalNames() {
    ArrayList<Journal_Database> journals = new ArrayList<Journal_Database>();
    Cursor cursor = Database.query("journals",
            JournalsCOL_All,"publicFlag like 1", null, null, null, "nameSystem");
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        Journal_Database journalObject = cursorToJournals(cursor);
        journals.add(journalObject);
        cursor.moveToNext();
    }
    cursor.close();
    return journals;
}

public static ArrayList<Journal_Database> getAllSearchedJournals(String journalName, String limit ) {
    ArrayList<Journal_Database> journals = new ArrayList<Journal_Database>();
    Cursor cursor = Database.query("journals",
            JournalsCOL_All,
            "nameSystem like '%"+journalName+"%' AND PublicFlag = 1"
            +" OR nameFull like '%"+journalName+"%' AND PublicFlag = 1"
            +" OR nameShort like '%"+journalName+"%' AND PublicFlag = 1"
            , null, null, null, "nameSystem", limit );
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        Journal_Database journalObject = cursorToJournals(cursor);
        journals.add(journalObject);
        cursor.moveToNext();
    }
    cursor.close();
    return journals;
}



private static Subscription_Database cursorToSubscriptions(Cursor cursor) {
    Subscription_Database subscription = new Subscription_Database(0);
    subscription.setJournalID(cursor.getInt(0));
    return subscription;
}

public static boolean JournalPresence() {
    final SQLiteStatement stmt = 
    Database.compileStatement("SELECT COUNT(*) FROM JOURNALS");
    if (stmt.simpleQueryForLong()==0){
    return false;
    }
    else{
        return true;
    }
}

public static String getJournalNameShort(int journalId){
    Cursor cursor2 = Database.query("journals",
            JournalCOL_NameShort,"journalId like "+"'"+journalId+"'", null, null, null, null);
    cursor2.moveToFirst();
    String Title = "";
    while (!cursor2.isAfterLast()) {
        Title = cursor2.getString(0);
        cursor2.moveToNext();
    }
    cursor2.close();
    return Title;
}

public static String getJournalEditorialBoard(int journalId){
    Cursor cursor2 = Database.query("editorialboard",
            EditorialBoard_All,"journalId like "+"'"+journalId+"'", null, null, null, null);
    cursor2.moveToFirst();
    String EditorialBoard = "";
    while (!cursor2.isAfterLast()) {
        EditorialBoard = cursor2.getString(2)+cursor2.getString(0)+cursor2.getString(1);
        cursor2.moveToNext();
    }
    cursor2.close();
    return EditorialBoard;
}

public static ArrayList<Subscription_Database> getAllSubscribedJournals() {
    ArrayList<Subscription_Database> journals = new ArrayList<Subscription_Database>();
    Cursor cursor = Database.query("subscriptions",
            SubscriptionCOL_JournalId,"", null, null, null, null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        Subscription_Database subscription = cursorToSubscriptions(cursor);
        journals.add(subscription);
        cursor.moveToNext();
    }
    cursor.close();
    return journals;
}

public static int getHistoryLastSuccessfullUpdate(){
    Cursor cursor2 = Database.query("history",
            HistoryCOL_LastSuccessfullUpdate,"", null, null, null, null);
    cursor2.moveToFirst();
    int lastSuccessfullUpdate = 0;
    lastSuccessfullUpdate = cursor2.getInt(0);
    cursor2.close();
    return lastSuccessfullUpdate;
}

public static int CheckMDPIPresence() 
{
    final SQLiteStatement stmt = 
    Database.compileStatement("SELECT COUNT(*) FROM mdpi");
    return (int) stmt.simpleQueryForLong();
}

public static String getJournalAimsAndScope(String journalNameShort)
{
    Cursor cursor2 = Database.query("journals",
            JournalCOL_Abaut,"nameSystem ="+"'"+journalNameShort+"'", null, null, null, null);
    cursor2.moveToFirst();
    String aimsAndScope = null;
    aimsAndScope = cursor2.getString(0);
    cursor2.close();
    return aimsAndScope;
}

public static int getJournalIdFromNameShort(String journalNameShort)
{
    Cursor cursor2 = Database.query("journals",
            JournalCOL_Id,"nameShort ="+"'"+journalNameShort+"'", null, null, null, null);
    cursor2.moveToFirst();
    int journalId = 0;
    while (!cursor2.isAfterLast()) {
        journalId = cursor2.getInt(0);
        cursor2.moveToNext();
    }
    cursor2.close();
    return journalId;
}

public static String getJournalNameShortFromNameSystem(String journalNameSystem)
{
    Cursor cursor2 = Database.query("journals",
            JournalCOL_NameShort,"nameSystem ="+"'"+journalNameSystem+"'", null, null, null, null);
    cursor2.moveToFirst();
    String journalNameShort = null;
    while (!cursor2.isAfterLast()) {
        journalNameShort = cursor2.getString(0);
        cursor2.moveToNext();
    }
    cursor2.close();
    return journalNameShort;
}

public static int getJournalIdFromNameSystem(String journalNameShort)
{
    Cursor cursor2 = Database.query("journals",
            JournalCOL_Id,"nameSystem ="+"'"+journalNameShort+"'", null, null, null, null);
    cursor2.moveToFirst();
    int journalId = 0;
    while (!cursor2.isAfterLast()) {
        journalId = cursor2.getInt(0);
        cursor2.moveToNext();
    }
    cursor2.close();
    return journalId;
}

public static boolean editorialBoardExistsAllready(int journalId) {
    final SQLiteStatement stmt = 
            Database.compileStatement("SELECT COUNT(*) FROM editorialboard WHERE journalId ="+journalId);
            long count= stmt.simpleQueryForLong();
    if (count==1)
        return true;
    else
    return false;
}

public  static String getEditorialboardValue(int journalId, String row) {
    String[] editorialBoardValue = {row};
    Cursor cursor = Database.query("editorialboard",
            editorialBoardValue, "journalId ="+journalId, null, null, null,null);
    cursor.moveToFirst();
    String result = "";
        result = cursor.getString(0);
    cursor.close();
    return result;
}

public static String getJournalISSNfromJournalId(int journalId){
    Cursor cursor2 = Database.query("journals",
            JournalCOL_ISSNelectronic,"journalId like "+journalId, null, null, null, null);
    cursor2.moveToFirst();
    String ISSNElectronic = null;
    while (!cursor2.isAfterLast()) {
        ISSNElectronic = cursor2.getString(0);
        cursor2.moveToNext();
    }
    cursor2.close();
    return ISSNElectronic;
}

public  static String getMDPIAbaut() {
    Cursor cursor = Database.query("mdpi",
            MDPIColAbaut,"", null, null, null, null);
    cursor.moveToFirst();
    String abaut = null;
    while (!cursor.isAfterLast()) {
        abaut = cursor.getString(0);        
        cursor.moveToNext();
    }
    cursor.close();
    return abaut;
}

public  static String getMDPIOpenAccess() {
    Cursor cursor = Database.query("mdpi",
            MDPIColOpenAccess,"", null, null, null, null);
    cursor.moveToFirst();
    String openAccess = null;
    while (!cursor.isAfterLast()) {
        openAccess = cursor.getString(0);       
        cursor.moveToNext();
    }
    cursor.close();
    return openAccess;
}

public  static ArrayList<String>  getOfficesHTML() {
    Cursor cursor = Database.query("offices",
            OfficesColHTML,"", null, null, null, null);
    cursor.moveToFirst();
    ArrayList<String> officesHTML = new ArrayList<String>();
    while (!cursor.isAfterLast()) {
        officesHTML.add(cursor.getString(0));       
        cursor.moveToNext();
    }
    cursor.close();
    return officesHTML;
}

public  static ArrayList<String>  getPublicJournalsNameSystem() {
    Cursor cursor = Database.query("journals",
            JournalCOL_NameSystem,"publicFlag like 1", null, null, null, "nameSystem");
    cursor.moveToFirst();
    ArrayList<String> publicJournalsNameSystem = new ArrayList<String>();
    while (!cursor.isAfterLast()) {
        publicJournalsNameSystem.add(cursor.getString(0));      
        cursor.moveToNext();
    }
    cursor.close();
    return publicJournalsNameSystem;
}

public  static ArrayList<String>  getPublicSearchedJournalsNameSystem(String journalName) {
    Cursor cursor = Database.query("journals",
            JournalCOL_NameSystem,"publicFlag like 1 AND nameSystem like "+journalName, null, null, null, "nameSystem");
    cursor.moveToFirst();
    ArrayList<String> publicJournalsNameSystem = new ArrayList<String>();
    while (!cursor.isAfterLast()) {
        publicJournalsNameSystem.add(cursor.getString(0));      
        cursor.moveToNext();
    }
    cursor.close();
    return publicJournalsNameSystem;
}

public  static ArrayList<String>  getPublicJournalsNameShort() {
    Cursor cursor = Database.query("journals",
            JournalCOL_NameShort,"publicFlag like 1", null, null, null, "nameShort");
    cursor.moveToFirst();
    ArrayList<String> publicJournalsNameShort = new ArrayList<String>();
    while (!cursor.isAfterLast()) {
        publicJournalsNameShort.add(cursor.getString(0));       
        cursor.moveToNext();
    }
    cursor.close();
    return publicJournalsNameShort;
}

public static String getHistoryLastSelectedJournalNameSystem(){
    Cursor cursor2 = Database.query("history",
            HistoryCOL_LastSelectedJournal,"", null, null, null, null);
    cursor2.moveToFirst();
    String lastSelectedJournal = null;

    lastSelectedJournal = cursor2.getString(0);
    cursor2.close();
    return lastSelectedJournal;
}

public static Journal_Database getHistoryLastSelectedJournal(String lastSelectedJournalNameSystem){
    Cursor cursor = Database.query("journals",
            JournalsCOL_All,"nameSystem like "+"'"+lastSelectedJournalNameSystem+"'", null, null, null, null);
    cursor.moveToFirst();
        Journal_Database lastSelectedJournal = cursorToJournals(cursor);
        cursor.moveToNext();
    cursor.close();
    return lastSelectedJournal;
}
private static Journal_Database cursorToJournals(Cursor cursor) {
    Journal_Database journal = new Journal_Database(0, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, 0, null, null);
    journal.setJournalID(cursor.getInt(0));
    journal.setNameFull(cursor.getString(1));
    journal.setNameShort(cursor.getString(2));
    journal.setNameSystem(cursor.getString(3));
    journal.setAbout(cursor.getString(4));
    journal.setNameIso4(cursor.getString(5));
    journal.setNamePubmed(cursor.getString(6));
    journal.setNamePubmedShort(cursor.getString(7));
    journal.setISSNElectronic(cursor.getString(8));
    journal.setCoden(cursor.getString(9));
    journal.setAPCChf(cursor.getString(10));
    journal.setAPCCny(cursor.getString(11));
    journal.setAPCEngChf(cursor.getString(12));
    journal.setAPCEngCny(cursor.getString(13));
    journal.setAPCFormatChf(cursor.getString(14));
    journal.setSCITracked(cursor.getString(15));
    journal.setImpactFactor(cursor.getString(16));
    journal.setImpactFactor5years(cursor.getString(17));
    journal.setImpactFactorYear(cursor.getString(18));
    journal.setEstablishedYear(cursor.getString(19));
    journal.setShortDescription(cursor.getString(20));
    journal.setAcceptedPapers(cursor.getString(21));
    journal.setStyleHeaderLight(cursor.getString(22));
    journal.setStyleHeaderDark(cursor.getString(23));
    journal.setForthcomingIssue(cursor.getString(24));
    journal.setContactEmail(cursor.getString(25));
    journal.setContactID(cursor.getString(26));
    journal.setPubfrequency(cursor.getString(27));
    journal.setPublicFlag(cursor.getInt(28));
    journal.setReviewRequestTime(cursor.getString(29));
    journal.setDOIAbbreviation(cursor.getString(30));
    return journal;
}
}
Milos Cuculovic
  • 19,631
  • 51
  • 159
  • 265
  • Post some code. And, see the error, what its telling, your database is not open. – Praveenkumar Jun 21 '12 at 06:24
  • It would hard to find out solution if you don't post your code! – Vipul Jun 21 '12 at 06:25
  • Thank you for the quick replay, it is not eaasy to post the code, I have something like 15 activities and almost 10 are using the database. I am opening my db in the onCreate on the main activity and closing in the onDestroy in the main activity. May be that's the reason of the problem... – Milos Cuculovic Jun 21 '12 at 06:29
  • 1
    @Anapost code of LocalDatabase.java and User_Registration_Country_Choosing.java – Vipul Jun 21 '12 at 06:32
  • can you put the database main file where you are createing the database and onCreate function of User_Registration_Country_Choosing.java – Dheeresh Singh Jun 21 '12 at 06:32
  • @VipulShah, I Edited my question by adding the 2 classes you asked for. – Milos Cuculovic Jun 21 '12 at 06:46

2 Answers2

1

You need to change the pattern for accessing the database.

Most importantly make a database helper if you don't have it. The main reson for this is having concurrent access to the database for writing. SQLite can'be access for writing from 2 places at the same time. The Database helper takes care of this.

Here is a code sample of a DBHelper that might help you. note that this is for using the ORMLite library database helper but its pretty much the same as a regular helper.

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

    private static final String DATABASE_NAME = "database.db";
    private static final int DATABASE_VERSION = 6;


    private static final AtomicInteger usageCounter = new AtomicInteger(0);
    // we do this so there is only one helper
    private static DatabaseHelper helper = null;

    /**
     * Use the {@link #DatabaseHelper(Context, String)}
     *
     * @param context
     */
    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION, R.raw.ormlite_config);
    }

    @Override
    public void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource,
                }

    /**
     * Get the helper, possibly constructing it if necessary. For each call to this method, there
     * should be 1 and only 1 call to {@link #close()}.
     */
    public static synchronized DatabaseHelper getHelper(Context context) {
        if (helper == null) {
            initHelper(context);
        }
        usageCounter.incrementAndGet();
        return helper;
    }

    private static void initHelper(Context context) {
        helper = new DatabaseHelper(context);
        usageCounter.set(0);
    }


    /**
     * Close the database connections and clear any cached DAOs. For each call to
     * {@link #getHelper(Context)}, there should be 1 and only 1 call to this method. If there were
     * 3 calls to {@link #getHelper(Context)} then on the 3rd call to this method, the helper and
     * the underlying database connections will be closed.
     */
    @Override
    public void close() {
        if (usageCounter.decrementAndGet() <= 0) {
            super.close();
            helper = null;
        }
    }
}

So this shows how to have a single open database instance and access it.

Each time you want to make some DB operation call the getHelper(context) method and after you are done you must call close. note that for each getHelper method you need to call close. So a common way of using this would be to get a reference in onCreate of an activity and close it in onDestroy(maybe make an abstract base activity to group this functionality).

Also keep in mind to use it separately in code that might live even after the activity is shut down such as async tasks.

DArkO
  • 15,880
  • 12
  • 60
  • 88
  • Thank you Darko, so If I am understanding, my problem comes with the reason that my DB is closed and I am trying to do some operations on it. And with the DatabaseHelper class, this will be regulated if I am calling the open method on each onCreate and close method on each onDestroy... – Milos Cuculovic Jun 21 '12 at 06:52
  • Yes the important code here is in the 2 methods called getHelper and close. The database helper represents just a good way to code a DB. however you can still use your own code but with the adjustments i presented in my helper code. Just open a writeable database before each db operation and close it afterwards. The way i have presented will avoid issues with the access to the Db. – DArkO Jun 21 '12 at 07:24
  • also as i can see your code, you can really benefit from using some ORM database library. i recommend ORMLite. There are better ways to work with databases in android and i suggest you do some research. it will save you the time in development and stabilization. – DArkO Jun 21 '12 at 07:27
  • Thank you Darko, I will try to use this. – Milos Cuculovic Jun 21 '12 at 07:27
0

The issue is you forgot to call open() .

You have never called open() function in LocalDatabase

Vipul
  • 27,808
  • 7
  • 60
  • 75
  • Thank you Vipul Shah. In fact, I am calling localDatabase = new LocalDatabase(this); localDatabase.open(); in the onCreate in my Main Activity class which is named MDPIActivity.java . This is not right? – Milos Cuculovic Jun 21 '12 at 06:58
  • No because they are different instance.you should call it in localDatabase because you are using Database.query.So you must have Database = databasetables.getWritableDatabase(); or Database = databasetables.getReadableDatabase(); written before calling query – Vipul Jun 21 '12 at 07:01
  • Ok, and where shuld I open the DB, in public LocalDatabase(Context context) ? – Milos Cuculovic Jun 21 '12 at 07:05
  • Ok, i added in public LocalDatabase(Context context) this: Database = databasetables.getWritableDatabase(); I don't need to add Database = databasetables.getReadableDatabase(); ? – Milos Cuculovic Jun 21 '12 at 07:20
  • Both are same with minute difference.you can use any – Vipul Jun 21 '12 at 07:28
  • Thank yoou, I have another issue with this app, If you could take a look here;http://stackoverflow.com/questions/11133457/android-noclassdeffounderror-for-some-app-users – Milos Cuculovic Jun 21 '12 at 07:30
  • If it solved your issues then please close this question first by accepting correct answer – Vipul Jun 21 '12 at 07:32
  • StrictMode is been introduced in API level 9.Those users must be using pre API level 9 devices – Vipul Jun 21 '12 at 07:35