lundi 4 mai 2015

how to retrieve specific values from SQLite database (android) and display in an editable textview

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.

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.

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

Aucun commentaire:

Enregistrer un commentaire