【问题标题】:How to get user input to query?如何获取用户输入进行查询?
【发布时间】:2019-08-20 15:52:51
【问题描述】:

我正在尝试获取用户的输入值作为查询参数。

场景是这样的:

在我的片段中,我有一个带有 onclick 显示日期选择器的文本视图。 当挑选的日期时,片段将显示使用存储在与用户所选日期相关的数据库中的数据的回收。

然后我想在 dao 查询如下:

@Query("SELECT * FROM `transaction` where date(//user chosen date) = transactionDate")
public List<TransactionEntity> getAllTransactions();

我只是不知道如何将用户选择的日期从片段传递到 dao。 或者我可以对片段进行查询吗?

我在这个应用程序中使用房间数据库、存储库和视图模型。

这是我的片段类:

public class Tab2Frag extends Fragment {
    private Tab2FragModelView tab2ViewModel;
    private DatePickerDialog.OnDateSetListener dateSetListener;

    public Tab2Frag() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView2 = inflater.inflate(R.layout.fragment_tab2, container, false);

        final TextView dateChooser = rootView2.findViewById(R.id.dateChooserTV);
        String date_n = new SimpleDateFormat("dd-MM-yyyy",
                Locale.getDefault()).format(new Date());
        dateChooser.setText(date_n);

        dateChooser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Calendar cal = Calendar.getInstance();
                int year = cal.get(Calendar.YEAR);
                int month = cal.get(Calendar.MONTH);
                int day = cal.get(Calendar.DAY_OF_MONTH);

                DatePickerDialog dialog = new DatePickerDialog(getContext(),
                        android.R.style.Theme_DeviceDefault_Dialog_Alert,
                        dateSetListener, year, month, day
                );
                dialog.show();
            }
        });

        dateSetListener = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int day) {

                // Create a Date variable/object with user chosen date
                Calendar cal = Calendar.getInstance();
                cal.setTimeInMillis(0);
                cal.set(year, month, day);
                Date chosenDateDate = cal.getTime();


                // Format the date using style long and UK locale
                DateFormat df_long_uk = DateFormat.getDateInstance(DateFormat.LONG, Locale.UK);
                String df_long_uk_str = df_long_uk.format(chosenDateDate);
                // Display the formatted date
                dateChooser.setText(df_long_uk_str);
                String dateIn = new SimpleDateFormat("yyyy-MM-dd",
                        Locale.getDefault()).format(new Date());
                String dateVar = dateIn; //this is the var that I want to pass to query
            }
        };


        rootView2.findViewById(R.id.recView);
        RecyclerView recyclerView = rootView2.findViewById(R.id.recView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setHasFixedSize(true);


        final TransactionAdapter adapter = new TransactionAdapter();
        recyclerView.setAdapter(adapter);

        tab2ViewModel = ViewModelProviders.of(this).get(Tab2FragModelView.class);
        tab2ViewModel.getAllTransactions().observe(getViewLifecycleOwner(),
                new Observer<List<TransactionEntity>>() {
            @Override
            public void onChanged(List<TransactionEntity> transactionEntities) {
                adapter.setTransaction(transactionEntities);
            }
        });

        // Inflate the layout for this fragment
        return rootView2;
    }
}

现在,我的查询是这样的:

    @Query("SELECT * FROM `transaction` where date('now') = transactionDate")
    LiveData<List<TransactionEntity>> getAllTransactions();

我将日期保存为 yyyy-MM-dd 格式的字符串,例如 iso 8601

我的实体:

@Entity(tableName = "transaction")
public class TransactionEntity {
    @PrimaryKey(autoGenerate = true)
    @NonNull
    @ColumnInfo(name = "transactionId")
    private int transactionId;

    @ColumnInfo(name = "transactionDate")
    private String date;

    @ColumnInfo(name = "transactionCategory")
    private String category;

    @ColumnInfo(name = "transactionDetail")
    private String detail;

    @ColumnInfo(name = "transactionAmount")
    private double amount;

    public TransactionEntity(String date, String category , String detail, double amount) {
        this.transactionId = transactionId;
        this.date = date;
        this.category = category;
        this.detail = detail;
        this.amount = amount;

【问题讨论】:

    标签: android android-studio android-room


    【解决方案1】:

    只需像这样将参数传递给函数:

    @Query("SELECT * FROM `transaction` where date = :transactionDate")
    public List<TransactionEntity> getAllTransactions(transactionDate);
    

    从提问者编辑: 我的 dao 是这样的:

     @Query("SELECT * FROM `transaction` where transactionDate = :dateVar")
        List<TransactionEntity> getAllTransactionsByDate(String dateVar);
    

    原来我需要修改我的 repo 和 modelView。这个答案对我有帮助,非常感谢!

    【讨论】:

    • 但是它将如何从片段中获取用户选择的日期?它是自动发生的吗?
    • @ObedAdhinatapraya 我需要查看您的片段代码才能确定。
    • 您好,抱歉回复缓慢。我将我的片段代码放在问题中,请检查。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    相关资源
    最近更新 更多