从sqlite获取数据并在gridview中显示

时间:2015-01-07 11:44:59

标签: android sqlite gridview

我在SQLite数据库中有150条记录。我想在网格视图中显示数据库中的1行。用户将在编辑文本中输入代码,我想根据数据库中的代码选择记录并显示在网格视图中。我已经使用以下方法从数据库中获取数据,但我不知道如何在网格视图中插入值。

从SQLite获取数据的方法:

public String[][] SelectDocData( String drcode) {
 // TODO Auto-generated method stub
try {

  String arrData[][] = null; 
  SQLiteDatabase db;
  db = this.getReadableDatabase(); // Read Data
  String strSQL = "select * from table = drcode" ;
  Cursor cursor = db.rawQuery(strSQL, null);
  if(cursor != null)
  {

  if (cursor.moveToFirst()) {
  arrData = new String[cursor.getCount()][cursor.getColumnCount()];

 int i= 0;
 do {               
 arrData[i][0] = cursor.getString(0);
 arrData[i][1] = cursor.getString(1);
 arrData[i][2] = cursor.getString(2);
 i++;

} while (cursor.moveToNext());                     
}}

cursor.close();
return arrData;

} catch (Exception e) {

return null;
}
}

1 个答案:

答案 0 :(得分:7)

GridView设置适配器就像ListView适配器一样。我想在这里展示一个例子。

这是Gridview(activity_main.xml)的XML布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.griddemo.MainActivity" >

<EditText
    android:id="@+id/et_empcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

<GridView
    android:id="@+id/gv_emp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:numColumns="3"
    android:horizontalSpacing="4dp"
    android:verticalSpacing="4dp"
    android:layout_below="@+id/et_empcode" >
</GridView>

</RelativeLayout>

这是GridView

项目的另一个布局文件(layout_grid_item.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff00ff"
android:orientation="vertical" >

<TextView
    android:id="@+id/tv_emp_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="ID" />

<TextView
    android:id="@+id/tv_emp_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="name" />

<TextView
    android:id="@+id/tv_emp_email"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Email" />

<TextView
    android:id="@+id/tv_emp_address"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Address" />

</LinearLayout>

这是适配器类(MyAdapter.java

public class MyAdapter extends BaseAdapter {
Context context;
ArrayList<Employee> empList;
private static LayoutInflater inflater = null;

public MyAdapter(Context context, ArrayList<Employee> empList) {
    this.context = context;
    this.empList = empList;
    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return empList.size();
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    if (convertView == null)
        convertView = inflater.inflate(R.layout.layout_grid_item, null);

    TextView codeTextView = (TextView) convertView.findViewById(R.id.tv_emp_id);
    TextView nameTextView = (TextView) convertView.findViewById(R.id.tv_emp_name);
    TextView emailTextView = (TextView) convertView.findViewById(R.id.tv_emp_email);
    TextView addressTextView = (TextView) convertView.findViewById(R.id.tv_emp_address);

    Employee e = new Employee();
    e = empList.get(position);
    codeTextView.setText("Code: " + String.valueOf(e.getCode()));
    nameTextView.setText("Name: " + e.getName());
    emailTextView.setText("Email: " + e.getEmail());
    addressTextView.setText("Address: " + e.getAddress());
    return convertView;
}

}

这是模型类(Employee.java)

package com.example.griddemo;

public class Employee {

int code;
String name, email, address;

/* Setters */ 
public void setCode(int code) {
    this.code = code;
}

public void setName(String name) {
    this.name = name;
}

public void setEmail(String email) {
    this.email = email;
}

public void setAddress(String address) {
    this.address = address;
}

/* Getters */ 
public int getCode() {
    return this.code;
}

public String getName() {
    return this.name;
}

public String getEmail() {
    return this.email;
}

public String getAddress() {
    return this.address;
}
}

这是处理数据库操作的类(DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper {

private String TAG = this.getClass().getSimpleName();

private static final String DATABASE_NAME = "emp_db";
private static final int DATABASE_VERSION = 1;

// TABLE NAMES
private static final String TABLE_EMP = "employee";

/* Keys for Table Employee */ 
private static final String KEY_CODE = "code";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_ADDRESS = "address";

String CREATE_TABLE_CALL = "CREATE TABLE " + TABLE_EMP + "(" + KEY_CODE + " INTEGER," + KEY_NAME + " TEXT," + KEY_EMAIL + " TEXT," + KEY_ADDRESS
        + ")";

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    // TODO Auto-generated constructor stub
}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    Log.v(TAG, "CREATE TABLE CALL: " + CREATE_TABLE_CALL);
    db.execSQL(CREATE_TABLE_CALL);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_EMP);
    onCreate(db);
}

/* Method to create a Employee */ 
public long createEmployee(Employee emp) {
    long c;

    SQLiteDatabase database = getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_CODE, emp.getCode());
    values.put(KEY_NAME, emp.getName());
    values.put(KEY_EMAIL, emp.getEmail());
    values.put(KEY_ADDRESS, emp.getAddress());

    c = database.insert(TABLE_EMP, null, values);
    database.close();
    return c;

}

/* Method for fetching record from Database */
public ArrayList<Employee> getAllEmployee() {
    String query = "SELECT * FROM " + TABLE_EMP;
    ArrayList<Employee> employees = new ArrayList<Employee>();
    SQLiteDatabase database = getReadableDatabase();
    Cursor c = database.rawQuery(query, null);
    if (c != null) {
        while (c.moveToNext()) {
            int code = c.getInt(c.getColumnIndex(KEY_CODE));
            String name = c.getString(c.getColumnIndex(KEY_NAME));
            String email = c.getString(c.getColumnIndex(KEY_EMAIL));
            String address = c.getString(c.getColumnIndex(KEY_ADDRESS));

            Employee emp = new Employee();
            emp.setCode(code);
            emp.setName(name);
            emp.setEmail(email);
            emp.setAddress(address);

            Log.v("DBHelper: ", "Name: " + name);
            Log.v("DBHelper: ", "Code: " + code);
            Log.v("DBHelper: ", "Email: " + email);
            Log.v("DBHelper: ", "Address: " + address);

            employees.add(emp);
        }
    }

    return employees;

}
/* This method is used to get a single record from Database. 
   I have given an example, you have to do something like this. */

public Employee getEmployeeByCode(int code)
{
    String query = "SELECT * FROM " + TABLE_EMP+ " WHERE "+ KEY_CODE + " = " +code;
    Employee emp = new Employee();
    SQLiteDatabase database = getReadableDatabase();
    Cursor c = database.rawQuery(query, null);  

    if (c.getCount() > 0) {

        c.moveToFirst();
        int code = c.getInt(c.getColumnIndex(KEY_CODE));
        String name = c.getString(c.getColumnIndex(KEY_NAME));
        String email = c.getString(c.getColumnIndex(KEY_EMAIL));
        String address = c.getString(c.getColumnIndex(KEY_ADDRESS));

        emp.setCode(code);
        emp.setName(name);
        emp.setEmail(email);
        emp.setAddress(address);

        Log.v("DBHelper: ", "Name: " + name);
        Log.v("DBHelper: ", "Code: " + code);
        Log.v("DBHelper: ", "Email: " + email);
        Log.v("DBHelper: ", "Address: " + address);


    }
    return emp;
}

这是MainActivity.java

public class MainActivity extends Activity {

GridView gridView;
ArrayList<Employee> employeeList;
MyAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    gridView = (GridView) findViewById(R.id.gv_emp);

    DatabaseHelper databaseHelper = new DatabaseHelper(MainActivity.this);
    employeeList = new ArrayList<Employee>();

    employeeList = databaseHelper.getAllEmployee();
    adapter = new MyAdapter(MainActivity.this, employeeList);
    gridView.setAdapter(adapter);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, 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();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}