Mi programa no puede encontrar tablas en la base de datos sqlite en Android

I have SQLite database file (which I did not create in this program, and it has its tables and datas), I open it in my android program, but when I write SELECT statement program can not find tables and I get error:

Error: no such table: Person

Este es el código:

public class SQLiteAdapter {

    private DbDatabaseHelper databaseHelper;

    private static String dbfile = "/data/data/com.example.searchpersons/databases/";

    private static String DB_NAME = "Person.db";

    static String myPath = dbfile + DB_NAME;

    private static SQLiteDatabase database;

    private static final int DATABASE_VERSION = 3;

    private static String table = "Person";

    private static Context myContext;

    public SQLiteAdapter(Context ctx) {
        SQLiteAdapter.myContext = ctx;
        databaseHelper = new DbDatabaseHelper(SQLiteAdapter.myContext);
    }

    public static class DbDatabaseHelper extends SQLiteOpenHelper {
        public DbDatabaseHelper(Context context) {
            super(context, DB_NAME, null, DATABASE_VERSION);
            dbfile = "/data/data/" + context.getPackageName() + "/databases/";
            myPath = dbfile + DB_NAME;
            //this.myContext = context;
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        }
    }

    public SQLiteDatabase open() {
        try {
            database = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
            Log.v("db log", "database exist open");
        } catch (SQLiteException e) {
            Log.v("db log", "database does't exist");
        }

        if (database != null && database.isOpen())
            return database;
        else {
            database = databaseHelper.getReadableDatabase();
            Log.v("db log", "database exist helper");
        }

        return database;
    }

    public Cursor onSelect(String firstname, String lastname) {
        Log.v("db log", "database exist select");
        Cursor c = database.rawQuery("SELECT * FROM " + table + " where Firstname='" + firstname + "' And Lastname='" + lastname + "'", null);
        c.moveToFirst();
        return c;
    }

    public void close() {
        if (database != null && database.isOpen()) {
            database.close();
        }
    }
}

And this is button click function:

   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
      Button btn1 = (Button) rootView.findViewById(R.id.button1);

      btn1.setOnClickListener(new View.OnClickListener() {

          public void onClick(View v) {
              EditText t = (EditText) rootView.findViewById(R.id.editText1);
              String name = t.getText().toString();
              EditText tt = (EditText) rootView.findViewById(R.id.editText2);
              String lastname = tt.getText().toString();

              if (name.length() == 0 || lastname.length() == 0) {
                  Toast.makeText(rootView.getContext(), "Please fill both box", Toast.LENGTH_LONG).show();
              } else {
                  GridView gridview = (GridView) rootView.findViewById(R.id.gridView1);
                  List < String > li = new ArrayList < String > ();
                  ArrayAdapter < String > adapter = new ArrayAdapter < String > (rootView.getContext(), android.R.layout.simple_gallery_item, li);

                  try {
                      SQLiteAdapter s = new SQLiteAdapter(rootView.getContext());
                      s.open();
                      Cursor c = s.onSelect(name, lastname);
                      if (c != null) {
                          if (c.moveToFirst()) {
                              do {
                                  String id = c.getString(c.getColumnIndex("ID"));
                                  String name1 = c.getString(c.getColumnIndex("Firstname"));
                                  String lastname1 = c.getString(c.getColumnIndex("Lastname"));
                                  String personal = c.getString(c.getColumnIndex("PersonalID"));
                                  li.add(id);
                                  li.add(name1);
                                  li.add(lastname1);
                                  li.add(personal);
                                  gridview.setAdapter(adapter);
                              } while (c.moveToNext());
                          }
                      } else {
                          Toast.makeText(rootView.getContext(), "There is no data", Toast.LENGTH_LONG).show();
                      }

                      c.close();
                      s.close();
                  } catch (Exception e) {
                      Toast.makeText(rootView.getContext(), "Error : " + e.getMessage(), Toast.LENGTH_LONG).show();
                  }
              }
          }
      });
      return rootView;
  }

I check database in SQLite Database Browser, everything is normal (There are tables and data), but program still can not find them.

I added sqlitemanager to eclipse and it can not see tables too: enter image description here There is only one table android_metadata and there are no my tables.

¿Alguien puede ayudarme?

preguntado el 12 de junio de 14 a las 11:06

Can you post exact error from the log cat? -

where are you creating your tables??? your onCreate method does nothing in this code... you need to create tables in onCreate método. -

3 Respuestas

I thought about it for about a week, the answer is very simple. I resolved the problem so: from administrador de sqlite enter image description here

I added database from that button. And now everything works fine ;)

Respondido el 23 de junio de 14 a las 08:06

In oncreate you have to create your db. I am sending you my db class.



import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DbAdapter extends SQLiteOpenHelper {

    private static DbAdapter mDbHelper;

    public static final String DATABASE_NAME = "demoDb";


    public static final String TABLE_Coin= "coin_table";
    public static final String TABLE_Inbox= "inbox";
    public static final String TABLE_Feature= "feature";
    public static final String TABLE_Time= "time";
    public static final String TABLE_Deduct_money= "deduct_time";
    public static final String TABLE_Unread_message= "unread_message";



    public static final String COLUMN_Email= "email";
    public static final String COLUMN_Appearence= "appearence";
    public static final String COLUMN_Drivability= "drivability";
    public static final String COLUMN_Fuel= "fuel";
    public static final String COLUMN_Insurance= "insurance";

    public static final String COLUMN_Wow= "wow";
    public static final String COLUMN_CurrentValue= "current_value";
    public static final String COLUMN_coin = "name";
    public static final String COLUMN_seenTime = "seen";
    public static final String COLUMN_number_of_times = "number_of_times";
    public static final String COLUMN_name = "name";

    public static final String COLUMN_type = "type";
    public static final String COLUMN_text = "text";
    public static final String COLUMN_image = "image";
    public static final String COLUMN_created_time = "created_time";

    public static final String COLUMN_unread = "unread";

    // ****************************************

    private static final int DATABASE_VERSION = 1;


    private final String DATABASE_CREATE_BOOKMARK = "CREATE TABLE "
            + TABLE_Coin + "(" + COLUMN_coin
            + " Varchar,"+COLUMN_Email +" Varchar, UNIQUE("
            + COLUMN_Email + ") ON CONFLICT REPLACE)";


    private final String DATABASE_CREATE_BOOKMARK1 = "CREATE TABLE "
            + TABLE_Feature + "(" + COLUMN_Appearence
            + " Integer,"+COLUMN_Email +" Varchar ,"+COLUMN_name +" Varchar ,"+COLUMN_Drivability +" Integer ,"+COLUMN_Wow +" Integer,"+COLUMN_CurrentValue +" Integer,"+COLUMN_Fuel +" Integer,"+COLUMN_Insurance +" Integer, UNIQUE("
            + COLUMN_Email + ") ON CONFLICT REPLACE)";


    private final String DATABASE_CREATE_BOOKMARK2 = "CREATE TABLE "
            + TABLE_Time + "(" + COLUMN_Email +" Varchar ,"+COLUMN_seenTime +" Integer,"+COLUMN_number_of_times +" Integer, UNIQUE("
            + COLUMN_Email + ") ON CONFLICT REPLACE)";



    private final String DATABASE_CREATE_BOOKMARK3 = "CREATE TABLE "
            + TABLE_Deduct_money + "(" + COLUMN_seenTime
            + " Varchar,"+ COLUMN_number_of_times
            + " Integer,"+COLUMN_Email +" Varchar, UNIQUE("
            + COLUMN_Email + ") ON CONFLICT REPLACE)";


    private final String DATABASE_CREATE_BOOKMARK4 = "CREATE TABLE "
            + TABLE_Inbox + "(" + COLUMN_created_time
            + " DATETIME,"+ COLUMN_image
            + " Varchar,"
            + COLUMN_type
            + " Varchar,"+ COLUMN_name
            + " Varchar,"+ COLUMN_text
            + " Varchar,"+COLUMN_Email +" Varchar)";


    private final String DATABASE_CREATE_BOOKMARK5 = "CREATE TABLE "
            + TABLE_Unread_message + "(" + COLUMN_unread
            + " Varchar,"+COLUMN_Email +" Varchar, UNIQUE("
            + COLUMN_Email + ") ON CONFLICT REPLACE)";

    private DbAdapter(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public static synchronized DbAdapter getInstance(Context context) {
        if (mDbHelper == null) {
            mDbHelper = new DbAdapter(context);
        }

        return mDbHelper;
    }

    /**
     * Tries to insert data into table
     * 
     * @param contentValues
     * @param tablename
     * @throws SQLException
     *             on insert error
     */
    public void insertQuery(ContentValues contentValues, String tablename)
            throws SQLException {

        try {
            final SQLiteDatabase writableDatabase = getWritableDatabase();
            writableDatabase.insert(tablename, null, contentValues);
            // writableDatabase.insertWithOnConflict(tablename, null,
            // contentValues,SQLiteDatabase.CONFLICT_REPLACE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //  public void insertReplaceQuery(ContentValues contentValues, String tablename)
    //          throws SQLException {
    //
    //      try {
    //          final SQLiteDatabase writableDatabase = getWritableDatabase();
    //          writableDatabase.insertOrThrow(tablename, null, contentValues);
    //
    //      } catch (Exception e) {
    //          e.printStackTrace();
    //      }
    //  }
    //
    //  /**
    //   * Update record by ID with contentValues
    //   * 
    //   * @param id
    //   * @param contentValues
    //   * @param tableName
    //   * @param whereclause
    //   * @param whereargs
    //   */
        public void updateQuery(ContentValues contentValues, String tableName,
                String whereclause, String[] whereargs) {

            try {
                final SQLiteDatabase writableDatabase = getWritableDatabase();
                writableDatabase.update(tableName, contentValues, whereclause,
                        whereargs);

            } catch (Exception e) {
                e.printStackTrace();

            }
        }

    public Cursor fetchQuery(String query) {
        final SQLiteDatabase readableDatabase = getReadableDatabase();
        final Cursor cursor = readableDatabase.rawQuery(query, null);
        if (cursor != null) {
            cursor.moveToFirst();
        }
        return cursor;
    }

    public Cursor fetchQuery(String query, String[] selectionArgs) {
        final SQLiteDatabase readableDatabase = getReadableDatabase();
        final Cursor cursor = readableDatabase.rawQuery(query, selectionArgs);

        if (cursor != null) {
            cursor.moveToFirst();
        }
        return cursor;
    }

    public void delete(String table) {
        final SQLiteDatabase writableDatabase = getWritableDatabase();
        writableDatabase.delete(table, null, null);
    }

    public void delete(String table, String whereClause, String[] selectionArgs) {
        final SQLiteDatabase writableDatabase = getWritableDatabase();
        writableDatabase.delete(table, whereClause, selectionArgs);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL(DATABASE_CREATE_BOOKMARK);
        db.execSQL(DATABASE_CREATE_BOOKMARK1);
        db.execSQL(DATABASE_CREATE_BOOKMARK2);
        db.execSQL(DATABASE_CREATE_BOOKMARK3);
        db.execSQL(DATABASE_CREATE_BOOKMARK4);
        db.execSQL(DATABASE_CREATE_BOOKMARK5);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("DROP TABLE IF EXISTS " + TABLE_Coin);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_Feature);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_Time);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_Deduct_money);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_Inbox);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_Unread_message);

        onCreate(db);

    }
}

Respondido el 12 de junio de 14 a las 12:06

You are messing up the paths.

Please clean up every definition or reference to dbfile e myPath.You are initializing them in the definition with some values (probably copy-pasted), then giving them new different values in the DbDatabaseHelper constructor. And the helper will not use these paths, it will just create the database in the default directory.

Then after this, in the open método al que estás llamando SQLiteDatabase.openDatabase with your intended paths. Use instead obtener base de datos legible e obtener base de datos grabable from the Helper.

Respondido el 12 de junio de 14 a las 12:06

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.