如何从SQLite数据库(android)中检索特定值并显示在可编辑的textview中

时间:2021-12-02 15:15:22

I am currently building a small android device. On my main page I have a spinner that is populated with "device_names" from my SQLite database.

我目前正在构建一个小型Android设备。在我的主页面上,我有一个使用SQLite数据库中的“device_names”填充的微调器。

When I user selects the desired device, they then have the option to update its information or delete it.

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

when they select update, they oopen 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 textviews so that the user can udpate the information.

我是Java的新手,我无法弄清楚如何从上一页的微调器中检索相应的值来填充三个不同的文本视图,以便用户可以更新信息。

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, as 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

非常感谢Ben

1 个解决方案

#1


0  

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(). With your 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! Like that you don't need the Database for take back information. Have you try this?

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

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

如果您需要DataBase来获取回收信息,请点击此链接,这对SqliteHelper非常有帮助

So, you need a class that manage the devices with the getter and setter method. 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

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

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. Or the second method that can help you is

您可以收回按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;
}

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类!

#1


0  

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(). With your 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! Like that you don't need the Database for take back information. Have you try this?

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

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

如果您需要DataBase来获取回收信息,请点击此链接,这对SqliteHelper非常有帮助

So, you need a class that manage the devices with the getter and setter method. 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

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

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. Or the second method that can help you is

您可以收回按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;
}

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类!