web-dev-qa-db-ja.com

部屋のインスタンスを取得する際の問題-データベース

残念ながら、AndroidプロジェクトのRoom-Databaseのインスタンスを取得する際に大きな問題が発生しました。 https://developer.Android.com/training/data)の指示に従いました。 -storage/room/index.html しかし、最後のステップは私にはうまくいきません:

AppDatabase db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "database-name").build();

彼らのAppDatabase.Javaは次のようになります

@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}

私の問題: "AppDatabase db"でエラーが発生しました 'シンボルを解決できません "AppDatabase "'。 AppDatabaseは単なる抽象クラスであるため、これは非常に意味があります。しかし、これはチュートリアルでどのように機能するはずですか? MainActivityのonCreateメソッドでインスタンスを取得しようとしました。これが私のgradlefilesです:buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.Android.tools.build:gradle:3.0.0'
       // NOTE: Do not place your application dependencies here; they belong
      // in the individual module build.gradle files
    }
}

ext {
    buildToolsVersion = "25.0.2"
    supportLibVersion = "25.3.1"
    archRoomVersion = "1.0.0-alpha1"
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://maven.google.com' }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

そして2番目のもの:

apply plugin: 'com.Android.application'

Android {
compileSdkVersion 26
defaultConfig {
    applicationId "com.example.fabian.kohlmannkonstruktionen"
    minSdkVersion 15
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner 
"Android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-Android.txt'), 
'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.Android.support:appcompat-v7:26.1.0'
implementation 'com.Android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.Android.support.test:runner:1.0.1'
androidTestImplementation 'com.Android.support.test.espresso:espresso-
core:3.0.1'
compile 'Android.Arch.persistence.room:runtime:' + 
rootProject.archRoomVersion
annotationProcessor 'Android.Arch.persistence.room:compiler:' + 
rootProject.archRoomVersion

}

MainActivity.Java

package com.example.fabian.kohlmannkonstruktionen;

import Android.app.AlertDialog;
import Android.content.DialogInterface;

import Android.content.Intent;
import Android.support.v7.app.AppCompatActivity;
import Android.os.Bundle;
import Android.view.View;
import Android.widget.ArrayAdapter;
import Android.Arch.persistence.db.SupportSQLiteDatabase;
import Android.Arch.persistence.room.Database;
import Android.Arch.persistence.room.Room;
import Android.Arch.persistence.room.RoomDatabase;
import Android.Arch.persistence.room.migration.Migration;
import Android.content.Context;


public class MainActivity extends AppCompatActivity {

AppDatabase db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    db = AppDatabase.getInMemoryDatabase(getApplicationContext());
}
...

AppDatabase.Java

package com.example.fabian.kohlmannkonstruktionen;

import Android.app.AlertDialog;
import Android.content.DialogInterface;
import Android.content.Intent;
import Android.support.v7.app.AppCompatActivity;
import Android.os.Bundle;
import Android.view.View;
import Android.widget.ArrayAdapter;
import Android.Arch.persistence.db.SupportSQLiteDatabase;
import Android.Arch.persistence.room.Database;
import Android.Arch.persistence.room.Room;
import Android.Arch.persistence.room.RoomDatabase;
import Android.Arch.persistence.room.migration.Migration;
import Android.content.Context;


public class MainActivity extends AppCompatActivity {
    AppDatabase db;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        db = AppDatabase.getInMemoryDatabase(getApplicationContext());
}

Projekt.Java

import Android.Arch.persistence.room.Entity;
import Android.Arch.persistence.room.PrimaryKey;

/**
 * Created by Fabian on 14.11.2017.
 */
@Entity
public class Projekt {
    @PrimaryKey(autoGenerate = true)
    Integer id;

    Integer projektnummer;
    Integer lohn,arbeitszeit;
    String projektname, firma;
    Boolean abgeschlossen;
    public Projekt(String projektname,String firma,Integer projektnummer){
        this.abgeschlossen=false;
        this.projektname=projektname;
        this.projektnummer=projektnummer;
        this.firma=firma;
    }
...getters and setters...

ProjektDao.Java

import Android.Arch.persistence.room.Dao;
import Android.Arch.persistence.room.Delete;
import Android.Arch.persistence.room.Insert;
import Android.Arch.persistence.room.Query;

import Java.util.List;

/**
 * Created by Fabian on 15.11.2017.
 */
@Dao
public interface ProjektDao {
    @Query("SELECT * FROM Projekt")
    List<Projekt> getAll();

    @Query("SELECT * FROM Projekt where id LIKE  :id")
    Projekt findByID(String id);

    @Query("SELECT COUNT(*) from Projekt")
    int countUsers();

    @Insert
    void insertAll(Projekt... projekts);

    @Delete
    void delete(Projekt projekt);
}

TerminとTerminDaoは同じように見えます

これは、gradleコンソールからのテキストです。

Executing tasks: [assemble]

Configuration on demand is an incubating feature.
Configuration 'compile' in project ':app' is deprecated. Use 'implementation' instead.
:app:compileDebugJavaWithJavac
C:\Users\Fabian\AndroidStudioProjects\KohlmannKonstruktionen\app\src\main\Java\TerminDao.Java:14: warning: The query returns some columns [pausenzeit, startzeit, endzeit, lohnproh, mitarbeiter, standort] which are not use by Projekt. You can use @ColumnInfo annotation on the fields to specify the mapping. Projekt has some fields [projektnummer, lohn, arbeitszeit, projektname, firma, abgeschlossen] which are not returned by the query. If they are not supposed to be read from the result, you can mark them with @Ignore annotation. You can suppress this warning by annotating the method with @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH). Columns returned by the query: id, pausenzeit, startzeit, endzeit, lohnproh, mitarbeiter, standort. Fields in Projekt: id, projektnummer, lohn, arbeitszeit, projektname, firma, abgeschlossen.
    List<Projekt> getAll();
                  ^
C:\Users\Fabian\AndroidStudioProjects\KohlmannKonstruktionen\app\src\main\Java\AppDatabase.Java:13: warning: Schema export directory is not provided to the annotation processor so we cannot export the schema. You can either provide `room.schemaLocation` annotation processor argument OR set exportSchema to false.
public abstract class AppDatabase extends RoomDatabase {
                ^
C:\Users\Fabian\AndroidStudioProjects\KohlmannKonstruktionen\app\src\main\Java\com\example\fabian\kohlmannkonstruktionen\MainActivity.Java:13: error: cannot find symbol
    AppDatabase db = AppDatabase.getInMemoryDatabase(getApplicationContext());
    ^
  symbol:   class AppDatabase
  location: class MainActivity
1 error
2 warnings

 FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 5s

14 actionable tasks: 1 executed, 13 up-to-date
5
Fabi

ぼくの AppDatabase.classはあなたのものとは少し異なります:

...
INSTANCE = Room.databaseBuilder(context, AppDatabase.class, "xxx")
                    // To simplify the codelab, allow queries on the main thread.
                    // Don't do this on a real app! See PersistenceBasicSample for an example.
                    .allowMainThreadQueries()
                    .build();
...

と私 build.gradleにはlifecycleも含まれます。

// for room
compile 'Android.Arch.lifecycle:extensions:1.0.0';
compile 'Android.Arch.persistence.room:runtime:1.0.0';
annotationProcessor 'Android.Arch.lifecycle:compiler:1.0.0';
annotationProcessor 'Android.Arch.persistence.room:compiler:1.0.0';
5
YBrush

あなたを助けるかもしれない私のコードをチェックしてください。

AppDatabase.Java

@Database(entities = {Product.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {

    private static AppDatabase INSTANCE;

    public abstract ProductDao productDao();

    public static AppDatabase getInMemoryDatabase(Context context) {
        if (INSTANCE == null) {
            INSTANCE =
                    Room.inMemoryDatabaseBuilder(context.getApplicationContext(), AppDatabase.class).allowMainThreadQueries().build();
        }
        return INSTANCE;
    }

    public static void destroyInstance() {
        INSTANCE = null;
    }
}

Mainactivity.Java

AppDatabase db = AppDatabase.getInMemoryDatabase(getApplicationContext());

Build.Gradle(プロジェクト)

allprojects {
    repositories {
        jcenter()
        maven { url 'https://maven.google.com' }
    }
}

Build.Gradle(App)

// Room
compile 'Android.Arch.persistence.room:runtime:1.0.0'
annotationProcessor 'Android.Arch.persistence.room:compiler:1.0.0'

これにより、インスタンスが1つだけ作成されます。これは私のコードではうまく機能します。

3
Samir Bhatt

私にとっては、コピー/貼り付けの場合でした。

@PrimaryKeyなどを再入力して、Android Studioはそれらを使用していることを認識します。または、IDEはテキストとして扱います。

0
joeskru