【问题标题】:how to retrieve specific values from SQLite database (android) and display in an editable textview如何从 SQLite 数据库(android)中检索特定值并显示在可编辑的文本视图中
【发布时间】:2019-11-21 23:38:15
【问题描述】:

我目前正在构建一个小型 android 应用程序。在我的 MainActivity 中,我有一个微调器,其中填充了我的 SQLite 数据库的“device_names”表中的数据。

当用户选择所需的设备时,他们可以选择更新其信息或删除它。

当他们选择更新时,他们会打开一个新活动,其中包含三个文本视图、设备名称、设备编号和设备密码。这就是我的问题出现的地方。

我对Java很陌生,我不知道如何从上一页的微调器中检索相应的值来填充三个不同的TextView,以便用户可以更新信息。

这是我的主要活动代码:

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) {

    }

}

这是我的更新设备代码:

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);
    }
}

这是我的设备操作文件

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;
    }
}

我希望这对某人有意义。我真的不能让它工作。

我认为在数据库中进行简单搜索以提取与设备名称匹配的所有值效果最好,然后将设备编号属性转换为字符串,将设备密码转换为另一个字符串,我只是无法解决这个问题。

非常感谢 本

【问题讨论】:

    标签: java android string sqlite


    【解决方案1】:

    如果我理解得很好,您的问题是“我如何将旧数据传递给活动,以便用户可以阅读并更新它们?”。 您可以使用putExtra() 发送旧数据。 使用您的intent.putExtra(SELECTED_DEVICE, selecteddevice);,您只发送设备类型,如果您输入其他信息,您可以从UpdateDevice 取回它们,您可以使用旧数据EditText 的SetText()! 像这样,您不需要数据库来获取信息。 你试过吗?

    尝试使用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
    

    如果您需要数据库以获取回收信息,请点击这个非常有用的链接Guide for SqliteHelper

    因此,您需要一个使用 getter 和 setter 方法管理设备的类。 同时,您需要将数据保存在数据库中以备“未来维护”之需。 正如您在该方法的链接中看到的

    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;
    }
    

    您可以通过 id 检索单个联系人(针对您的设备)的所有信息。 或者第二种可以帮助你的方法是

    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;
    }
    

    返回表中所有项目的列表,因此您可以检查类似的内容(将该代码放在需要从数据库中读取所有数据的位置):

    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();
              }
    }
    

    我在这里发布的所有信息都来自我发布的链接。 我写了一些解释以获得更多帮助。 我希望这就是你所需要的! PS:记住Device类的get和set方法!

    【讨论】:

    • 嗨,l 感谢您的回复,我正在寻找的是能够在主要活动上选择一个设备,然后从这里按下“更新所选设备”按钮,这将采取用户更新设备活动。我有那个工作,从这里我只想运行一个查询,它将搜索数据库并在 device_name 列中找到包含所选设备的行,然后获取其他两个值,device_number 和 device_password,并检索它们和将它们放入字符串中,然后可以将其添加到相应的可编辑文本视图中。希望有帮助
    • 您可以在此处查看应用在主活动和更新设备活动上的外观:i.imgur.com/uU03XXD.png 和 i.imgur.com/n14dXLK.png
    • 哦,好吧,所以您需要对数据库进行“简单”查询。所以你需要在你的public class DeviceOperations extends SQLiteOpenHelper 中使用一个方法来获取所有记录,这样你就可以检查正确的设备并检索信息……现在我重新编辑我的帖子,这样我就可以更清楚了!
    • 已发布!我复制并粘贴方法,只需根据您的方式调整代码!
    • 对不起,我还没有成功实现这个。我觉得代码与我看到的有点相似,我只是没有正确配置它。当我有机会尝试时会报告。再次感谢
    猜你喜欢
    • 2015-07-06
    • 2012-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多