如何在房间数据库中使用多项选择 [英] How to use Multiple Selection with Room Database

查看:54
本文介绍了如何在房间数据库中使用多项选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将交易链接到成员,就像将交易ID链接到许多成员ID一样?

How can I link the transaction to the member, like link a transaction id to many member ids?

我有一个活动来创建新交易,在该活动中,我输入交易的名称并有一个要插入的按钮.单击该按钮后,我想查看成员列表.

I have an activity to create new transaction, in that activity I enter the name of the transaction and have a button to insert. After I click on that button, I want to see the list of members.

然后,我要选择要链接到事务的成员.通过单击每个成员,它应该在我选择的成员旁边显示一个勾号或其他内容,或者应将单击的成员设置为不同的颜色.

Then I want to choose the members I want to link to the transaction. By clicking on every member, it should show me a tick or something next to the member I chose or it should set the clicked members in a different colour.

然后,应在事务中插入我选择的所有链接成员.

Then the transaction should be inserted with all the linked members I chose.

我现在是这样做的,我只是进行一个新交易,单击它,使用选定的交易开始一个新的活动,然后在工具栏中单击一个按钮以启动另一个我应该能够进行的活动选择我要与交易关联的成员.

I did it like this for now, that I just make a new transaction, click on it, start a new activity with the chosen transaction, then in the toolbar I click on a button to start another activity where I should be able to choose the members I want to link with the transaction.

是否可以通过新交易活动选择要直接链接到交易的成员?还是可以进行新交易,当我单击按钮保存新交易时,它将记录插入数据库中,并在插入后立即开始选择链接到该交易的成员的活动?

Is it possible to choose the members I want to link to the transaction directly with the new transaction activity? Or is it possible to make a new transaction and when I click on the button to save the new transaction, it inserts the record into the database and directly after insert, the activity where I choose the members to link to the transaction starts?

关于我的删除方法:我已经在onSwipe方法中实现了该方法.我该如何做才能单击多个具有勾号或不同颜色的交易,然后一次将其全部删除?

Also regarding my delete method: I have the method implemented in a onSwipe method. How can I do so that I can click on multiple transactions, they have a tick or a different colour, and delete them all at the same time?

我可以单击一个按钮(例如,在工具栏中)以删除,然后选择多个成员,单击确认删除"按钮,出现确认屏幕(但尚未删除),并在接受确认屏幕之后,删除它们?

I can click on a button (e.g. in the toolbar) to delete, then choose multiple members, click on a "confirm delete" button, let a confirmation screen appear (but not deleting yet), and after accepting the confirmation screen, delete them?

集体交易:

@Entity(tableName = "transaction_table")
public class Transaction {

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

@ColumnInfo(name = "Transaction Name")
private String transactionName;

@ColumnInfo(name = "Transaction Balance")
private double balance;

public double getBalance() {
    return balance;
}

public void setBalance(double balance) {
    this.balance = balance;
}

public long getId() {
    return id;
}

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

public String getTransactionName() {
    return transactionName;
}

public void setTransactionName(String transactionName) {
    this.transactionName = transactionName;
}

public Transaction(String transactionName, double balance) {
    this.transactionName = transactionName;
    this.balance = balance;
}

}

班级成员:

@Entity(tableName = "member_table")
public class Member {


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

@ColumnInfo(name = "First Name")
private String firstname;

@ColumnInfo(name = "Surname")
private String surname;

@ColumnInfo(name = "Balance")
private double balance;

public String getFirstname() {
    return firstname;
}

public void setFirstname(String firstname) {
    this.firstname = firstname;
}

public String getSurname() {
    return surname;
}

public void setSurname(String surname) {
    this.surname = surname;
}

public double getBalance() {
    return balance;
}

public void setBalance(double balance) {
    this.balance = balance;
}

public long getId() {
    return id;
}

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

public Member(String firstname, String surname) {
    this.firstname = firstname;
    this.surname = surname;
    this.balance = 0;
}

}

分类交易的主要活动:

public class TransactionMainActivity extends AppCompatActivity implements TransactionListAdapter.TransactionClickListener {

private TransactionViewModel mTransactionViewModel;
private List<Transaction> mTransaction;

public static final int NEW_TRANSACTION_ACTIVITY_REQUEST_CODE = 1;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.transaction_activity);
    Toolbar toolbar = findViewById(R.id.toolbar_TransactionMainActivity);
    setSupportActionBar(toolbar);
    if (getSupportActionBar() != null) {
        getSupportActionBar().setTitle(R.string.Transaction);
    }

    FloatingActionButton fab = findViewById(R.id.fab_TransactionMainActivity);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(TransactionMainActivity.this, NewTransactionActivity.class);
            startActivityForResult(intent, NEW_TRANSACTION_ACTIVITY_REQUEST_CODE);
        }
    });

    RecyclerView recyclerView = findViewById(R.id.RecyclerViewCard_Transaction);
    final TransactionListAdapter adapter = new TransactionListAdapter(this);
    recyclerView.setAdapter(adapter);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    mTransactionViewModel = ViewModelProviders.of(this).get(TransactionViewModel.class);

    mTransactionViewModel.getAllTransactions().observe(this, new Observer<List<Transaction>>() {
        @Override
        public void onChanged(@Nullable List<Transaction> transactions) {
            mTransaction = transactions;
            adapter.setTransaction(transactions);
        }
    });

    ItemTouchHelper helper = new ItemTouchHelper(
            new ItemTouchHelper.SimpleCallback(0,
                    ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
                @Override
                public boolean onMove(RecyclerView recyclerView,
                                      RecyclerView.ViewHolder viewHolder,
                                      RecyclerView.ViewHolder target) {
                    return false;
                }

                @Override
                public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                    int position = viewHolder.getAdapterPosition();
                    Transaction myTransaction = adapter.getTransactionAtPosition(position);
                    Toast.makeText(TransactionMainActivity.this,
                            getString(R.string.TransactionDeleted) + " " +
                                    myTransaction.getTransactionName(), Toast.LENGTH_LONG).show();

                    mTransactionViewModel.delete(myTransaction);
                }
            });
    helper.attachToRecyclerView(recyclerView);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.MainMenuToolbarSearch:

        case R.id.MainMenuToolbarAdd:

        case R.id.MainMenuToolbarDelete:

    }
    return super.onOptionsItemSelected(item);
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == NEW_TRANSACTION_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
        Transaction transaction = new Transaction(data.getStringExtra(NewTransactionActivity.EXTRA_REPLY), data.getDoubleExtra(NewTransactionActivity.EXTRA_REPLY2, -1));
        mTransactionViewModel.insert(transaction);
    } else

    {
        Toast.makeText(
                getApplicationContext(),
                R.string.transaction_not_saved,
                Toast.LENGTH_LONG).show();
    }
}

分类新交易活动:

public class NewTransactionActivity extends AppCompatActivity {

public static final String EXTRA_REPLY = "com.example.android.transactionlistsql.REPLY";
public static final String EXTRA_REPLY2 = "com.example.android.transactionlistsql.REPLY2";

private EditText mEditTextTransaction;
private EditText mEditTextTransaction2;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.newtransaction_activity);
    mEditTextTransaction = findViewById(R.id.NewTransactionName);
    mEditTextTransaction2 = findViewById(R.id.NewTransactionBalance);
    mEditTextTransaction2.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
    mEditTextTransaction2.setText("0");
    final Button button = findViewById(R.id.NewTransactionButtonSave);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent replyIntent = new Intent();
            if (TextUtils.isEmpty(mEditTextTransaction.getText())){
                Toast.makeText(getApplicationContext(), R.string.TransactionNameMissing, Toast.LENGTH_LONG).show();
                return;
            }
            else if (TextUtils.isEmpty(mEditTextTransaction2.getText())){
                mEditTextTransaction2.setText("0");
            }
            else {                 
                String newtransactionname = mEditTextTransaction.getText().toString();
                double newtransactionbalance = (Double.parseDouble(mEditTextTransaction2.getText().toString()));
                replyIntent.putExtra(EXTRA_REPLY, newtransactionname);
                replyIntent.putExtra(EXTRA_REPLY2, newtransactionbalance);
                setResult(RESULT_OK, replyIntent);
            }
            finish();
        }
    });
}
}

我的AsyncTask插入方法:

My AsyncTask for insert method:

    private static class insertAsyncTask extends AsyncTask<Transaction, Void, Void> {

    private TransactionDao mAsyncTaskDao;

    insertAsyncTask(TransactionDao dao) {
        mAsyncTaskDao = dao;
    }

    @Override
    protected Void doInBackground(final Transaction... params) {
        mAsyncTaskDao.insert(params[0]);
        return null;
    }
}

标记为错误的行是这一行:mAsyncTaskDao.insert(params [0]);

The line marked as error is this one: mAsyncTaskDao.insert(params[0]);

错误:

07-11 03:10:49.003 16307-16508/com.example.mainbuchhaltung E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #4

Process: com.example.mainbuchhaltung, PID: 16307

java.lang.RuntimeException: An error occurred while executing doInBackground()

    at android.os.AsyncTask$3.done(AsyncTask.java:309)
    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
    at java.lang.Thread.run(Thread.java:818)
 Caused by: android.database.sqlite.SQLiteConstraintException: FOREIGN KEY constraint failed (code 787)
#################################################################
Error Code : 787 (SQLITE_CONSTRAINT_FOEIGNKEY)
Caused By : Abort due to constraint violation.
    (FOREIGN KEY constraint failed (code 787))
#################################################################
    at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
    at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:915)
    at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
    at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
    at android.arch.persistence.db.framework.FrameworkSQLiteStatement.executeInsert(FrameworkSQLiteStatement.java:50)
    at android.arch.persistence.room.EntityInsertionAdapter.insert(EntityInsertionAdapter.java:64)
    at com.example.mainbuchhaltung.Transaction.TransactionDao_Impl.insert(TransactionDao_Impl.java:96)
    at com.example.mainbuchhaltung.Transaction.TransactionRepository$insertAsyncTask.doInBackground(TransactionRepository.java:64)
    at com.example.mainbuchhaltung.Transaction.TransactionRepository$insertAsyncTask.doInBackground(TransactionRepository.java:54)
    at android.os.AsyncTask$2.call(AsyncTask.java:295)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        ... 4 more

推荐答案

此处

然后,一旦获得交易数据(交易名称和金额),就必须将数据传递到MemberList活动,例如此处

Then once you get transaction data (TransactionName and Amount) then you have to pass data to MemberList activity like here

现在在MemberList屏幕中完成选择后,请执行以下过程:
假设您的字符串中包含成员ID.

Now in your MemberList screen once have done with your selection follow below process:
Suppose you have member ids in a string.

String memberIds = "12,18,25,27,30";

现在,您必须创建所有成员ID都分开的Transaction实体对象,并将其插入到Transaction表中,如下所示.

Now you have to create Transaction entity object with all member ids separated and insert it in the table of Transaction like below.

    String[] memberArray = memberIds.split(",", memberIds.length());
            for(String memberId : memberArray){
                // transactionName & transactionAmount which you received in the bundle from add transaction activity
                Transaction objTransaction = new Transaction(transactionName, transactionAmount); 
                objTransaction.setMemberId(Long.parseLong(memberId));
                // Insert data into your database
                mTransactionViewModel.insert(objTransaction);
            }

它将为"transaction_table"表中的每个memberId创建一对一的单独条目.

It will create a separate entry for each memberId in "transaction_table" table with one to one relationship.

您可以通过执行此处

这篇关于如何在房间数据库中使用多项选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆