[英]how to retrieve specific values from SQLite database (android) and display in an editable textview
I am currently building a small android application.我目前正在构建一个小型 android 应用程序。 On my MainActivity I have a spinner which is populated with data from the "device_names" table of my SQLite database.
在我的 MainActivity 上,我有一个微调器,其中填充了来自我的 SQLite 数据库的“device_names”表中的数据。
When the user selects the desired device, they then have the option to update its information or delete it.当用户选择所需的设备时,他们可以选择更新或删除它的信息。
When they select update, they open a new activity with three text views, device name, device number and device password.当他们选择更新时,他们会打开一个包含三个文本视图、设备名称、设备编号和设备密码的新活动。 This is where my problem arises.
这就是我的问题出现的地方。
I am very new to Java, and I can't figure out how to retrieve the corresponding values from the spinner on the previous page to populate the three different TextView so that the user can update the information.我对Java很陌生,我无法弄清楚如何从上一页的微调器中检索相应的值来填充三个不同的TextView,以便用户可以更新信息。
Here is my main activity code:这是我的主要活动代码:
package ben.findmyflock;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class DeviceManager extends Activity implements AdapterView.OnItemSelectedListener{
Spinner spinner;
private Button newActivity;
public final static String SELECTED_DEVICE = "ben.findmyflock.DEVICE";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_manager);
spinner= (Spinner) findViewById(R.id.device_spinner);
/*ArrayAdapter adapter=ArrayAdapter.createFromResource(this,R.array.device_array,android.R.layout.simple_spinner_item);
spinner.setAdapter(adapter);*/
spinner.setOnItemSelectedListener(this);
loadSpinnerData();
}
/**
* Function to load the spinner data from SQLite database
* */
private void loadSpinnerData() {
// database handler
DeviceOperations db = new DeviceOperations(getApplicationContext());
// Spinner Drop down elements
List<String> labels = db.getAllLabels();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, labels);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
public void addNewDevice(View v) {
//do something when a button is clicked
Button adddevicebutton=(Button) v;
startActivity(new Intent(getApplicationContext(), AddDevice.class));
}
public void updateSelectedDevice(View v) {
Intent intent = new Intent(this, UpdateDevice.class);
Spinner spinner = (Spinner) findViewById(R.id.device_spinner);
String selecteddevice = spinner.getSelectedItem().toString();
intent.putExtra(SELECTED_DEVICE, selecteddevice);
startActivity(intent);
}
public void deleteSelectedDevice(View v) {
//delete selected spinner value from database
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_device_manager, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TextView myText= (TextView) view;
Toast.makeText(this,myText.getText() + " Selected", Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
Here my Update Device code:这是我的更新设备代码:
package ben.findmyflock;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class UpdateDevice extends Activity {
ListView listview;
SQLiteDatabase sqLiteDatabse;
DeviceOperations deviceOperations;
Cursor cursor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_device);
Intent intent = getIntent();
String selecteddevice = intent.getStringExtra(DeviceManager.SELECTED_DEVICE);
EditText devname = (EditText)findViewById(R.id.update_device_name);
devname.setText(selecteddevice, TextView.BufferType.EDITABLE);
EditText devnum = (EditText)findViewById(R.id.update_device_number);
deviceOperations = new DeviceOperations(getApplicationContext());
sqLiteDatabse =deviceOperations.getReadableDatabase();
cursor = deviceOperations.getInformation(sqLiteDatabse);
if(cursor.moveToFirst())
{
do {
String name,num,pass;
name = cursor.getString(0);
num = cursor.getString(1);
pass = cursor.getString(2);
}while (cursor.moveToNext());
}
devnum.setText(selecteddevicenumber, TextView.BufferType.EDITABLE);
EditText devpass = (EditText)findViewById(R.id.update_device_password);
devpass.setText(selecteddevicepassword, TextView.BufferType.EDITABLE);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_update_device, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And here is my Device Operations File这是我的设备操作文件
package ben.findmyflock;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Created by Ben on 03/05/2015.
*/
public class DeviceOperations extends SQLiteOpenHelper{
// Database Version
public static final int database_version = 1;
// Database Name
public static final String DATABASE_NAME = "device_database";
// Labels table name
public static final String TABLE_NAME = "device_info";
// Labels Table Columns names
public static final String DEVICE_NAME = "device_name";
public static final String DEVICE_NUMBER = "device_number";
public static final String DEVICE_PASSWORD = "device_password";
private static final String[] COLUMNS = {DEVICE_NAME,DEVICE_NUMBER,DEVICE_PASSWORD};
public DeviceOperations(Context context) {
super(context, DATABASE_NAME, null, database_version);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
// Category table create query
String CREATE_DEVICE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + DEVICE_NAME + " TEXT," + DEVICE_NUMBER + " INTEGER" + DEVICE_PASSWORD + " TEXT)";
db.execSQL(CREATE_DEVICE_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
// Create tables again
onCreate(db);
}
//Inserting values
public void putInformation(DeviceOperations dop,String name,String number,String pass)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DEVICE_PASSWORD, pass);
values.put(DEVICE_NUMBER, number);
values.put(DEVICE_NAME, name);
db.insert(TABLE_NAME, null, values);
db.close();
}
public Cursor getInformation(SQLiteDatabase db)
{
Cursor cursor;
String[] projections = {DEVICE_NAME, DEVICE_NUMBER, DEVICE_PASSWORD};
cursor = db.query(TABLE_NAME,projections,null,null,null,null,null);
return cursor;
}
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;
}
}
I hope this makes sense to someone.我希望这对某人有意义。 I really cant get it to work.
我真的无法让它工作。
I think a simple search within the database to extract all the values that match the device name would work best and then convert the device number attribute to a string and the device password to another string, i just cant work that bit out.我认为在数据库中进行简单的搜索以提取与设备名称匹配的所有值最有效,然后将设备编号属性转换为字符串,将设备密码转换为另一个字符串,我只是无法解决这个问题。
Many Thanks Ben非常感谢本
If i understood well, your problem is "how can i pass to the activity the old data so the user can read them and update?".如果我理解得很好,您的问题是“我如何将旧数据传递给活动,以便用户可以读取它们并更新?”。 You can send the old data with the
putExtra()
.您可以使用
putExtra()
发送旧数据。 With your intent.putExtra(SELECTED_DEVICE, selecteddevice);
随着你的
intent.putExtra(SELECTED_DEVICE, selecteddevice);
you send only the type of device, if you put other information you can take them back from the UpdateDevice
and you can SetText()
of your EditText
with the old data!您只发送设备类型,如果您输入其他信息,您可以从
UpdateDevice
它们,并且您可以使用旧数据对EditText
进行SetText()
! Like that you don't need the Database for take back information.就像那样,您不需要数据库来收回信息。 Have you try this?
你试过这个吗?
Try to Start activity with StartActivityForResult
, and take back new information with:尝试使用
StartActivityForResult
开始活动,并通过以下方式取回新信息:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 1) {
if (resultCode == RESULT_OK) {
String result1 = data.getStringExtra("result1");
String result2 = data.getStringExtra("result2");
String result3 = data.getStringExtra("result3");
//Update the database with new data
}
if (resultCode == RESULT_CANCELED) {
//No change
}
}
}//onActivityResult
If you need the DataBase for take back information follow this link that is very helpfull Guide for SqliteHelper如果您需要数据库以获取收回信息,请点击此链接,该链接对 SqliteHelper非常有用
So, you need a class that manage the devices with the getter and setter method.因此,您需要一个使用 getter 和 setter 方法管理设备的类。 In the same time you need to save data in your DataBase for the "future maintenace".
同时,您需要将数据保存在您的数据库中以备“未来维护”之用。 As you can see in the link with the method
正如您在方法链接中看到的
getContact()
// Getting single contact
public Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
You can take back all information for a single Contact (for you device) searching it by id.您可以通过 ID 检索单个联系人(对于您的设备)的所有信息。 Or the second method that can help you is
或者可以帮助您的第二种方法是
getAllContacts()
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
That return a list of all items inside the table, so you can check something like that (put that code where you need to read all data from database):这将返回表中所有项目的列表,因此您可以检查类似的内容(将该代码放在需要从数据库读取所有数据的位置):
DatabaseHandler db = new DatabaseHandler(this);
// Reading all device
List<Device> devices = db.getAllContacts();
for (Device dev : devices) {
if(dev.getNameDevice() == DeviceToUpadeName){
//do the get of all information
device_number = dev.getDeviceNumber();//This getmethod is from you Device Class
device_password = dev.getDevicePassword();
}
}
All the information that i post here are from the link that i post.我在这里发布的所有信息都来自我发布的链接。 I write some explanation for more help.
我写了一些解释以获得更多帮助。 I hope it's all that you need!
我希望这就是你所需要的! PS:Remeber the Device class fot the method get and set!
PS:记住get和set方法的Device类!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.