我正在尝试将EditText中的值放入数据库,然后从该数据库中获取值。
我在活动中单击按钮时尝试将值存储在数据库中,如下所示:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class hjhj extends Activity implements OnClickListener {
private EditText txt,txt1;
Button b;
String nam;
String ag;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt = (EditText) findViewById(R.id.EditText01);
txt1= (EditText) findViewById(R.id.EditText02);
b=(Button) this.findViewById(R.id.Button01);
b.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
nam=txt.getText().toString();
ag=txt1.getText().toString();
new DetailsOpenHelper(this);
}
}
DetailsOpenHelper:
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DetailsOpenHelper extends SQLiteOpenHelper{
private static String DATABASE_NAME="employeedatabase";
private static final int DATABASE_VERSION = 2;
private static final String DETAILS_TABLE_NAME = "employeedetails";
private static String nam;
private static String ag;
static String NAME=nam;
static String AGE=ag;
private String KEY_ROWID;
private static final String DETAILS_TABLE_CREATE =
"CREATE TABLE " + DETAILS_TABLE_NAME + " (" +
NAME + " TEXT, " +
AGE + " TEXT);";
private SQLiteOpenHelper mSQL;
private SQLiteDatabase db;
public DetailsOpenHelper(hjhj hjhj){
super(hjhj, DATABASE_NAME, null,DATABASE_VERSION );
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DETAILS_TABLE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DETAILS_TABLE_IF_NOT_EXISTS");
onCreate(db);
}
public void open() throws SQLException
{
DetailsOpenHelper mSQL = new DetailsOpenHelper(null);
db = mSQL.getWritableDatabase();
}
private void addDetails( String nam, String ag) {
SQLiteDatabase db = mSQL.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(NAME, nam);
//values.put(TIME, System.currentTimeMillis());
values.put(AGE, ag);
db.insert(DETAILS_TABLE_NAME, null, values);
}
public Cursor getAllDetails()
{
return db.query(DETAILS_TABLE_NAME, new String[] {
KEY_ROWID,
NAME,
AGE }, null, null, null, null, null, null);
}
public boolean updateDetails(long rowId, String nam,
String ag)
{
ContentValues args = new ContentValues();
args.put(NAME, nam);
args.put(AGE, ag);
return db.update(DETAILS_TABLE_NAME, args,
KEY_ROWID + "=" + rowId, null) > 0;
}
}
我想在单击按钮时存储和检索值。如果你知道的话,请任何人帮助我。我已经尝试了很多。
另外,如何使用命令提示符查看数据库?
答案 0 :(得分:1)
ReminderDbAdopter.java (simply a java class)
package com.studentdemo;
import java.util.ArrayList;
import java.util.List;
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.SQLiteOpenHelper;
public class RemindersDbAdapter {
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
// Not used, but you could upgrade the database with ALTER
// Scripts
}
}
private static final String DATABASE_NAME = "studinfo";
private static final String DATABASE_TABLE = "student";
private static final int DATABASE_VERSION = 1;
public static final String USERNAME= "title";
public static final String ROLLNUM = "id";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_CREATE =
"create table " + DATABASE_TABLE + "("
+ ROLLNUM + " integer primary key autoincrement, "
+ USERNAME + " text not null);";
private final Context mCtx;
public RemindersDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public RemindersDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public long createReminder(String title) {
ContentValues initialValues = new ContentValues();
initialValues.put(USERNAME, title);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteReminder(long rowId) {
return
mDb.delete(DATABASE_TABLE, ROLLNUM + "=" + rowId, null) > 0;
}
public Cursor fetchAllReminders() {
return mDb.query(DATABASE_TABLE, new String[] {ROLLNUM,USERNAME}, null, null, null, null, null);
}
public Cursor fetchReminder(long rowId) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {ROLLNUM,
USERNAME, }, ROLLNUM + "=" +
rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updateReminder(long rowId, String title) {
ContentValues args = new ContentValues();
args.put(USERNAME, title);
return
mDb.update(DATABASE_TABLE, args,ROLLNUM + "=" + rowId, null) > 0;
}
// The SQLiteOpenHelper class was omitted for brevity
// That code goes here.
}
ReminderEditActivity (main activity)
package com.studentdemo;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class ReminderEditActivity extends Activity {
private RemindersDbAdapter mDbHelper;
private EditText mTitleText;
private Button mConfirmButton;
private Long mRowId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new RemindersDbAdapter(this);
setContentView(R.layout.reminder_edit);
mTitleText = (EditText) findViewById(R.id.title);
setmConfirmButton((Button) findViewById(R.id.confirm));
mRowId = savedInstanceState != null
? savedInstanceState.getLong(RemindersDbAdapter.ROLLNUM): null;
registerButtonListenersAndSetDefaultText();
}
private void registerButtonListenersAndSetDefaultText() {
{
mConfirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
saveState();
setResult(RESULT_OK);
Toast.makeText(ReminderEditActivity.this,
getString(R.string.hello),
Toast.LENGTH_SHORT).show();
finish();
}
});
}
}
private void setRowIdFromIntent() {
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null
? extras.getLong(RemindersDbAdapter.ROLLNUM)
: null;
}
}
@Override
protected void onPause() {
super.onPause();
mDbHelper.close();
}
@Override
protected void onResume() {
super.onResume();
mDbHelper.open();
setRowIdFromIntent();
populateFields();
}
// Date picker, button click events, and buttonText updating, createDialog
// left out for brevity
// they normally go here ...
private void populateFields() {
if (mRowId != null) {
Cursor reminder = mDbHelper.fetchReminder(mRowId);
startManagingCursor(reminder);
mTitleText.setText(reminder.getString(
reminder.getColumnIndexOrThrow(RemindersDbAdapter.USERNAME)));
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong(RemindersDbAdapter.ROLLNUM, mRowId);
}
private void saveState() {
String title = mTitleText.getText().toString();
if (mRowId == null) {
long id = mDbHelper.createReminder(title);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateReminder(mRowId, title);
}
}
public void setmConfirmButton(Button mConfirmButton) {
this.mConfirmButton = mConfirmButton;
}
public Button getmConfirmButton() {
return mConfirmButton;
}
}
reminder_edit.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/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Write student information:"/>
<EditText
android:id="@+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@android:drawable/editbox_background"
android:layout_below="@id/label"/>
<Button
android:id="@+id/confirm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/title"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dip"
android:text="save" />
</RelativeLayout>
then run the program
you can find the database 1.click start button in your window
2.choose run
3.type adb shell(before it you set the path of adb in mycomputer properties C:\Program Files\Android\android-sdk-windows\platforms)
4.then type
cd data
cd data
cd your packagename
cd databases
sqlite3 studinfo
.tables
you find ur table name
答案 1 :(得分:0)
我在我的一个项目中完成了这项任务,以便记住用户名&amp;密码选项。 在这里,有2个EditView和ImageButton用于记住用户名和密码。 当用户点击记住按钮时,他的用户名将密码保存在数据库中。 请参阅下面的代码并尝试从中获取帮助:
final ImageButton login=(ImageButton)findViewById(R.id.Login);
final ImageButton register=(ImageButton)findViewById(R.id.Register);
final ImageButton remember=(ImageButton)findViewById(R.id.remember);
this.myDbAdapter=new DBAdapter(this);
List<String> email = this.myDbAdapter.selectAll();
editText1=(EditText)findViewById(R.id.emailText);
editText2=(EditText)findViewById(R.id.passwordText);
if(!email.isEmpty()){
remember.setBackgroundResource(R.drawable.checked);
editText1.setText(email.get(0));
editText2.setText(email.get(1));
}
remember.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(Config.rememberLogin==0){
remember.setBackgroundResource(R.drawable.checked);
Config.rememberLogin=1;
//myDbAdapter.deleteAll();
myDbAdapter.insert(editText1.getText()+"",editText2.getText()+"");
}
else{
remember.setBackgroundResource(R.drawable.check_none);
Config.rememberLogin=0;
myDbAdapter.deleteAll();
}
}
});
其中 rememberLogin是Config类的公共静态int成员,用于检查是否使用了remember按钮。 这是函数 selectAll()&amp; deleteDll()myDbAdapter 类:
public void deleteAll()
{
this.db.delete(TABLE_NAME, null, null);
}
public List<String> selectAll() {
List<String> list = new ArrayList<String>();
Cursor cursor = this.db.query(TABLE_NAME, new String[] {"email","password"},
null, null, null, null,null);
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
list.add(cursor.getString(1));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
希望这些代码可以帮助你......:)
答案 2 :(得分:0)
首先,使用应用程序启动本身调用Database类并与之建立连接。
正如我所看到的,从onClick()方法调用了新的DetailsOpenHelper(this),每次单击按钮时都会打开连接。
在Onclick()方法中调用addDetails()方法并传递editText值。
我希望这会对你的情况有所帮助。
答案 3 :(得分:0)
它非常大使...
试试这段代码
final EditText edit_name=(EditText)findViewById(R.id.edit_name);
final EditText edit_phone_numer=(EditText)findViewById(R.id.edit_phone_number);
Button add_new=(Button)findViewById(R.id.button_add_new);
Button saved_data=(Button)findViewById(R.id.button_saved_data);
Button more_option=(Button)findViewById(R.id.button_delete);
final Table tb=new Table(this);
final String _name=edit_name.getText().toString();
final String _phone_number=edit_phone_numer.getText().toString();
System.out.println(_name);
//Toast.makeText(getBaseContext(), _name, Toast.LENGTH_LONG).show();
System.out.println(_phone_number);
add_new.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
edit_name.setText("");
edit_phone_numer.setText("");
}
});
saved_data.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
tb.open();
final String _name=edit_name.getText().toString();
final String _phone_number=edit_phone_numer.getText().toString();
System.out.println(_name);
Toast.makeText(getBaseContext(), "Record Saved", Toast.LENGTH_LONG).show();
System.out.println(_phone_number);
tb.createemployee(_name, _phone_number);
tb.delete("12");
tb.close();
}
});
more_option.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, moreoption.class);
startActivity(i);
}
});
答案 4 :(得分:0)
确定。我不知道你是否已经得到了你的答案,但是因为你没有标记任何我认为你没有。如果任何答案让你朝着正确的方向前进,你应该标记它。
假设您的代码不包含任何错误(我没有测试它)。
要将值存储在数据库中: 在此代码之后:new DetailsOpenHelper(this);在onClick中,使用nam和ag变量调用addDetails函数。就是这样。
要从数据库中检索值: 有一个函数(getAllDetails)将返回一个游标,公开数据库中的每个记录。你可以稍微修改一下,只露出一条记录。如果你想了解这一点,请告诉我。使用该功能: 经过上述修改后:
Cursor cursor = getAllDetails(); cursor.moveToFirst(); nam = cursor.getString(cursor.getColumnIndex(“nam”)); ag = cursor.getString(cursor.getColumnIndex(“ag”)); txt.setText(NAM); txt.setText(AG);
这应该会让您的第一个代码运行,但我建议您学习使用listView来显示光标的结果。
祝你好运