-2

I am new in android. I have created a date picker. But i could not insert date into the database. I tried as:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(provider.getDate());
values.put(DATE, formattedDate );

DATE data type is not supported by android. So i declared as String. But the problem is not solved. Here is my code:

Database Handler

public class DatabaseHandler extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "income.db";
public static final String TABLE_NAME = "income_table";
public static final String ID="id";
public static final String AMOUNT = "amount";
public static final String PAYER_NAME = "payer";
public static final String NOTE = "note";

public static final String DATE= "date";


String query = "CREATE TABLE " + TABLE_NAME +
        "(" +ID+ " integer primary key autoincrement, " + AMOUNT + " real, "
        + PAYER_NAME + " text, " + NOTE + " text, " + DATE + " text " + ")";




public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
    sqLiteDatabase.execSQL(query);

}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(sqLiteDatabase);

}

public void addInformation(DataProvider provider){
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    String formattedDate = formatter.format(provider.getDate());
    SQLiteDatabase db = getWritableDatabase();
    ContentValues values=new ContentValues();
    values.put(AMOUNT,provider.getMoney());
    values.put(PAYER_NAME,provider.getName());
    values.put(NOTE,provider.getDesc());
    values.put(DATE, formattedDate );
    db.insert(TABLE_NAME, null, values);
    db.close();

}

DataProvider Class:

public class DataProvider {
private double money;
private String name;
private String desc;
private String date;

public String getDate() {
    return date;
}

public void setDate(String date) {
    this.date = date;
}

public DataProvider(double money, String name, String desc, String date) {
    this.money = money;
    this.name = name;
    this.desc = desc;
    this.date=date;


}



public double getMoney() {
    return money;
}

public void setMoney(double money) {
    this.money = money;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getDesc() {
    return desc;
}

public void setDesc(String desc) {
    this.desc = desc;
}

}

Datepicker class:

public class Income extends AppCompatActivity implements View.OnClickListener {

TextView amount, payer, note, show,showDate;
EditText edit_amount, payer_name, edit_note;
Button save, cancel;
DatabaseHandler db;
ImageButton date;
int year,month,day;

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

    save = (Button) findViewById(R.id.save);
    cancel = (Button) findViewById(R.id.cancel);

    amount = (TextView) findViewById(R.id.amount);
    payer = (TextView) findViewById(R.id.payer);
    note = (TextView) findViewById(R.id.note);
    show = (TextView) findViewById(R.id.show);
    showDate = (TextView) findViewById(R.id.showDate);

    edit_amount = (EditText) findViewById(R.id.edit_amount);
    payer_name = (EditText) findViewById(R.id.edit_payer);
    edit_note = (EditText) findViewById(R.id.edit_note);
    //date= (ImageButton) findViewById(R.id.datePicker);

    db = new DatabaseHandler(this);

    save.setOnClickListener(this);
    cancel.setOnClickListener(this);
    showDate.setOnClickListener(this);
}

@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onClick(View view) {
    if (view.getId() == R.id.save) {
        String amounts,payers,notes,date;
        amounts=edit_amount.getText().toString();
        payers= payer_name.getText().toString();
        notes= edit_note.getText().toString();
        date=showDate.getText().toString();
        if(amounts.isEmpty())
        {
           edit_amount.setError("Amounts should not be blank");
        }
        else {
            Double a =new Double(amounts.toString());
            DataProvider provider = new DataProvider(a, payers, notes,date);
            db.addInformation(provider);
            Intent i = new Intent(this, MainActivity.class);
            startActivity(i);
        }
    }

    if (view.getId() == R.id.cancel) {
        Intent i =new Intent(this,MainActivity.class);
        startActivity(i);
    }

    if (view.getId()==R.id.showDate){

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

            DatePickerDialog dpd = new DatePickerDialog(this,
                    new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                        showDate.setText(i+"/"+(i1+1)+"/"+i2);
                        }
                    },year,month,day);
            dpd.show();


    }

    }
}
Fatema
  • 41
  • 1
  • 2
  • 9

2 Answers2

0

while inserting into the database you are not storing the date picked up by date picker, try to replace below code

values.put(DATE, formattedDate );

with code

values.put(DATE, showDate.getText().toString() );

Please ensure before clicking save button, you have picked up date and its appearing in showText text box.

  • db.insert(TABLE_NAME, null, values); –  Nov 25 '16 at 07:33
  • replace below code db.insert(TABLE_NAME, null, values); with below, it will tell you exact error message, d –  Nov 25 '16 at 07:34
  • db.insertOrThrow(TABLE_NAME, null, values);(TABLE_NAME, null, values); –  Nov 25 '16 at 07:35
0

When using the Date Picker we format all dates selected to be 8 characters long then to view the date a sub routine formats that string to look like this 01-02-2017 but this format is for the View only when the string is sent to the DB it is converted back to this 01022017 below is our Date Picker code and the sub routine to format the View also included is the code to remove the dashs "-"

Date Picker Code

    public void findByDate(){

    final Dialog dialog = new Dialog(DetailsActivity.this,R.style.DatePickerTheme);
    dialog.setContentView(R.layout.datepickerview);
    dialog.setTitle("");
    DatePicker picker = dialog.findViewById(R.id.datePicker);
    final Calendar c = Calendar.getInstance();
    mYear = c.get(Calendar.YEAR);
    mMonth = c.get(Calendar.MONTH);
    mDay = c.get(Calendar.DAY_OF_MONTH);
    picker.updateDate(mYear, mMonth, mDay);// Keeps Calendar initial view what ever today is!

    picker.init(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), new DatePicker.OnDateChangedListener() {

        @Override
        public void onDateChanged(DatePicker picker, int year, int monthOfYear, int dayOfMonth) {

                String searchFrom = (String.valueOf(monthOfYear + 1)) + (String.valueOf(dayOfMonth)) + String.valueOf(year);
                if (searchFrom.length() == 7) {
                    StringBuilder str = new StringBuilder(searchFrom);
                    str.insert(2, '0');
                    etPurchaseDate.setText(str);
                } else if (searchFrom.length() == 6) {
                    StringBuilder str = new StringBuilder(searchFrom);
                    str.insert(0, '0');
                    str.insert(2, '0');
                    System.out.println("===========================str "+str);
                    etPurchaseDate.setText(str);
                } else {

                    etPurchaseDate.setText(searchFrom);
                }
                Toast.makeText(DetailsActivity.this, "Date Formatted for Storage", Toast.LENGTH_LONG).show();
                etCost.requestFocus();
                dialog.dismiss();

        }
});

    dialog.show();
}

Sub Routine to Format the Date String

    public String DATE_TO_FORMAT(String formatDATE){
    /* THIS METHOD KEEP THE DATE FORMATTED FOR DISPLAY */
    /* ONLY CALLED FROM ERROR TRAPPING */
    String s = etPurchaseDate.getText().toString();
    String RDmonth = s.substring(0, 2);
    String RDday = s.substring(2, 4);
    String RDyear = s.substring(4, 8);
    formatDATE = RDmonth + "-" + RDday + "-" + RDyear;
    return formatDATE;
}

Remove the Dash's

                if(etPurchaseDate.length()==10){//
                /* Routine puts DATE back in DB as 8 Character String REMOVES dashes "-" */
                StringBuilder removeTHIS = new StringBuilder(etPurchaseDate.getText().toString());
                String value = removeTHIS.toString().replace("-", "");
                etPurchaseDate.setText(value);
                etCost.requestFocus();
                purchase_date = value;
            //}else{
                //etPurchaseDate.setText(etPurchaseDate.getText().toString());
                etCost.requestFocus();
            }

One BIG issue with this design is dealing with the end user not using the Date Picker this needs to be dealt with in your error trapping before saving for instance a date entered like this 00-33-0217 It might be best to force all dates be enters with the Date Picker and set the field disabled BUT that design has other issues

Vector
  • 3,066
  • 5
  • 27
  • 54