与数据库没有连接?

时间:2019-06-24 17:35:03

标签: java database android-studio authentication android-room

我是Android Studio的新手,并且正在通过登录和注册创建一个项目。我正在使用会议室技术,但在Internet上进行了搜索,但找不到为什么无法访问数据库。尽管我调用数据库并且它具有后台的数据,但是当我尝试读取它时却发现它是空的。请帮助我不知道该怎么办!谢谢!!

我的DAO文件

package com.example.myapplicationversion2;

import android.arch.lifecycle.LiveData;
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 android.arch.persistence.room.Update;

import com.example.myapplicationversion2.User;

import java.util.List;

@Dao
public interface DAO {

    @Insert
    void insert(User user);

    @Update
    void update(User user);

    @Delete
    void delete(User user);

    @Query( "SELECT * from user where username=:username and password=:password" )
    User checkUser(String username,String password);

    @Query( "SELECT * FROM user order by user_id asc" )
    LiveData<List<User>> getAllUsers();
    @Query( "SELECT * FROM user order by user_id asc" )
    List<User> getUserNotLive();

}

MY DATABASE.class

package com.example.myapplicationversion2;

import android.arch.persistence.db.SupportSQLiteDatabase;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.content.Context;
import android.os.AsyncTask;
import android.support.annotation.NonNull;

@android.arch.persistence.room.Database( entities = {User.class,Questions.class,Users_Questions.class}, version = 1,exportSchema = false)
public abstract class Database extends RoomDatabase {
    private static Database instance;

    public abstract DAO userDAO();

    public abstract QuestionsDAO questionsDAO();
    public abstract Users_questionsDAO users_questionsDAO();


    public static synchronized Database getInstance(Context context){
        if (instance==null){
            instance= Room.databaseBuilder(context.getApplicationContext(),Database.class,"database.db")
                    .fallbackToDestructiveMigration()
                    .addCallback( roomCallBack )
                    .allowMainThreadQueries()
                    .build();
        }
        return instance;
    }

    private static RoomDatabase.Callback roomCallBack=new RoomDatabase.Callback(){
        @Override
        public void onCreate(@NonNull SupportSQLiteDatabase db) {
            super.onCreate( db );
            new PopulateDBAsyncTask( instance ).execute(  );
        }
    };

    private static class PopulateDBAsyncTask extends AsyncTask<Void,Void,Void>{
        private DAO DAO;
        private QuestionsDAO qDAO;

        private PopulateDBAsyncTask(Database db){
            DAO =db.userDAO();
            qDAO =db.questionsDAO();

        }


        @Override
        protected Void doInBackground(Void... voids) {
            DAO.insert( new User("Vangelis","vakiskor@yahoo.gr","vakiskor","1234","Admin") );
            DAO.insert( new User("John","john@yahoo.gr","john","1234","User") );
            DAO.insert( new User("Administrator","admin@yahoo.gr","admin","admin","Admin") );
            qDAO.insert( new Questions( "Πως αξιολογείτε την μεταδοτικότητα του Καθηγητή;" ) );
            qDAO.insert( new Questions( "Πόσο ενδιαφέρον βρίσκετε το συγκεκριμένο μάθημα;" ) );
            qDAO.insert( new Questions( "Πως αξιολογείτε το γνωστικό επίπεδο των υπολοίπων συμφοιτητών σας;" ) );
            return null;
        }
    }
}

我的LOGIN.class

package com.example.myapplicationversion2;


import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.content.Intent;
import android.os.Handler;
import android.provider.ContactsContract;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.util.List;

public class Login extends AppCompatActivity implements View.OnClickListener {
    public static final String EXTRA_USERNAME="com.example.myapplicationversion2.EXTRA_USERNAME";
    public static final String EXTRA_PASSWORD="com.example.myapplicationversion2.EXTRA_PASSWORD";

    private static int user_id;
    private EditText editTextUsername,editTextPassword;

    private NestedScrollView nestedScrollView;


    private AppCompatButton appCompatButtonLogin;

    private AppCompatTextView textViewLinkRegister;
    private DAO checkUser;
    private DAO userDao;
    private Database database;

    User user;

    //private ViewModel viewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_login );
        database=Database.getInstance( this );

        //database=Room.databaseBuilder( this, Database.getInstance( this),"database.db").allowMainThreadQueries().build();
        database= Room.databaseBuilder( this,Database.class,"database.db" ).fallbackToDestructiveMigration().allowMainThreadQueries().build();
        nestedScrollView=findViewById( R.id.nestedScrollView );
        editTextUsername=findViewById( R.id.textInputEditTextUsername );
        editTextPassword=findViewById( R.id.textInputEditTextPassword );
        userDao=database.userDAO();

        appCompatButtonLogin = (AppCompatButton) findViewById(R.id.appCompatButtonLogin);

        textViewLinkRegister = (AppCompatTextView) findViewById(R.id.textViewLinkRegister);

        appCompatButtonLogin.setOnClickListener(this );
        textViewLinkRegister.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.appCompatButtonLogin:
                user_id = v.getId();
                login();
                break;
            case R.id.textViewLinkRegister:
                Intent intentRegister=new Intent(getApplicationContext(),RegisterExistingUser.class);
                startActivity( intentRegister );
                break;
        }
    }

    private void login() {
        if ( !emptyValidation()){

            new Handler().postDelayed( new Runnable() {
                @Override
                public void run() {
                    System.out.println( "====================================" );
                    List<User> list=userDao.getUserNotLive();

                    for (User tmp:list){
                        System.out.print( tmp.getUsername()+tmp.getPassword() );
                    }
                    System.out.println( "====================================" );

                    System.out.println ( "***" + editTextUsername.getText().toString() + editTextPassword.getText().toString() );

                    User user = userDao.checkUser( editTextUsername.getText().toString().trim(), editTextPassword.getText().toString().trim() );
                    if (user != null) {
                        if (user.getSpecialty().trim().equals( "Admin" ) || user.getSpecialty().equals( "admin" ) || user.getSpecialty().equals( "ADMIN" )) {
                            Intent accountIntent = new Intent( Login.this, AdminChoices.class );
                            startActivity( accountIntent );
                            emptyInputEditText();
                        } else {
                            Intent accountIntent = new Intent( Login.this, UsersQuestionsActivity.class );
                            startActivity( accountIntent );
                            emptyInputEditText();
                        }
                    }
                    else {
                        Toast.makeText( Login.this, "Μη εγκεκριμένος χρήστης", Toast.LENGTH_LONG).show();
                    }
                }
            },1000);
        }


        else{
            Snackbar.make( nestedScrollView,getString(R.string.error_valid_username_password ),Snackbar.LENGTH_LONG ).show();
        }
    }

    private boolean emptyValidation() {
        if (TextUtils.isEmpty( editTextUsername.getText().toString() )||TextUtils.isEmpty( editTextPassword.getText().toString() )) {
            return true;
        } else{
            return false;
        }

    }


    private void emptyInputEditText() {
        editTextUsername.setText( null );
        editTextPassword.setText( null );
    }

    public static int getUser_id()
    {
        return user_id;
    }
}

1 个答案:

答案 0 :(得分:0)

在完全创建数据之前,您可能试图将数据插入数据库。 您应该先确保数据库已完成构建。

我认为您可以做的是将AsyncTask替换为EXECUTOR,并删除.allowMainThreadQueries()调用以确保您不在主线程上运行。 我没有测试它,但我认为它应该可以工作。

public static synchronized Database getInstance(Context context){
        if (instance==null){
            instance= Room.databaseBuilder(context.getApplicationContext(),Database.class,"database.db")
                    .fallbackToDestructiveMigration()
                    .addCallback( new Callback() {
                    @Override
                    public void onCreate(@NonNull SupportSQLiteDatabase db) {
                        super.onCreate(db);
                        Executors.newSingleThreadScheduledExecutor().execute(new Runnable() {
                            @Override
                            public void run() {
                                DAO dao =getInstance(context).userDAO();
                                QuestionsDAO qDAO = getInstance(context).questionsDAO();
                                DAO.insert( new User("Vangelis","vakiskor@yahoo.gr","vakiskor","1234","Admin") );
                                DAO.insert( new User("John","john@yahoo.gr","john","1234","User") );
                                DAO.insert( new User("Administrator","admin@yahoo.gr","admin","admin","Admin") );
                                qDAO.insert( new Questions( "Πως αξιολογείτε την μεταδοτικότητα του Καθηγητή;" ) );
                                qDAO.insert( new Questions( "Πόσο ενδιαφέρον βρίσκετε το συγκεκριμένο μάθημα;" ) );
                                qDAO.insert( new Questions( "Πως αξιολογείτε το γνωστικό επίπεδο των υπολοίπων συμφοιτητών σας;" ) );
                            }
                        });
                    }
                    })
                    .build();
        }
        return instance;
    }