在android中基于月份和年份从数据库中检索数据

时间:2013-10-20 08:41:47

标签: android database sqlite date

我是一个更新鲜的android.I有一个关于数据库的查询。我已经在数据库中插入了一些数据,即我已经从自定义datepickerdialog中选择的textview插入了月份和年份,并且还插入了日期和textview中的一些信息到数据库。我想从数据库中检索基于月份和年份的插入日期和信息,并显示在listwiev中。 以下代码显示了数据的插入..

  package com.example.collegeapp;

    import java.lang.reflect.Field;
    import java.util.Calendar;
    import android.app.Activity;
    import android.app.DatePickerDialog;
    import android.app.Dialog;
    import android.content.ContentValues;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.DatePicker;
    import android.widget.EditText;
    import android.widget.ImageButton;
    import android.widget.Toast;

    public class Events1 extends Activity {
    int yr,mm,dd;
    ImageButton ib;
    EditText et1,et2,et3;
    String d,c,e;
    Button b1;
    static final int Date_Dialog_id=1;
    Database md=new Database(this);

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_events1);
            ib=(ImageButton) findViewById(R.id.imageButton1);
            et1=(EditText) findViewById(R.id.editText1);
            et2=(EditText) findViewById(R.id.editText2);
            et3=(EditText) findViewById(R.id.editText3);

            b1=(Button) findViewById(R.id.button1);
            md.open();

    b1.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub

                    d=et1.getText().toString();
                    c=et2.getText().toString();
                    e=et3.getText().toString();
                    ContentValues cv=new ContentValues();
                    cv.put("d",d);
                    cv.put("c",c);
                    cv.put("e",e);

                    md.add(cv);
                     Toast t=Toast.makeText(getApplicationContext(), "Data is inserted",Toast.LENGTH_SHORT);
                     t.show();
                     et1.setText("");
                     et2.setText(" ");
                     et3.setText(" ");
                }
            });

            ib.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                     showDialog(Date_Dialog_id);
                   }

            });
            final Calendar c = Calendar.getInstance();
             yr = c.get(Calendar.YEAR);
              mm = c.get(Calendar.MONTH);


             }
        DatePickerDialog.OnDateSetListener mDateSetListner = new DatePickerDialog.OnDateSetListener() {

              @Override
              public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {

               yr= year;
               mm = monthOfYear;
               dd = dayOfMonth;
               updateDate();
              }
             };

             @Override
             protected Dialog onCreateDialog(int id) {
              switch (id) {
              case Date_Dialog_id:

               DatePickerDialog datePickerDialog = this.customDatePicker();
               return datePickerDialog;
              }
              return null;
             }

             protected void updateDate() {
              int localMonth = (mm + 1);
              String monthString = localMonth < 10 ? "0" + localMonth : Integer
                .toString(localMonth);
              String localYear = Integer.toString(yr).substring(2);
              et1.setText(new StringBuilder()
              // Month is 0 based so add 1
                .append(monthString).append("/").append(localYear).append(" "));
              showDialog(Date_Dialog_id);
             }

             private DatePickerDialog customDatePicker() {
              DatePickerDialog dpd = new DatePickerDialog(this, mDateSetListner,
               yr,mm,dd);
              try {

               Field[] datePickerDialogFields = dpd.getClass().getDeclaredFields();
               for (Field datePickerDialogField : datePickerDialogFields) {
                if (datePickerDialogField.getName().equals("mDatePicker")) {
                 datePickerDialogField.setAccessible(true);
                 DatePicker datePicker = (DatePicker) datePickerDialogField
                   .get(dpd);
                 Field datePickerFields[] = datePickerDialogField.getType()
                   .getDeclaredFields();
                 for (Field datePickerField : datePickerFields) {
                  if ("mDayPicker".equals(datePickerField.getName())
                    || "mDaySpinner".equals(datePickerField
                      .getName())) {
                   datePickerField.setAccessible(true);
                   Object dayPicker = new Object();
                   dayPicker = datePickerField.get(datePicker);
                   ((View) dayPicker).setVisibility(View.GONE);
                  }}}}}
             catch (Exception ex) {
              }
              return dpd;

        }




}

以下是从数据库中检索数据的代码。
Events.java

         package com.example.collegeapp;
         import java.lang.reflect.Field;
         import java.util.Calendar;
         import android.app.Activity;
         import android.app.DatePickerDialog;
         import android.app.Dialog;
         import android.content.ContentValues;
         import android.database.Cursor;
         import android.os.Bundle;
         import android.support.v4.widget.SimpleCursorAdapter;
         import android.view.View;
         import android.view.View.OnClickListener;
         import android.widget.Button;
         import android.widget.DatePicker;
         import android.widget.EditText;
         import android.widget.ImageButton;
      import android.widget.ListView;
     import android.widget.TextView;
     import android.widget.Toast;

      public class Events extends Activity {
    ImageButton ib;
    Button b1;
    EditText et1;
    int yr,mm,dd;
    Cursor y;
    ListView lv;
    String m;
    static final int Date_Dialog_id=1;
    Database md=new Database(this);

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_events);
        ib=(ImageButton) findViewById(R.id.imageButton1);
        b1=(Button) findViewById(R.id.button1);
        et1=(EditText) findViewById(R.id.editText1);

        lv=(ListView) findViewById(R.id.listView1);
        md.open();

        b1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                go();

            }
        });

    ib.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                 showDialog(Date_Dialog_id);
               }

        });
         final Calendar c = Calendar.getInstance();
         yr = c.get(Calendar.YEAR);
          mm = c.get(Calendar.MONTH);

         }
    protected void go() {
        // TODO Auto-generated method stub
        m=et1.getText().toString();
        y=md.get(m);
         if (y.moveToFirst())
         {
           do {


          DisplayCmpTitle(y);
            } while (y.moveToNext());
         }



      }
          private void DisplayCmpTitle(Cursor y2) {
        // TODO Auto-generated method stub
    SimpleCursorAdapter cursorAdapter;

    String []from={"d","c","e"};
        int []to={R.id.textView1,R.id.textView2,R.id.textView3};
        cursorAdapter=new SimpleCursorAdapter(this,R.layout.activity_event3,y,from,to,0);
            lv.setAdapter(cursorAdapter);


    }


        DatePickerDialog.OnDateSetListener mDateSetListner = new DatePickerDialog.OnDateSetListener() {

          @Override
          public void onDateSet(DatePicker view, int year, int monthOfYear,
            int dayOfMonth) {

           yr= year;
           mm = monthOfYear;
           dd = dayOfMonth;
           updateDate();
          }
         };

         @Override
         protected Dialog onCreateDialog(int id) {
          switch (id) {
          case Date_Dialog_id:
           /*
            * return new DatePickerDialog(this, mDateSetListner, mYear, mMonth,
            * mDay);
            */
          DatePickerDialog datePickerDialog = this.customDatePicker();
           return datePickerDialog;
          }
          return null;
         }

         protected void updateDate() {
          int localMonth = (mm + 1);
          String monthString = localMonth < 10 ? "0" + localMonth : Integer
            .toString(localMonth);
          String localYear = Integer.toString(yr).substring(2);
          et1.setText(new StringBuilder()
          // Month is 0 based so add 1
            .append(monthString).append("/").append(localYear).append(" "));
          showDialog(Date_Dialog_id);
         }

         private DatePickerDialog customDatePicker() {
          DatePickerDialog dpd = new DatePickerDialog(this, mDateSetListner,
           yr,mm,dd);
          try {

           Field[] datePickerDialogFields = dpd.getClass().getDeclaredFields();
           for (Field datePickerDialogField : datePickerDialogFields) {
            if (datePickerDialogField.getName().equals("mDatePicker")) {
             datePickerDialogField.setAccessible(true);
             DatePicker datePicker = (DatePicker) datePickerDialogField
               .get(dpd);
             Field datePickerFields[] = datePickerDialogField.getType()
               .getDeclaredFields();
             for (Field datePickerField : datePickerFields) {
              if ("mDayPicker".equals(datePickerField.getName())
                || "mDaySpinner".equals(datePickerField
                  .getName())) {
               datePickerField.setAccessible(true);
               Object dayPicker = new Object();
               dayPicker = datePickerField.get(datePicker);
               ((View) dayPicker).setVisibility(View.GONE);
              }}}}}
         catch (Exception ex) {
          }
          return dpd;

    }

}


Events.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="18dp"
        android:gravity="center"
        android:text="Events"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="44dp"
        android:text="Button" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1"
        android:ems="10" />

    <ImageButton
        android:id="@+id/imageButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/editText1"
        android:background="@drawable/ic_launcher" />

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/imageButton1"
        android:layout_marginTop="74dp" >
    </ListView>

</RelativeLayout>

database.java

          package com.example.collegeapp;
          import android.content.ContentValues;
          import android.content.Context;
          import android.database.Cursor;
          import android.database.SQLException;
          import android.database.sqlite.SQLiteDatabase;
         import android.database.sqlite.SQLiteDatabase.CursorFactory;
         import android.database.sqlite.SQLiteOpenHelper;
          import android.util.Log;
         import android.widget.Toast;
        public class Database 
        {
    public static final String MY_db="testDB";
    //private static final String Table_name="stu";
    private static final String Key_id="_id";
    private static final String Key_mnth_yr="d";
    private static final String Key_date="c";

    private static final String Key_data="e";
    MyHelper1 mh;
    Context myCon;
    SQLiteDatabase sdb;
    public Database(Context c){
        myCon=c;
        mh=new MyHelper1(myCon,MY_db, null,1);
    }
    public Database open() throws SQLException{
        sdb=mh.getWritableDatabase();
        return this;
    }
    public class MyHelper1 extends SQLiteOpenHelper{


           public MyHelper1(Context context, String name, CursorFactory factory,
                int version) {
            super(context, name, factory, version);
            // TODO Auto-generated constructor stub
        }



        public void onCreate(SQLiteDatabase db) {
            try{
            // TODO Auto-generated method stub
    db.execSQL("cretae table s(_id integer primary key autoincrement,d text,c text,e           text);");

            }
            catch(SQLException e){
                e.printStackTrace();
            }

        }


        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub

        }
            }
    public void add(ContentValues cv){
       // SQLiteDatabase sdb = this.getWritableDatabase();


        sdb.insert("s", null, cv);
    }

        public Cursor get(String dtr) {
        // TODO Auto-generated method stub

        Cursor f=sdb.query("s",new String[] {"d","c","e" },"d" + "=" + dtr,
                new String [] { "dtr" },null,null,null,null);
        return f;


    }

    }

logcat中显示的错误是 - 无法绑定索引1处的参数,因为索引超出范围。语句有0参数。

0 个答案:

没有答案