如何访问在其他类中创建的数据库?

时间:2017-11-22 13:39:02

标签: android database

我一直在阅读有关该问题的Stackoverflow上的很多帖子。几乎所有答案都是关于使用SQLiteOpenHelper类,这正是我正在做的事情。

我的问题是我有一个存储一些统计信息的数据库,我想在StatsActivity中输出统计信息。问题是我在MainActivity中为统计信息创建了一个数据库,我不知道如何在StatsActivity中访问它。

我试图在StatsDB中实例化StatsActivity的实例,因为它已在其他主题中被告知。 StatsDB是一个扩展SQLiteOpenHelper并表示统计数据库的类。

StatsActivity.java

public class StatsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stats);

        StatsDB stats = new StatsDB(this);
        Cursor curs = stats.getAllStats();

        TextView created = (TextView) findViewById(R.id.TextView_Created_Counter);
        TextView participated = (TextView) findViewById(R.id.TextView_Participated_Counter);
    }
}

但是,我一直收到来自字符串Cursor curs = stats.getAllStats();的跟踪回溯的运行时错误:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kirill.myapplication/com.example.kirill.myapplication.StatsActivity}: android.database.sqlite.SQLiteException: no such table: StatsDatabase (code 1): , while compiling: SELECT _id, type, number FROM StatsDatabase
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2696)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2757)
                  at android.app.ActivityThread.-wrap12(ActivityThread.java)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1504)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:163)
                  at android.app.ActivityThread.main(ActivityThread.java:6237)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:877)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
               Caused by: android.database.sqlite.SQLiteException: no such table: StatsDatabase (code 1): , while compiling: SELECT _id, type, number FROM StatsDatabase
                  at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                  at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                  at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                  at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                  at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                  at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
                  at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
                  at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1318)
                  at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1165)
                  at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1036)
                  at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1204)
                  at com.example.kirill.myapplication.StatsDB.getAllStats(StatsDB.java:65)
                  at com.example.kirill.myapplication.StatsActivity.onCreate(StatsActivity.java:23)
                  at android.app.Activity.performCreate(Activity.java:6847)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2649)

它表示没有名称为StatsDatabase的数据库,但我正在对其进行实施MainActivity

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mapButton:
                Intent intentMap = new Intent(this, MapsActivity.class);
                startActivity(intentMap);
                break;
            case R.id.settingsButton:
                Intent intentSettings = new Intent(this, SettingsActivity.class);
                startActivity(intentSettings);
                break;
            case R.id.statsButton:
                Intent intentStats = new Intent(this, StatsActivity.class);
                startActivity(intentStats);
                break;
            default:
                break;
        }
    }

    Button mapBtn;
    Button statsBtn;
    Button settingsBtn;

    StatsDB stats;
    LocationsDB locations;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        stats = new StatsDB(this);
        locations = new LocationsDB(this);

        mapBtn = (Button) findViewById(R.id.mapButton);
        statsBtn = (Button) findViewById(R.id.statsButton);
        settingsBtn = (Button) findViewById(R.id.settingsButton);

        mapBtn.setOnClickListener(this);
        statsBtn.setOnClickListener(this);
        settingsBtn.setOnClickListener(this);
    }
}

StatsDB.java

package com.example.kirill.myapplication;

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

/**
 * Created by kirill on 21.11.17.
 */

public class StatsDB extends SQLiteOpenHelper {

    public static String DATABASE_STATS = "StatsDatabase";

    private static int VERSION = 1;

    public static final String FIELD_ROW_ID = "_id";

    public static final String FIELD_TYPE = "type";

    public static final String FIELD_NUMBER = "number";

    private static final String DATABASE_TABLE = "stats";

    private SQLiteDatabase statsDB;

    public StatsDB(Context context) {
        super(context, DATABASE_STATS, null, VERSION);
        statsDB = getWritableDatabase();
        ContentValues created = new ContentValues();
        ContentValues participated = new ContentValues();
        created.put(FIELD_TYPE, "Created");
        created.put(FIELD_NUMBER, "0");
        participated.put(FIELD_TYPE, "Participated");
        participated.put(FIELD_NUMBER, "0");

        statsDB.insert(DATABASE_TABLE, null, created);
        statsDB.insert(DATABASE_TABLE, null, participated);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql =     "create table " + DATABASE_TABLE + " ( " +
                FIELD_ROW_ID + " integer primary key autoincrement , " +
                FIELD_TYPE + " string , " +
                FIELD_NUMBER + " int " +
                " ) ";

        db.execSQL(sql);
    }

    public long insert(ContentValues contentValues){
        long rowID = statsDB.insert(DATABASE_TABLE, null, contentValues);
        return rowID;
    }

    public int del(){
        int cnt = statsDB.delete(DATABASE_TABLE, null , null);
        return cnt;
    }

    public Cursor getAllStats(){
        return statsDB.query(DATABASE_STATS, new String[] { FIELD_ROW_ID,  FIELD_TYPE , FIELD_NUMBER} , null, null, null, null, null);
    }

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


}

LocationsDB.java

package com.example.kirill.myapplication;

/**
 * Created by kirill on 21.11.17.
 */

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

public class LocationsDB extends SQLiteOpenHelper {

    /** Database name */
    private static String DATABASE_LOCATIONS = "locationmarkersqlite";

    /** Version number of the database */
    private static int VERSION = 1;

    /** Field 1 of the table locations, which is the primary key */
    public static final String FIELD_ROW_ID = "_id";

    /** Field 2 of the table locations, stores the latitude */
    public static final String FIELD_LAT = "lat";

    /** Field 3 of the table locations, stores the longitude*/
    public static final String FIELD_LNG = "lng";

    /** Field 4 of the table locations, stores the zoom level of map*/
    public static final String FIELD_ZOOM = "zom";

    /** A constant, stores the the table name */
    private static final String DATABASE_TABLE = "locations";

    /** An instance variable for SQLiteDatabase */
    private SQLiteDatabase mDB;

    /** Constructor */
    public LocationsDB(Context context) {
        super(context, DATABASE_LOCATIONS, null, VERSION);
        this.mDB = getWritableDatabase();
    }

    /** This is a callback method, invoked when the method getReadableDatabase() / getWritableDatabase() is called
     * provided the database does not exists
     * */
    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql =     "create table " + DATABASE_TABLE + " ( " +
                FIELD_ROW_ID + " integer primary key autoincrement , " +
                FIELD_LNG + " double , " +
                FIELD_LAT + " double , " +
                FIELD_ZOOM + " text " +
                " ) ";

        db.execSQL(sql);
    }

    /** Inserts a new location to the table locations */
    public long insert(ContentValues contentValues){
        long rowID = mDB.insert(DATABASE_TABLE, null, contentValues);
        return rowID;
    }

    /** Deletes all locations from the table */
    public int del(){
        int cnt = mDB.delete(DATABASE_TABLE, null , null);
        return cnt;
    }



    /** Returns all the locations from the table */
    public Cursor getAllLocations(){
        return mDB.query(DATABASE_TABLE, new String[] { FIELD_ROW_ID,  FIELD_LAT , FIELD_LNG, FIELD_ZOOM } , null, null, null, null, null);
    }

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

}

那么我在这种方法中做错了什么或者还有其他方法吗?

1 个答案:

答案 0 :(得分:2)

statsDB.query(DATABASE_STATS ...你需要在那里使用表,而不是数据库

您的错误告诉您no such table: StatsDatabase,这是真的。您创建的表名为stats