当前位置: 首页 > 知识库问答 >
问题:

如何从新插入的行中获取ID?

盛辰沛
2023-03-14

保存课程()应该启动验证导师()来创建和/或验证导师的当前输入信息是否可以添加到课程实体构造器中。mMentorViewModel.save导师(mMentor)应该通过Schuldler存储库,而Schuludler存储库使用数据库中的MentorDAO来插入新的导师。

我读过这个方法Android Room-使用auto generate获取新插入行的id,但是我缺少一些关于如何获取新创建的mentor信息的基本知识。

package com.example.wguscheduler.activities;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.example.wguscheduler.R;
import com.example.wguscheduler.entities.CourseEntity;
import com.example.wguscheduler.entities.MentorEntity;
import com.example.wguscheduler.entities.TermEntity;
import com.example.wguscheduler.viewmodel.CourseViewModel;
import com.example.wguscheduler.viewmodel.MentorViewModel;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class CourseAddActivity extends AppCompatActivity {

    private static final String TAG = "CourseAddActivity";
    private CourseViewModel mCourseViewModel;
    private MentorViewModel mMentorViewModel;
    private EditText mCourseTitle, mCourseStartDate, mCourseEndDate,mCourseNotes,
        mMentorFirstName, mMentorLastName, mMentorEmail, mMentorPhone;
    private MentorEntity mMentor;
    private Calendar mEndCalendar = Calendar.getInstance();
    private Calendar mStartCalendar = Calendar.getInstance();

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

        //initialize the tool bar
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        //initialize the view model
        mCourseViewModel = new ViewModelProvider(this).get(CourseViewModel.class);
        mMentorViewModel = new ViewModelProvider(this).get(MentorViewModel.class);

        //initialize EditText views
        mCourseTitle = findViewById(R.id.edit_course_add_title);
        mCourseStartDate = findViewById(R.id.edit_course_add_start);
        mCourseEndDate = findViewById(R.id.edit_course_add_end);
        mCourseNotes = findViewById(R.id.edit_course_add_notes);
        mMentorFirstName = findViewById(R.id.edit_mentor_add_first);
        mMentorLastName = findViewById(R.id.edit_mentor_add_last);
        mMentorEmail = findViewById(R.id.edit_mentor_add_email);
        mMentorPhone = findViewById(R.id.edit_mentor_add_phone);

        try {
            loadStartDatePicker();
            loadEndDatePicker();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    saveCourse();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void loadStartDatePicker() throws ParseException {
        DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                mStartCalendar.set(Calendar.YEAR, year);
                mStartCalendar.set(Calendar.MONTH, monthOfYear);
                mStartCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                updateStartLabel();

            }
        };

        mCourseStartDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new DatePickerDialog(CourseAddActivity.this,date, mStartCalendar.get(Calendar.YEAR), mStartCalendar.get(Calendar.MONTH),
                        mStartCalendar.get(Calendar.DAY_OF_MONTH)).show();
            }
        });
    }

    private void updateStartLabel() {
        String myFormat = "MM/dd/yyyy";
        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
        mCourseStartDate.setText(sdf.format(mStartCalendar.getTime()));

    }

    private void loadEndDatePicker() throws ParseException {
        DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                mEndCalendar.set(Calendar.YEAR, year);
                mEndCalendar.set(Calendar.MONTH, monthOfYear);
                mEndCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                updateEndLabel();
            }
        };

        mCourseEndDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new DatePickerDialog(CourseAddActivity.this,date, mEndCalendar.get(Calendar.YEAR), mEndCalendar.get(Calendar.MONTH),
                        mEndCalendar.get(Calendar.DAY_OF_MONTH)).show();

            }
        });
    }

    private void updateEndLabel() {
        String myFormat = "MM/dd/yyyy";
        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
        mCourseEndDate.setText(sdf.format(mEndCalendar.getTime()));
    }

    private void saveCourse() throws ParseException{

        SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
        verifyMentor();
        int termId = getIntent().getIntExtra("termId", 0);
        //int mentorId = mMentor.getId();
        String title = mCourseTitle.getText().toString();
        String status = "Plan to Take";
        Date start = formatter.parse(mCourseStartDate.getText().toString());
        Date end = formatter.parse(mCourseEndDate.getText().toString());
        String notes = mCourseNotes.getText().toString();

        CourseEntity course = new CourseEntity(termId, mMentor.getId(), title, status, start, end, notes);
        Log.d(TAG, "saveCourse: " + course.getCourse());
        mCourseViewModel.saveCourse(course);
        onSupportNavigateUp();
    }


    private void verifyMentor() {

        String first = mMentorFirstName.getText().toString();
        String last = mMentorLastName.getText().toString();
        String phone = mMentorPhone.getText().toString();
        String email = mMentorEmail.getText().toString();

        mMentor = new MentorEntity(first, last, phone, email);
        mMentorViewModel.saveMentor(mMentor);

    }

    // add support for going back a screen
    @Override
    public boolean onSupportNavigateUp(){
        onBackPressed();
        return true;
    }

}

package com.example.wguscheduler.entities;

import androidx.annotation.NonNull;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.PrimaryKey;

@Entity (tableName = "mentor_table")
public class MentorEntity {

    @PrimaryKey(autoGenerate = true)
    @NonNull
    @ColumnInfo(name = "id")
    private long mId;

    @ColumnInfo(name = "first_name")
    private String mFirstName;

    @ColumnInfo(name = "last_name")
    private String mLastName;

    @ColumnInfo(name = "phone")
    private String mPhone;

    @ColumnInfo(name = "email")
    private String mEmail;

    public MentorEntity(long mId, String mFirstName, String mLastName, String mPhone, String mEmail) {
        this.mId = mId;
        this.mFirstName = mFirstName;
        this.mLastName = mLastName;
        this.mPhone = mPhone;
        this.mEmail = mEmail;
    }

    @Ignore
    public MentorEntity(String mFirstName, String mLastName, String mPhone, String mEmail) {
        this.mId = this.mId;
        this.mFirstName = mFirstName;
        this.mLastName = mLastName;
        this.mPhone = mPhone;
        this.mEmail = mEmail;
    }

    public long  getId() {
        return mId;
    }

    public void setId(long mId) {
        this.mId = mId;
    }

    public String getFirstName() {
        return mFirstName;
    }

    public void setFirstName(String mFirstName) {
        this.mFirstName = mFirstName;
    }

    public String getLastName() {
        return mLastName;
    }

    public void setLastName(String mLastName) {
        this.mLastName = mLastName;
    }

    public String getPhone() {
        return mPhone;
    }

    public void setPhone(String mPhone) {
        this.mPhone = mPhone;
    }

    public String getEmail() {
        return mEmail;
    }

    public void setEmail(String mEmail) {
        this.mEmail = mEmail;
    }


    public String getMentor() {
        String mentor = String.format("\n" +
                        "\nMentorId: %s\n\r" +
                        "FirstName: %s\n\r" +
                        "LastName Id: %s\n\r" +
                        "Phone: %s\n\r" +
                        "Email: %s\n\r",
                        mId, mFirstName, mLastName, mPhone, mEmail);
        return mentor;
    }
}

package com.example.wguscheduler.dao;

import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Update;

import com.example.wguscheduler.entities.MentorEntity;

import java.util.List;

@Dao
public interface MentorDAO {

    //CREATE
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insertAll(List<MentorEntity> mentors);

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insert(MentorEntity mentor);

    //READ
    @Query("SELECT * FROM mentor_table")
    LiveData<List<MentorEntity>> getMentors();

    @Query("SELECT * FROM mentor_table WHERE id MATCH :mentorId")
    MentorEntity getMentor(long mentorId);

    //UPDATE
    @Update
    void update(MentorEntity mentor);

    //DELETE
    @Delete
    void delete(MentorEntity mentor);

}

package com.example.wguscheduler.viewmodel;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;

import com.example.wguscheduler.database.SchedulerRepository;
import com.example.wguscheduler.entities.MentorEntity;

import java.util.ArrayList;
import java.util.List;

public class MentorViewModel extends AndroidViewModel {

    private SchedulerRepository mSchedulerRepository;
    private LiveData<List<MentorEntity>> mAllMentors;

    public MentorViewModel(@NonNull Application application) {
        super(application);
        mSchedulerRepository = SchedulerRepository.getInstance(application.getApplicationContext());
        mAllMentors = mSchedulerRepository.getAllMentors();
    }

    public LiveData<List<MentorEntity>> getAllMentors(){
        return mAllMentors;
    }

    public void addSampleData(){
        mSchedulerRepository.addSampleData();
    }

    public void saveMentor(MentorEntity mMentor) {
        mSchedulerRepository.saveMentor(mMentor);
    }
}


package com.example.wguscheduler.database;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.TypeConverters;
import androidx.sqlite.db.SupportSQLiteDatabase;

import com.example.wguscheduler.dao.AssessmentDAO;
import com.example.wguscheduler.dao.CourseDAO;
import com.example.wguscheduler.dao.MentorDAO;
import com.example.wguscheduler.dao.TermDAO;
import com.example.wguscheduler.entities.AssessmentEntity;
import com.example.wguscheduler.entities.CourseEntity;
import com.example.wguscheduler.entities.MentorEntity;
import com.example.wguscheduler.entities.TermEntity;
import com.example.wguscheduler.utilities.Converters;

@Database(entities = {TermEntity.class,
        AssessmentEntity.class,
        CourseEntity.class,
        MentorEntity.class},
        version = 13)
@TypeConverters({Converters.class})
public abstract class SchedulerDatabase extends RoomDatabase {
    public abstract CourseDAO courseDAO();
    public abstract MentorDAO mentorDAO();
    public abstract TermDAO termDAO();
    public abstract AssessmentDAO assessmentDAO();

    private static volatile SchedulerDatabase INSTANCE;

    static SchedulerDatabase getDatabase(final Context context) {
        if (INSTANCE == null) {
            synchronized (SchedulerDatabase.class) {
                if (INSTANCE == null) {
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            SchedulerDatabase.class,
                            "scheduler_database")
                            .fallbackToDestructiveMigration()
                            .addCallback(sRoomDatabaseCallback)
                            .build();
                }
            }
        }
        return INSTANCE;
    }

    //open the database
    private static RoomDatabase.Callback sRoomDatabaseCallback = new RoomDatabase.Callback() {

        @Override
        public void onOpen(@NonNull SupportSQLiteDatabase db) {
            super.onOpen(db);

            //new PopulateSchedulerDatabase(INSTANCE).execute();
        }
    };
}

package com.example.wguscheduler.database;

import android.content.Context;
import android.util.Log;

import androidx.lifecycle.LiveData;

import com.example.wguscheduler.entities.AssessmentEntity;
import com.example.wguscheduler.entities.CourseEntity;
import com.example.wguscheduler.entities.MentorEntity;
import com.example.wguscheduler.entities.TermEntity;
import com.example.wguscheduler.utilities.CourseSampleData;
import com.example.wguscheduler.utilities.MentorSampleData;
import com.example.wguscheduler.utilities.TermSampleData;
import com.example.wguscheduler.utilities.AssessmentSampleData;

import java.text.ParseException;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class SchedulerRepository {

    private static final String TAG = "SchedulerRepository";
    private static SchedulerRepository mSchedulerRepository;

    //data lists
    private LiveData<List<TermEntity>> mAllTerms;
    private LiveData<List<CourseEntity>> mAllCourses;
    private LiveData<List<AssessmentEntity>> mAllAssessments;
    private LiveData<List<MentorEntity>> mAllMentors;

    private SchedulerDatabase mSchedulerDatabase;
    //executor to run only one thread, in order
    private Executor executor = Executors.newSingleThreadExecutor();

    //singleton creation of the scheduler repository
    public static SchedulerRepository getInstance(Context context){
        if(mSchedulerRepository == null){
            synchronized (SchedulerRepository.class) {
                if(mSchedulerRepository == null) {
                    mSchedulerRepository = new SchedulerRepository(context);
                }
            }
        }
        return mSchedulerRepository;
    }

    private SchedulerRepository(Context context){
        mSchedulerDatabase = SchedulerDatabase.getDatabase(context);
        mAllTerms = mSchedulerDatabase.termDAO().getTerms();
        mAllCourses = mSchedulerDatabase.courseDAO().getCourses();
        mAllAssessments = mSchedulerDatabase.assessmentDAO().getAssessments();
        mAllMentors = mSchedulerDatabase.mentorDAO().getMentors();
    }


    //CRUD

    //create
    public void saveTerm(TermEntity term){
        executor.execute(new Runnable() {
            @Override
            public void run() {
                mSchedulerDatabase.termDAO().insertTerm(term);
            }

        });
    }
    public void saveCourse(CourseEntity course) {

        executor.execute(new Runnable() {
            @Override
            public void run() {
                mSchedulerDatabase.courseDAO().insertCourse(course);
            }

        });
    }
    public void saveMentor(MentorEntity mMentor) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                mSchedulerDatabase.mentorDAO().insert(mMentor);
            }

        });
    }
    public void saveAssessment(AssessmentEntity assessment) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                mSchedulerDatabase.assessmentDAO().insert(assessment);
            }

        });
    }

    public void addSampleData() {

        executor.execute(new Runnable(){
            @Override
            public void run(){

                try {
                    mSchedulerDatabase.termDAO().insertAll(TermSampleData.getTerms());
                    mSchedulerDatabase.courseDAO().insertAll(CourseSampleData.getCourses());
                    mSchedulerDatabase.assessmentDAO().insertAll(AssessmentSampleData.getAssessments());
                    mSchedulerDatabase.mentorDAO().insertAll(MentorSampleData.getMentors());
                    Log.i(TAG, "addSampleData().run()" + CourseSampleData.getCourses());

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

    }

    //read
    public LiveData<List<TermEntity>> getAllTerms() {
        return mAllTerms;
    }
    public LiveData<List<CourseEntity>> getAllCourses(){ return mAllCourses;}
    public LiveData<List<AssessmentEntity>> getAllAssessments() {
        return mAllAssessments;
    }
    public LiveData<List<MentorEntity>> getAllMentors() {
        return mAllMentors;
    }

    //delete
    public void deleteTerm(int termId) {

        executor.execute(new Runnable() {
            @Override
            public void run() {
                mSchedulerDatabase.termDAO().deleteTerm(termId);
            }
        });

    }

    public void deleteCourse(int courseId) {
        executor.execute(new Runnable() {

            @Override
            public void run() {
                mSchedulerDatabase.courseDAO().deleteCourse(courseId);
            }
        });
    }

    public void deleteAssessment(int assessmentId) {
        executor.execute(new Runnable() {

            @Override
            public void run() {
                mSchedulerDatabase.assessmentDAO().deleteAssessment(assessmentId);
            }
        });
    }
}

共有1个答案

蓟辰沛
2023-03-14

您是否尝试过更改void insert(导师实体导师) 长插入(导师)

long insert(MentorEntity mentor); // this will return the row id


List<Long> insertAll(List<MentorEntity> mentors); // will return row ids created

 类似资料:
  • 问题内容: 我正在使用PHP中的mvc结构,我想检索最后插入的行ID。 我创建了以下sql代码: 但不幸的是我遇到了这个错误: 我也尝试过此堆栈链接,但不适用于我,因此如果您能帮助我获取ID,我将非常高兴。 我也在这里共享我的controller.php文件。 问题答案: 你快到了。 如果您查看lastInsertId的手册页,则会在数据库句柄上调用它- 您当前正在语句中对其进行调用。 您只需要致

  • 在下面的代码中,我得到。我读到,也可以直接从获取最后插入的行id。在我的代码中,我把空插入改为长,并尝试了许多其他的东西,就像我在互联网上找到的例子一样,但是每次我都会出错。你想给我提供一个代码/解决方案,从@插入获取行/用户ID吗? 实体 存储库 查看模型 片段/活动

  • 问题内容: 我使用此命令在两列表中插入一些单词: 如何获取每个单词插入行的ID(主键)。我的意思是执行后返回“ 55,56,57”之类的值。MySQL有这样的反应吗? 术语列是。如果一个术语已经存在,MySQL将不会插入它。是否可以返回该重复项的引用(即该术语所在行的ID)?像“55,A响应 12 ,56”。 问题答案: 您可以通过调用框架或MySQL库(使用任何语言)来获取它。 那行不通。插入后

  • 这是我的密码: 如您所知,它会在数据库中插入一个新行。现在我需要获取插入行的。我怎么能得到这个? 注意,我知道,如果我使用

  • 问题内容: 我有这样的UPSERT操作: 是一个复合主键,与“ people”表相比,“ people_update”表包含其他行和已更改的行。 我的问题是:有没有办法将查询的插入行和更新行作为返回行? 编辑:我通过添加一个子句中途解决了问题,但我也想在我的返回值中获取旧值。 问题答案: 如果将布尔更新的列添加到表中: 那么您可以通过在子句中进行设置来标识更新的行: 例如, 产量 该列显示和行已更

  • 问题内容: 如何在JDBC中获取插入ID? 问题答案: 如果它是自动生成的密钥,那么你可以使用它。你需要Statement使用与用于相同的名称进行调用INSERT。首先,你需要创建用于通知JDBC驱动程序以返回键的语句。 这是一个基本示例: 请注意,你是否依赖JDBC驱动程序。当前,大多数最新版本都可以使用,但是如果我没错,Oracle JDBC驱动程序仍然有些麻烦。MySQL和DB2已经支持它很