如何将KEY_NAME中的数据从我的数据库(在DbHelper中)获取到TextView(“txtSchedName”)?在我检索名称后,它的ID也将显示在TextView(“txtID”)中?
DbHelper
package com.example.dn;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbHelper extends SQLiteOpenHelper {
static String DATABASE_NAME="patientdata";
public static final String TABLE_NAME="patient";
public static final String KEY_ID="id";
public static final String KEY_NAME="pname";
public static final String KEY_AGE="page";
public static final String KEY_GENDER="pgender";
public static final String KEY_ADDRESS="paddress";
public static final String KEY_CONTACT="pcontact";
private SQLiteDatabase mDb;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, " +
""+KEY_NAME+" TEXT, "+KEY_AGE+" TEXT, "+KEY_GENDER+" TEXT, "+KEY_ADDRESS+" TEXT, "+KEY_CONTACT+" TEXT)";
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public void openDataBase() {
//Open the database
String myPath = DATABASE_NAME + TABLE_NAME;
SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
//latest created
public Cursor displayPatient() {
Cursor mCursor = mDb.query(TABLE_NAME, new String[] {KEY_ID,
KEY_NAME,KEY_AGE,KEY_CONTACT,KEY_GENDER,KEY_ADDRESS},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToLast();
}
return mCursor;
}
/*cur */
public List<String> getAllLabels(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery,null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(0));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning labels
return labels;
}
}
Schedule_DB_Helper
package com.example.dn;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class Schedule_DB_Helper extends SQLiteOpenHelper {
static String DATABASE_NAME="patient_schedule";
public static final String TABLE_NAME="schedule";
public static final String KEY_ID="ID";
public static final String KEY_NAME="NAME";
public static final String KEY_DATE="DATE";
public static final String KEY_TIME="TIME";
//public static final String KEY_NOTI="NOTI";
public Schedule_DB_Helper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, " +
""+KEY_NAME+" TEXT,"+KEY_DATE+" TEXT, "+KEY_TIME+" TEXT)";
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
AddSchedule
/* ©muhammad dn version 1.0
* created 2015
* run in 2 threads*/
package com.example.dn;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.database.Cursor;
public class AddSchedule extends Activity implements OnClickListener {
private Button btn_save;
private EditText name,datee, timee ; //gender_n_u
private Schedule_DB_Helper schedHelper;
private SQLiteDatabase dataBase;
private String id,sName,sDate,sTime;
private boolean isUpdate;
private Spinner spin;
//prprivate ArrayList<String> sched_name = new ArrayList<String>();pinner Notifications List
String []notifications = {"5minutes", "10minutes","20minutes","30minutes","1hours"};
//Spinner spin;
String Notifications;
ArrayAdapter<String> adapter;
// Variable for storing current date and time
private int mYear, mMonth, mDay, mHour, mMinute;
String am_pm = "";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_schedule);
spin=(Spinner)findViewById(R.id.Notification_spinner);
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,notifications);
spin.setAdapter(adapter);
btn_save=(Button)findViewById(R.id.btn_save);
name=(EditText)findViewById(R.id.txtSchedName);
datee=(EditText)findViewById(R.id.txtSchedDate1);
timee=(EditText)findViewById(R.id.txtSchedTime);
datee.setOnClickListener(this);
timee.setOnClickListener(this);
btn_save.setOnClickListener(this);
name.setOnClickListener(this);
//add new record
findViewById(R.id.btnAddSchedule).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),
AddPatient.class);
i.putExtra("update", false);
startActivity(i);
}
});
isUpdate=getIntent().getExtras().getBoolean("update");
if(isUpdate)
{
id=getIntent().getExtras().getString("ID");
sName=getIntent().getExtras().getString("NAME");
sDate=getIntent().getExtras().getString("DATE");
sTime=getIntent().getExtras().getString("TIME");
//sNoti=getIntent().getExtras().getString("NOTI");//
name.setText(sName);
datee.setText(sDate);
timee.setText(sTime);
//spin.setTag(sNoti);//
}
schedHelper=new Schedule_DB_Helper(this);
}
//©muhammad saveButton click event
public void onClick(View v) { //\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
if (v == name) {
DbHelper dbHelperInstance = new DbHelper(this);
Cursor cursor = dbHelperInstance.displayPatient();
if(cursor != null) {
EditText pName = (EditText) findViewById(R.id.txtSchedName);
pName.setText(cursor.getString(cursor.getColumnIndex(DbHelper.KEY_NAME)));
}
}
//date and time picking**************************************
if (v == datee) {
// Process to get Current Date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
// Launch Date Picker Dialog
DatePickerDialog dpd = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// Display Selected date in textbox
datee.setText(dayOfMonth + "-"
+ (monthOfYear + 1) + "-" + year);
}
}, mYear, mMonth, mDay);
dpd.show();
}
if (v == timee) {
// Process to get Current Time
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog tpd = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute ) {
//Adding AM:PM in Time
if (c.get(Calendar.AM_PM) == Calendar.AM)
am_pm = "AM";
else if (c.get(Calendar.AM_PM) == Calendar.PM)
am_pm = "PM";
// Display Selected time in textbox
timee.setText(hourOfDay + ":" + minute+" "+am_pm);
}
}, mHour, mMinute, false);
tpd.show();
}
//saving data
if (v == btn_save) {
sName=name.getText().toString().trim();
sDate=datee.getText().toString().trim();
sTime=timee.getText().toString().trim();
// sNoti=spin.getTag().toString().trim();
if(sName.length()>0 && sDate.length()>0 && sTime.length()>0)
{
saveData();
}
else
{
AlertDialog.Builder alertBuilder=new AlertDialog.Builder(AddSchedule.this);
alertBuilder.setTitle("Invalid Data");
alertBuilder.setMessage("Please, Enter valid data");
alertBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertBuilder.create().show();}
}}
//©muhammad Saving Data to SQLite
private void saveData(){
dataBase= schedHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(Schedule_DB_Helper.KEY_NAME, sName);
values.put(Schedule_DB_Helper.KEY_DATE, sDate );
values.put(Schedule_DB_Helper.KEY_TIME, sTime );
//values.put(Schedule_DB_Helper.KEY_NOTI, sNoti );
System.out.println("");
if(isUpdate)
{
//update database with new data
dataBase.update(Schedule_DB_Helper.TABLE_NAME, values, Schedule_DB_Helper.KEY_ID+"="+id, null);
}
else
{
//insert data into database
dataBase.insert(Schedule_DB_Helper.TABLE_NAME, null, values);
}
//close database
dataBase.close();
finish();
}
}
activity_add_schedule
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/note1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#222222"
android:drawableLeft="@drawable/note"
android:drawablePadding="10dp"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp"
android:text="@string/note1"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#ffffff"
android:textSize="12sp" />
<EditText
android:id="@+id/txtSchedName"
android:layout_width="260dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/pname"
android:layout_marginLeft="14dp"
android:ems="10"
android:hint="" >
<requestFocus />
</EditText>
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/txtSchedName"
android:layout_alignRight="@+id/pname"
android:contentDescription="@string/cd1"
android:src="@drawable/search" />
<EditText
android:id="@+id/txtSchedTime"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/TextView02"
android:layout_alignLeft="@+id/txtSchedDate1"
android:layout_alignRight="@+id/txtSchedDate1"
android:ems="10"
android:hint="@string/hint7"
android:nextFocusDown="@+id/btn_save" />
<Button
android:id="@+id/btnAddSchedule"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/pname"
android:layout_alignRight="@+id/pname"
android:layout_below="@+id/note1"
android:drawableLeft="@drawable/add_new"
android:drawablePadding="10dp"
android:onClick="addPatient"
android:text="@string/button_addPatient" />
<Button
android:id="@+id/btn_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:drawableLeft="@drawable/done"
android:drawablePadding="-40dp"
android:text="@string/button_done"
android:textSize="12sp"
android:width="163dp" />
<Button
android:id="@+id/btncancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:drawableLeft="@drawable/cancel"
android:drawablePadding="-30dp"
android:focusableInTouchMode="true"
android:onClick="cancel"
android:text="@string/button_cancel"
android:textSize="12sp"
android:width="164dp" />
<TextView
android:id="@+id/pname"
android:layout_width="291dp"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/txtSchedName"
android:layout_below="@+id/btnAddSchedule"
android:layout_marginTop="15dp"
android:text="@string/pname"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#686868"
android:textSize="12sp" />
<TextView
android:id="@+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/btncancel"
android:layout_alignLeft="@+id/TextView02"
android:layout_marginBottom="34dp"
android:text="@string/textView6"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#686868"
android:textSize="14sp" />
<Spinner
android:id="@+id/Notification_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/btn_save"
android:layout_toRightOf="@+id/TextView01" />
<TextView
android:id="@+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/Notification_spinner"
android:layout_alignLeft="@+id/TextView01"
android:layout_marginBottom="26dp"
android:text="@string/textView5"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#686868"
android:textSize="14sp" />
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/txtSchedTime"
android:layout_alignLeft="@+id/txtSchedName"
android:layout_marginBottom="21dp"
android:text="@string/textView4"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#686868"
android:textSize="14sp" />
<EditText
android:id="@+id/txtSchedDate1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/btn_save"
android:layout_alignRight="@+id/imageView1"
android:layout_alignTop="@+id/TextView01"
android:ems="10"
android:hint="@string/hint6"
android:nextFocusDown="@+id/textTIME" />
<TextView
android:id="@+id/TextView04"
android:layout_width="291dp"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/txtSchedName"
android:layout_below="@+id/txtSchedName"
android:layout_marginTop="17dp"
android:text="ID"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#686868"
android:textSize="12sp" />
<EditText
android:id="@+id/txtID"
android:layout_width="260dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/TextView04"
android:layout_alignBottom="@+id/TextView04"
android:layout_alignLeft="@+id/TextView04"
android:layout_marginLeft="35dp"
android:layout_toLeftOf="@+id/txtSchedDate1"
android:ems="10" />
</RelativeLayout>
答案 0 :(得分:0)
以下是我的应用程序中的一个示例,我想从我的SQLite
数据库中提取某些信息来实例化一个新的自定义对象。我根据UUID
提取了数据。您很可能还有其他方法可以确定从哪个列中提取数据。
// Member variable for selecting all columns in my table
private String[] allColumns = { MyObjectDatabaseHelper.COLUMN_ONE
MyObjectDatabaseHelper.COLUMN_TWO,
MyObjectDatabaseHelper.COLUMN_THREE,
MyObjectDatabaseHelper.COLUMN_FOUR,
MyObjectDatabaseHelper.COLUMN_FIVE,
MyObjectDatabaseHelper.COLUMN_SIX,
MyObjectDatabaseHelper.COLUMN_SEVEN,
MyObjectDatabaseHelper.COLUMN_EIGHT};
public MyObject getSession(UUID mUUID)
{
db = dbHelper.getReadableDatabase();
Cursor cursor = db.query(MyObjectDatabaseHelper.TABLE_MYOBJECT,
allColumns,
MyObjectDatabaseHelper.COLUMN_ONE + "=?",
new String [] {mUUID.toString()},
null,
null,
null,
null);
if (cursor != null)
{
cursor.moveToFirst();
}
MyObject mMyObject = new MyObject(UUID.fromString(cursor.getString(1)),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4),
cursor.getString(5),
cursor.getString(6),
cursor.getInt(7));
cursor.close();
return mMyObject;
}
在这个例子中,我选择了表中的所有列,然后在我的自定义对象的构造函数中使用了所有这些值。您可以做的只是选择一列,如果这就是您所需要的,然后使用该值设置TextView
中的文字。
您可能会这样做:
public getColumnText()
{
String text = cursor.getString(column);
return text;
}
有关query(...)
的详细信息,请参阅here。
public Cursor query(String table,String [] columns,String selection, String [] selectionArgs,String groupBy,String having,String orderBy, 字符串限制)
有关更多SQLite
教程,请参阅以下内容:
http://www.tutorialspoint.com/android/android_sqlite_database.htm
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
http://www.vogella.com/tutorials/AndroidSQLite/article.html#overview_sqlite