Show SQLITE data between dates - Android Studio (think be between)

Asked

Viewed 993 times

0

Good, I want the user to choose the data to show between the dates he chooses. I’ve tried everything but still can’t.

That is what I want to filter between dates, but the user has to choose them. I already got it with an SQL command, but it was manual. I wanted the user to choose the dates. Thank you!

Code:

java input.

private Edittext Dataedit; private Edittext editDescription; Private button Botaoadicionar; private button botaover; Static Edittext Dateedit; private Sqlitedatabase db;

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

    DataEdit = (EditText) findViewById(R.id.iEditdata);
    editDescricao = (EditText) findViewById(R.id.ieditDescricao);
    botaoadicionar = (Button) findViewById(R.id.botaoadicionar);
    botaover = (Button) findViewById(R.id.botaover);
    botaoadicionar.setOnClickListener(this);
    botaover.setOnClickListener(this);
    DateEdit = (EditText) findViewById(R.id.iEditdata);
    DateEdit.setOnClickListener(new View.OnClickListener() {
        // ver se fiz asneira...
        public void onClick(View v) {

            showTruitonDatePickerDialog(v);
        }
    });
}

protected void createDatabase(){
    db=openOrCreateDatabase("DadosDB", Context.MODE_PRIVATE, null);
    db.execSQL("CREATE TABLE IF NOT EXISTS tabeladados(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, data DATE,descricao VARCHAR);");
}
protected void insertIntoDB(){
    String data = DataEdit.getText().toString().trim();
    String descricao = editDescricao.getText().toString().trim();
    if(data.equals("") || descricao.equals("")){
        Toast.makeText(getApplicationContext(),"Preencha todos os campos", Toast.LENGTH_LONG).show();
        return;
    }

    String query = "INSERT INTO tabeladados (data,descricao) VALUES('"+data+"', '"+descricao+"');";
    db.execSQL(query);
    Toast.makeText(getApplicationContext(),"Guardado com sucesso", Toast.LENGTH_LONG).show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {


    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    return super.onOptionsItemSelected(item);
}
private void mostrardados(){
    Intent intent = new Intent(this,output.class);
    startActivity(intent);
    finish();
}
@Override
public void onClick(View v) {
    if(v == botaoadicionar){
        insertIntoDB();
    }
    if(v==botaover){
        mostrardados();
    }
}
public void showTruitonDatePickerDialog(View v) {
    DialogFragment newFragment = new DatePickerFragment();
    newFragment.show(getSupportFragmentManager(), "datePicker");
}

public static class DatePickerFragment extends DialogFragment implements
        DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {

        DateEdit.setText(year + "-" + (month + 1) + "-" + day);
    }
}

}

java output.

public class output extends Actionbaractivity Implements View.Onclicklistener { private Edittext editDescription; private Edittext editTextId; private Edittext editTextName; Private button Private boot button;

private Static final String SELECT_SQL = "SELECT * FROM table";

private SQLiteDatabase db;
private Cursor c;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.output);
    openDatabase();
    editTextId = (EditText) findViewById(R.id.oeditTextId);
    editDescricao = (EditText) findViewById(R.id.oeditDescricao);
    editTextName = (EditText) findViewById(R.id.oeditTextName);
    botaoanterior = (Button) findViewById(R.id.botaoanterior);
    botaoseguinte = (Button) findViewById(R.id.botaoseguinte);
    botaoseguinte.setOnClickListener(this);
    botaoanterior.setOnClickListener(this);
    c = db.rawQuery(SELECT_SQL, null);
    c.moveToFirst();
    showRecords();

}

protected void openDatabase() {
    db = openOrCreateDatabase("DadosDB", Context.MODE_PRIVATE, null);
}

protected void showRecords() {
    String id = c.getString(0);
    String data = c.getString(1);
    String add = c.getString(2);
    editTextId.setText(id);
    editDescricao.setText(add);
    editTextName.setText(data);

}
protected void moveNext() {
    if (!c.isLast())
        c.moveToNext();
    showRecords();
}
protected void movePrev() {
    if (!c.isFirst())
        c.moveToPrevious();
    showRecords();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
    if (v == botaoseguinte) {
        moveNext();
    }

    if (v == botaoanterior) {
        movePrev();
    }

}

public void voltar(View view) {
    Intent intent = new Intent(output.this, input.class);
    startActivity(intent);
}

}

xml input.

<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="VER"
    android:id="@+id/botaover"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Adicionar"
    android:id="@+id/botaoadicionar"
    android:layout_above="@+id/botaover"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/iEditdata"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginTop="114dp"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_above="@+id/botaoadicionar"
    android:weightSum="1">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/ieditDescricao"
        android:hint="Descrição:"
        android:layout_below="@+id/iEditdata"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_weight="1" />
</LinearLayout>

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:ems="10"
    android:layout_below="@+id/iEditdata"
    android:id="@+id/Edithoras"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:hint="Total horas:" />

xml output

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/oeditTextName"
    android:weightSum="1">

    <EditText
        android:layout_width="match_parent"
        android:focusableInTouchMode="false"
        android:layout_height="161dp"
        android:id="@+id/oeditDescricao"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_above="@+id/botaoguardar"
        android:layout_weight="1" />
</LinearLayout>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Anterior"
    android:id="@+id/botaoanterior"
    android:layout_weight="0.20"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<Button
    android:text="Voltar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="voltar"
    android:id="@+id/botaovoltar"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Seguinte"
    android:id="@+id/botaoseguinte"
    android:layout_weight="0.31"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_alignLeft="@+id/botaovoltar"
    android:layout_alignStart="@+id/botaovoltar" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:ems="10"
    android:id="@+id/totalhoras"
    android:layout_above="@+id/botaoanterior"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />
  • Are you storing the date as text? Usually in SQLITE it would be better to use REAL, along with the functions of Julian date (which actually is based on the proleptic Gregorian Calendar), or INTEGER with Posix time functions. Doing with string operations is always more labor-intensive for DB, in addition to space wastage.

  • db.execSQL("CREATE TABLE IF NOT EXISTS dashed(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, date DATE,Description VARCHAR);"); -> It is in date type in SQLITE. Dateedit is a popup that appears a calendar to insert a date in inputtext

  • There is no DATE in Sqlite. Saved some extension for android use it. Sqlite has TEXT, INTEGER, REAL and BLOB only.

  • What you recommend and how I should do it?

  • Without knowing the details of the application, I wouldn’t know the best way to go in your case. I just wanted to let you know that the Sqlite types are a little different from the most common Dbs, and in the case of money and dates, you better have something more specialized in your application to deal with it. A read in the Sqlite manual helps to give a sense, and in the part of the date functions has how to convert to INT or FLOAT when storing, and "disconnect" at SELECT time to show as same date.

  • Know some example of what I want to do somewhere? :/

  • For now, see if you can solve with the solution of Eggaldo, I think it is better after you study and understand, only copying an example will give you more doubts than solution. Once you have mastered the date functions, then you adapt.

  • The function that the expensive Reginaldo gave works, but I intend to select the two inputs of date...

Show 3 more comments

2 answers

0

That’s how it works:

SELECT *
FROM tabela
WHERE datapesquisada BETWEEN '2017-01-01' AND '2017-12-31';
  • Bom, where should I put this code? I want the user to choose and not me :/

  • You can create a dialog box to inform the start date and end date and click a button. So you would put the code in the onclick event of the button.

  • I think this is my greatest difficulty! Do you know of any example where I can learn? Thank you, you are helping a lot!

  • You can find examples for all tastes and purposes on the web. Example: https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=how%20to%20create%20a%20dialog%20box%20in%20android%20example

  • With the code I have on top, do you think you can? I wonder if you can find a way? :/

0


As Reginaldo said above, creating a button can solve this problem.

Create text boxes for the user to enter and then fetch this value to perform the query in the database.

I’m not sure about the syntax but it must be something like:

@Override
public void onClick(View v) {
   String dataInicial = (EditText)findViewById(R.id.dataInicial);
   String dataFinal = (EditText)findViewById(R.id.dataFinal); // EditText é só um exemplo

   String query = "SELECT * FROM tabela 
   WHERE data BETWEEN " + dataInicial + " AND " + dataFinal;
   // aqui será o código para executar a query à BD.
   Cursor c = db.rawQuery(query, null);
   // depois terás de efetuar o tratamento dos dados
}
  • I should put in the right input part?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.