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

时间:2015-05-04 16:58:55

标签: java android string sqlite

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

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

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

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

这是我的主要活动代码:

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

我希望这对某人有意义,因为我真的无法让它发挥作用。

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

非常感谢 本

1 个答案:

答案 0 :(得分:0)

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

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

如果您需要DataBase以获取回收信息,请点击此链接,该链接非常有用Guide for SqliteHelper

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

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:记住方法get和set的设备类: