2014-01-22 5 views
0

Я создал EditText (дата) и кнопку (Обновить) в файле selection.xml. Дата использует datepicker для его настройки.Как получить данные из базы данных на основе даты

У меня 2 вопроса Мне нужна помощь. Когда я нажимаю на editText, всплывает датапикер после того, как я выберу дату и нажмем на обновление, она перейдет к моей другой компоновке (update.xml). Как я могу гарантировать, что дата, которую я выбираю с помощью datepicker, совпадает с датой в базе данных.

2) В моем файле update.xml будут показаны все записи для указанной даты, которые я указал/search в моем файле selection.xml.

Я новичок в android, особенно из базы данных и занимаюсь датой. Мне нужна помощь для моего вопроса, как указано. Может кто-нибудь, пожалуйста, помогите мне? Вот мой код.

DBAdapter.java

public class DBAdapter { 



    public static final String KEY_ROWID = "_id"; 
    public static final String KEY_DATE = "date"; 
    public static final String KEY_PRICE = "fuelprice"; 
    public static final String KEY_FUEL = "fuelpump"; 
    public static final String KEY_COST = "tcost"; 
    public static final String KEY_ODM = "odometer"; 
    public static final String KEY_CON = "fcon"; 

    private static final String TAG = "DBAdapter"; 

    private static final String DATABASE_NAME = "MyDB"; 
    private static final String DATABASE_TABLE = "fuelLog"; 
    private static final int DATABASE_VERSION = 2; 



    private static final String DATABASE_CREATE = 
      "create table fuelLog (_id integer primary key autoincrement, " + "date text not null, fuelprice text not null, fuelpump text not null, tcost text not null, odometer text not null, fcon text not null);"; 


     private final Context context;  

     private DatabaseHelper DBHelper; 
     private SQLiteDatabase db; 

     public DBAdapter(Context ctx){ 
      this.context = ctx; 
      DBHelper = new DatabaseHelper(context); 
     } 

     private static class DatabaseHelper extends SQLiteOpenHelper 
     { 
      DatabaseHelper(Context context){ 
       super(context, DATABASE_NAME, null, DATABASE_VERSION); 
      } 

      public void onCreate(SQLiteDatabase db) 
      { 
       try{ 
        db.execSQL(DATABASE_CREATE);  
       }catch (SQLException e){ 
        e.printStackTrace(); 
       } 
      }//onCreate 

      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
      { 
       Log.w(TAG, "Upgrading database from version " + oldVersion + " to " 
         + newVersion + ", which will destroy all old data"); 
       db.execSQL("DROP TABLE IF EXISTS contacts"); 
       onCreate(db); 
      }//onUpgrade 

     }//DatabaseHelper 


     public DBAdapter open() throws SQLException 
     { 
      db = DBHelper.getWritableDatabase(); 
      return this; 
     }//open 


     //---closes the database---  
     public void close() 
     { 
      DBHelper.close(); 
     }//close 


     //---insert a log into the database--- 
     public long insertLog(String date, String fuelprice, String fuelpump,String tcost,String odometer,String fcon) 
     { 
      ContentValues initialValues = new ContentValues(); 
      initialValues.put(KEY_DATE, date); 
      initialValues.put(KEY_PRICE, fuelprice); 
      initialValues.put(KEY_FUEL, fuelpump); 
      initialValues.put(KEY_COST, tcost); 
      initialValues.put(KEY_ODM, odometer); 
      initialValues.put(KEY_CON, fcon); 


      return db.insert(DATABASE_TABLE, null, initialValues); 
     }//insertLog 
} 

selection.java

public class selection extends Activity { 


    Button newButton; 
    Button updateButton; 
    Button deleteButton; 
    Button summaryButton; 
    static EditText updateEdit; 
    private int mYear; 
    private int mMonth; 
    private int mDay; 

    static final int DATE_DIALOG_ID = 0; 




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

     updateEdit = (EditText)findViewById(R.id.updateEdit); 


     updateEdit.setOnClickListener(new View.OnClickListener() { 
       public void onClick(View v) { 
        // showDialog(DATE_DIALOG_ID); 
        DialogFragment newFragment = new DatePickerFragment(); 
        newFragment.show(getFragmentManager(), "datePicker"); 
       } 
      });    

     newButton = (Button) findViewById(R.id.newBTN); 
     newButton.setOnClickListener(new OnClickListener() 
     { 
      public void onClick(View v) 
      { 

       Intent mainAct=new Intent(getApplicationContext(),MainActivity.class); 
       startActivity(mainAct); 

      }     
      }); 

     updateButton = (Button) findViewById(R.id.updateBTN); 
     updateButton.setOnClickListener(new OnClickListener() 
     { 
      public void onClick(View v) 
      { 

       Intent updateAct=new Intent(getApplicationContext(),update.class); 
       startActivity(updateAct); 

      } 

      }); 

     deleteButton = (Button) findViewById(R.id.deleteBTN); 
     deleteButton.setOnClickListener(new OnClickListener() 
     { 
      public void onClick(View v) 
      {     
       Intent updateAct=new Intent(getApplicationContext(),update.class); 
       startActivity(updateAct); 

      } 

      }); 

     summaryButton = (Button) findViewById(R.id.summaryBTN); 
     summaryButton.setOnClickListener(new OnClickListener() 
     { 
      public void onClick(View v) 
      { 

       Intent summaryView=new Intent(getApplicationContext(),summary.class); 
       startActivity(summaryView); 

      }     
      }); 

     } 
    public static class DatePickerFragment extends DialogFragment 
    implements DatePickerDialog.OnDateSetListener { 

     public EditText editText; 
     DatePicker dpResult; 

    public Dialog onCreateDialog(Bundle savedInstanceState) { 
    // Use the current date as the default date in the picker 

    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(), (EditSessionActivity)getActivity(), year, month, day); 

    // Create a new instance of DatePickerDialog and return it 
    return new DatePickerDialog(getActivity(), this, year, month, day); 
    } 

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

     updateEdit.setText(String.valueOf(day) + "/" 
       + String.valueOf(month + 1) + "/" + String.valueOf(year)); 
     // set selected date into datepicker also 


    } 
    } 
} 

update.java (я еще сделать кодирование, потому что я не знаю, как я могу извлечь данные из из базы данных, на основе даты)

public class update extends Activity{ 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.update); 
} 
} 

selection.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="fill_parent" 
    android:orientation="vertical" 
    android:layout_height="fill_parent" 
    tools:context=".MainActivity" > 


    <TableLayout 
     android:id="@+id/tableLayout1" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:stretchColumns="1 "> 

     <TableRow 
      android:id="@+id/tableRow1" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"> 

      <Button 
      android:id="@+id/newBTN" 
      android:text="New" 
      android:layout_width="wrap_content" 
      android:layout_height="60px" > 
     </Button> 
     </TableRow> 

     <TableRow 
      android:id="@+id/tableRow2" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" > 
      <Button 
      android:id="@+id/updateBTN" 
      android:text="Update" 
      android:layout_width="wrap_content" 
      android:layout_height="60px" > 
     </Button> 
      <EditText 
       android:id="@+id/updateEdit" 
       android:text="" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
        android:editable="false" 
       android:enabled="true"> 
      </EditText> 
     </TableRow> 
     <TableRow 
      android:id="@+id/tableRow3" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" > 
      <Button 
      android:id="@+id/deleteBTN" 
      android:text="Delete" 
      android:layout_width="wrap_content" 
      android:layout_height="60px" > 
     </Button> 
      <EditText 
       android:id="@+id/deleteEdit" 
       android:text="" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content"> 
      </EditText> 
     </TableRow> 


      <TableRow 
      android:id="@+id/tableRow4" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" > 
      <Button 
      android:id="@+id/summaryBTN" 
      android:text="Summary" 
      android:layout_width="wrap_content" 
      android:layout_height="60px" > 
     </Button>  
     </TableRow>   

     </TableLayout>   
</LinearLayout> 

update.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="fill_parent" 
    android:orientation="vertical" 
    android:layout_height="fill_parent" 
    tools:context=".MainActivity" > 


    <TableLayout 
     android:id="@+id/tableLayout1" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:stretchColumns="1"> 

     <TableRow 
      android:id="@+id/tableRow1" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"> 
      <TextView 
       android:id="@+id/datetxtview" 
       android:text="@string/date" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content"> 
      </TextView> 
       <EditText 
       android:id="@+id/date" 
       android:text="" 
       android:inputType="date" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
        android:editable="false"> 
      </EditText> 
     </TableRow> 

     <TableRow 
      android:id="@+id/tableRow2" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" > 
      <TextView 
       android:id="@+id/fuelpricetxtview" 
       android:text="@string/fuelprice" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content"> 
      </TextView> 
      <EditText 
       android:id="@+id/fuelprice" 
       android:text="" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content"> 
      </EditText> 
     </TableRow> 
     <TableRow 
      android:id="@+id/tableRow3" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" > 
      <TextView 
       android:id="@+id/fuelpumptxtview" 
       android:text="@string/fuelpump" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content"> 
      </TextView> 
      <EditText 
       android:id="@+id/fuelpump" 
       android:text="" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content"> 
      </EditText> 
     </TableRow> 


      <TableRow 
      android:id="@+id/tableRow4" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" > 
      <TextView 
       android:id="@+id/totalcosttxtview" 
       android:text="@string/totalcost" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content"> 
      </TextView> 

      <TextView 
       android:id="@+id/tcost" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="" /> 

     </TableRow> 



     <TableRow 
      android:id="@+id/tableRow5" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" > 
      <TextView 
       android:id="@+id/odometertxtview" 
       android:text="@string/odometer" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content"> 
      </TextView> 

      <EditText 
       android:id="@+id/odometer" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:ems="10" > 

       <requestFocus /> 
      </EditText> 

     </TableRow> 
     <TableRow 
      android:id="@+id/tableRow6" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" > 
      <TextView 
       android:id="@+id/fctxtview" 
       android:text="@string/fc" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content"> 
      </TextView> 

      <TextView 
       android:id="@+id/fcon" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="" /> 

     </TableRow>  
     </TableLayout> 


    <LinearLayout 
     android:id="@+id/linearLayout1" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" > 

      <Button 
      android:id="@+id/updateBTN" 
      android:text="Update" 
      android:layout_width="wrap_content" 
      android:layout_height="60px" > 
     </Button> 
     <Button 
      android:id="@+id/cancelBTN" 
      android:text="@string/cancel" 
      android:layout_width="wrap_content" 
      android:layout_height="60px" > 
     </Button> 
    </LinearLayout> 
</LinearLayout> 
+0

Пожалуйста, сначала найдите http://stackoverflow.com/questions/5565736/how-do-i-retrieve-data-from-an-sqlite-database-on-android?rq=1 – PedroAGSantos

ответ

0

Вы можете преобразовать дату String, а затем сохранить строку в БД, как:

String dateText = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date() 

дата будет выглядеть следующим образом 2014-01-19 04:51:48

В вашем DatePicker:

SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd"); 
String dateFormat = dateformat.format(new Date(datePicker.getYear(),  
datePicker.getMonth(), datePicker.getDayOfMonth())); 
1

Используйте это для извлечения даты из DatePicker:

public class MainActivity extends Activity { 

    static EditText mDateDisplay; 
    private Button mPickDate; 
    private int mYear; 
    private int mMonth; 
    private int mDay; 

    static final int DATE_DIALOG_ID = 0; 



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


     mDateDisplay = (EditText) findViewById(R.id.editText1); 
     mPickDate = (Button) findViewById(R.id.button1); 


     mPickDate.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       // showDialog(DATE_DIALOG_ID); 
       DialogFragment newFragment = new DatePickerFragment(); 
       newFragment.show(getFragmentManager(), "datePicker"); 
      } 
     }); 


    } 


    public static class DatePickerFragment extends DialogFragment 
    implements DatePickerDialog.OnDateSetListener { 

     public EditText editText; 
     DatePicker dpResult; 

    public Dialog onCreateDialog(Bundle savedInstanceState) { 
    // Use the current date as the default date in the picker 

    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(), (EditSessionActivity)getActivity(), year, month, day); 

    // Create a new instance of DatePickerDialog and return it 
    return new DatePickerDialog(getActivity(), this, year, month, day); 
    } 

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

     mDateDisplay .setText(String.valueOf(day) + "/" 
       + String.valueOf(month + 1) + "/" + String.valueOf(year)); 
     // set selected date into datepicker also 


    } 
    } 
} 

И дата извлечения и вставки см следующие шаги:

Вы не можете использовать функции даты-времени, используя оболочку Java " ContentValues». Вы можете реализовать следующим образом:

1) Вы можете использоватьSQLiteDatabase.ExecSQL (сырой SQL-запрос)

dbObj.execSQL("INSERT INTO "+DATABASE_TABLE+" VALUES (null, datetime()) "); 

2) Вы можете использовать SimpleDateFormat

// setting the format to sql date time 
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
Date date = new Date(); 
ContentValues initialValues = new ContentValues(); 
initialValues.put("date_time", dateFormat.format(date)); 
long recordId = mDb.insert(DB_TABLE_NAME, null, initialValues); 

3) хранить значение даты в базе данных в виде (длинный типа) миллисекунд и для отображения вы можете отформатировать его,

import java.text.DateFormat; 
import java.text.SimpleDateFormat; 
import java.util.Calendar; 

System.out.println(getDate(82233213123L, "dd/MM/yyyy hh:mm:ss.SSS")); 

// Return date in specified format. 
// milliSeconds Date in milliseconds 
// dateFormat Date format 
// return date as string in specified format 

public static String formatDate(long milliSeconds, String dateFormat) 
{ 

    DateFormat formatter = new SimpleDateFormat(dateFormat); 

// Create a calendar object that will convert the date and time value in milliseconds to date. 
    Calendar calendar = Calendar.getInstance(); 
calendar.setTimeInMillis(milliSeconds); 
return formatter.format(calendar.getTime()); 
    } 
} 

1 секунда = 1000 миллисекунд, так что если вы хотите добавить 1 час, затем использовать эту формулу

currentTImeMilli + (60 * 60 * 1000) 
Смежные вопросы