Исключение ActiveAndroid SQLite «Нет такой таблицы»

У меня проблема с активным андроидом. Я пытаюсь получить местоположение пользователя, количество пассажиров и общее направление. Я хочу сохранить их в памяти телефона в таблице под названием «Разделения», используя activeAndroid. Но всякий раз, когда я вызываю метод save(), я получаю длинный список ошибок. Я попытался переустановить приложение и изменить имя моей БД в манифесте, но ни одно из этих решений не сработало. Пожалуйста, имейте в виду, что я очень новичок в программировании, поэтому, если возможно, ведите себя так, как будто мне 5 лет. Спасибо :)

Вот вывод LogCat

11-03 23:27:51.094    2905-2905/dk.specialisering.splitcab E/SQLiteLog﹕ (1) no such table: Splits
11-03 23:27:51.115    2905-2905/dk.specialisering.splitcab E/SQLiteDatabase﹕ Error inserting passengers=1 Id=null startLong=9.92773733 direction=North startLat=57.0487396
    android.database.sqlite.SQLiteException: no such table: Splits (code 1): , while compiling: INSERT INTO Splits(passengers,Id,startLong,direction,startLat) VALUES (?,?,?,?,?)
            at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
            at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1118)
            at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:691)
            at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
            at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
            at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
            at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1589)
            at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1461)
            at com.activeandroid.Model.save(Model.java:153)
            at dk.specialisering.splitcab.MainActivity.save(MainActivity.java:127)
            at dk.specialisering.splitcab.MainActivity$1.onClick(MainActivity.java:37)
            at android.view.View.performClick(View.java:4475)
            at android.view.View$PerformClick.run(View.java:18786)
            at android.os.Handler.handleCallback(Handler.java:730)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5419)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
            at dalvik.system.NativeStart.main(Native Method)
11-03 23:27:51.175    2905-2905/dk.specialisering.splitcab E/SQLiteLog﹕ (1) no such table: Splits
11-03 23:27:51.175    2905-2905/dk.specialisering.splitcab E/SQLiteDatabase﹕ Error inserting passengers=1 Id=null startLong=9.92773733 direction=North startLat=57.0487396
    android.database.sqlite.SQLiteException: no such table: Splits (code 1): , while compiling: INSERT INTO Splits(passengers,Id,startLong,direction,startLat) VALUES (?,?,?,?,?)
            at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
            at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1118)
            at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:691)
            at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
            at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
            at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
            at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1589)
            at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1461)
            at com.activeandroid.Model.save(Model.java:153)
            at dk.specialisering.splitcab.MainActivity.save(MainActivity.java:127)
            at dk.specialisering.splitcab.MainActivity$1.onClick(MainActivity.java:37)
            at android.view.View.performClick(View.java:4475)
            at android.view.View$PerformClick.run(View.java:18786)
            at android.os.Handler.handleCallback(Handler.java:730)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5419)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
            at dalvik.system.NativeStart.main(Native Method)

Вот мой класс модели для таблицы

@Table(name = "Splits")
public class Splits extends Model {
    @Column(name = "startLat")
    public double startLat;
    @Column(name = "startLong")
    public double startLong;
    @Column(name = "passengers")
    public int passengers;
    @Column(name = "direction")
    public String direction;


    public Splits()
    {
        super();
    }

    public Splits(double startLat, double startLong, int passengers, String direction)
    {
        this.startLat = startLat;
        this.startLong = startLong;
        this.passengers = passengers;
        this.direction = direction;
    }

}

Моя активность

    package dk.specialisering.splitcab;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.Image;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;

import com.activeandroid.ActiveAndroid;

import dk.specialiserng.model.Splits;


public class MainActivity extends Activity {

    TextView textLat;
    TextView textLong;



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

        final ImageButton btn = (ImageButton)findViewById(R.id.imgBtn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save();
            }
        });
        ActiveAndroid.initialize(this);
        populateSpinners();
        initializeLocation();
    }
        private class myLocationListener implements LocationListener{
            @Override
            public void onLocationChanged(Location location) {

                if(location != null) {
                    double pLong = location.getLongitude();
                    double pLat = location.getLatitude();

                    textLat.setText(Double.toString(pLat));
                    textLong.setText((Double.toString(pLong)));
                }

            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        }


    public void populateSpinners()
    {
        Spinner passengerSpinner = (Spinner) findViewById(R.id.ddlPassengers);

        Spinner directionSpinner = (Spinner) findViewById(R.id.ddlDirection);
// Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> passengerAdapter = ArrayAdapter.createFromResource(this,
                R.array.noOfPassengers, android.R.layout.simple_spinner_item);

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.splitDirection, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
        passengerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
        passengerSpinner.setAdapter(passengerAdapter);

        directionSpinner.setAdapter(adapter);


    }

    public void initializeLocation()
    {

        textLat = (TextView) findViewById(R.id.textLat);
        textLong = (TextView) findViewById(R.id.textLong);

        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        LocationListener ll = new myLocationListener();
        Location lastLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
        if (lastLocation != null)
        {
            textLat.setText(Double.toString(lastLocation.getLatitude()));
            textLong.setText(Double.toString(lastLocation.getLongitude()));
        }
    }

    public void save()
    {
        Spinner pasSpin = (Spinner)findViewById(R.id.ddlPassengers);
        Spinner dirSpin = (Spinner)findViewById(R.id.ddlDirection);
        double latitude = Double.parseDouble(textLat.getText().toString());
        double longitude = Double.parseDouble(textLong.getText().toString());
        int passengers = Integer.parseInt(pasSpin.getSelectedItem().toString());
        String direction = dirSpin.getSelectedItem().toString();

        Splits splits = new Splits(latitude, longitude, passengers, direction);

        splits.save();


    }

    }

Мой макет

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Your Position in latitude and longitude"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:id="@+id/textLat"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignRight="@+id/textView"
        android:layout_alignEnd="@+id/textView" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:id="@+id/textLong"
        android:layout_below="@+id/textLat"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignRight="@+id/textLat"
        android:layout_alignEnd="@+id/textLat" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Number of Splitters in your party"
        android:id="@+id/textView2"
        android:layout_below="@+id/textLong"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <Spinner
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/ddlPassengers"
        android:layout_below="@+id/textView2"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:spinnerMode="dropdown" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="The direction you will be going"
        android:id="@+id/textView3"
        android:layout_below="@+id/ddlPassengers"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Spinner
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/ddlDirection"
        android:layout_below="@+id/textView3"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:spinnerMode="dropdown" />

    <ImageButton
        android:layout_width="200dp"
        android:layout_height="90dp"
        android:scaleType="fitCenter"
        android:id="@+id/imgBtn"
        android:src="@drawable/gotitbtn"
        android:background="@android:color/transparent"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"

        />

</RelativeLayout>

Я надеюсь, что кто-то может помочь, я знаю, что разместил кучу, но я впадаю в отчаяние в этот момент. заранее спасибо


person Matt Baech    schedule 03.11.2014    source источник


Ответы (6)


хотя поздно, надеюсь, что это поможет.

с официальной страницы ActiveAndroid в github:

«Это связано с тем, что ActiveAndroid создает схему только в том случае, если нет существующего файла базы данных. Чтобы «регенерировать» схему после создания новой модели, проще всего удалить приложение из эмулятора и разрешить его полную повторную установку. Это связано с тем, что это очищает файл базы данных и запускает ActiveAndroid для повторного создания таблиц на основе аннотированных моделей в проекте».

person mehdi    schedule 03.06.2015
comment
Да, это правда, хотя вы можете (и я думаю, должны) использовать ‹meta-data android:name=AA_DB_VERSION android:value=X /› в манифесте (как предлагает документация) и увеличивать X, когда вы хотите воссоздать базу данных AA (по умолчанию X = 1). - person Arthez; 10.02.2016
comment
uninstall the app from the emulator and allow it to be fully re-installed работает.. Спасибо.. - person Shailendra Madda; 22.02.2016
comment
это может быть проблемой, если у вас уже есть приложение, которое использует 1 таблицу, и при отправке обновления оно просто выйдет из строя и сгорит. Возможно, стоит просто использовать обновление aa_db_version, как предложил Стивен. - person ; 05.02.2020

Увеличьте AA_DB_VERSION в своем манифесте. Это заставит ActiveAndroid регенерировать вашу схему.

person Steven    schedule 15.09.2015
comment
Точно, эта штука мне помогла, хотя в документации это и предлагают. - person Arthez; 10.02.2016

кажется, вы забыли вызвать super() в своем классе модели в функции конструктора:

public Splits(double startLat, double startLong, int passengers, String direction)
{
    super();
    this.startLat = startLat;
    this.startLong = startLong;
    this.passengers = passengers;
    this.direction = direction;
}

Другая возможность заключается в том, что вы не объявили свой класс модели в файле манифеста.

person Eduardo    schedule 18.03.2015
comment
Если конструктор явно не вызывает конструктор суперкласса, компилятор Java автоматически вставляет вызов конструктору суперкласса без аргументов. docs.oracle.com/javase/tutorial/java/IandI/super. html Кроме того: ActiveAndroid просматривает все ваши файлы, чтобы найти ваши классы модели. - person nasch; 21.10.2015

Кажется, что в вашей базе данных нет таблицы с названием Splits. Если вы внесли изменения в свою базу данных и тестируете свое приложение на одном реальном устройстве (не в эмуляторе), вам потребуется удалить приложение с устройства (или, по крайней мере, его данные), чтобы обновить базу данных. Надеюсь поможет =)

person Luciano Rodríguez    schedule 03.11.2014
comment
Как указано в вопросе, я уже пробовал это. Не повезло там. Я думал, что мой класс Model создаст для меня таблицу? Или я неправильно набрал активандроид - person Matt Baech; 04.11.2014
comment
Это ЕЩЕ ОДНА из тех вещей, которые работают на эмуляторе, но не на устройстве. - person Captain Kenpachi; 07.12.2016

Вероятно, вы неправильно настроили ActiveAndroid. Ознакомьтесь с этим руководством в разделе "Часто задаваемые вопросы".

person x0z    schedule 05.11.2014

Этот код инициализации:

    ActiveAndroid.initialize(this);

переходит в класс Application. Таким образом, вы можете расширить класс Application и использовать его инициализацию в OnCreate. Нравиться

public class MyApplication extends Application{
    @Override
    public void onCreate() {
        super.onCreate();
        ActiveAndroid.initialize(this);
    }
}

Убедитесь, что вы используете этот класс приложения в AndroidManifest.xml в качестве своего приложения. т.е.,

<application android:name="com.exampleapp.MyApplication" ...>

См.: https://github.com/pardom/ActiveAndroid/wiki/Getting-started

person Niranjan    schedule 07.11.2014