从SQLite数据库填充表格布局

时间:2015-08-19 11:24:12

标签: android sqlite

我在数据库中填充TableLayout。我创建了一个方法buildTable来从数据库中获取数据并动态创建表行,在MainActivity onCreate方法中调用该方法。一切都很好,没有错误,但是当我运行应用程序时,它没有显示带有数据的表。

以下是我的主要活动:

public class MainActivity extends AppCompatActivity {
    private EditText userName, Password ,salary, Address, name;
    private TableLayout t1;
    TestDatabaseAdapter testHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        userName = (EditText) findViewById(R.id.userNameEditText);
        Password = (EditText) findViewById(R.id.passwordEditText);
        salary = (EditText) findViewById(R.id.salaryEditText);
        Address = (EditText) findViewById(R.id.addressEditText);
        name = (EditText) findViewById(R.id.searchTextView);
       t1 = (TableLayout) findViewById(R.id.main_table);

        testHelper = new TestDatabaseAdapter(this);
        BuildTable();

    }
    private void BuildTable() {
        Cursor mCur = testHelper.populateTable();
        Message.message(this, "Successfully inserted a row at "+mCur.getCount());
        if (mCur.getCount() != 0) {
            if (mCur.moveToFirst()) {
                do {
                    int rows = mCur.getCount();
                    int cols = mCur.getColumnCount();

                    // outer for loop
                    for (int i = 0; i < rows; i++) {

                        TableRow row = new TableRow(this);
                        TableLayout.LayoutParams tableRowParams=
                                new TableLayout.LayoutParams
                                        (TableLayout.LayoutParams.MATCH_PARENT,TableLayout.LayoutParams.WRAP_CONTENT);
                        row.setLayoutParams(tableRowParams);

                        // inner for loop
                        for (int j = 0; j < cols; j++) {

                            TextView tv = new TextView(this);
                            tv.setLayoutParams(new ViewGroup.LayoutParams(
                                    ViewGroup.LayoutParams.WRAP_CONTENT,
                                    ViewGroup.LayoutParams.WRAP_CONTENT));
                            tv.setGravity(Gravity.CENTER);
                            tv.setTextSize(18);
                            tv.setPadding(0, 5, 0, 5);

                            tv.setText(mCur.getString(j));
                            row.addView(tv);

                        }
                        t1.addView(row);
                    }
                } while (mCur.moveToNext());
            }
        }
    }


    public void addUser(View view){

        String user = userName.getText().toString();
        String pass = Password.getText().toString();
        String sal = salary.getText().toString();
        String add = Address.getText().toString();

        long id = testHelper.insertData(user,pass,sal,add);
        if (id<0){
            Message.message(this, "Unsuccessful");
        }
        else {
            Message.message(this, "Successfully inserted a row at "+id);
        }
    }


    public void getUserDetails(View view){
        String data = testHelper.getAllData();
        Message.message(this, data);
    }


    public void getSingleUserDetails(View view){
        String s1 = name.getText().toString();

        if (!(s1.isEmpty())) {
            String sub1 = s1.substring(0,s1.indexOf(" "));
            String sub2 = s1.substring(s1.indexOf(" ")+1);

            String data = testHelper.getSingleUserDate(sub1,sub2);
            if (data.isEmpty()){
                Message.message(this, "No record found");
            }
            else {
                Message.message(this, data);
            }
        } else {
            Message.message(this, "Enter Some Text ");
        }
    }


    public void update(View view){
        String s1 = name.getText().toString();

        if (!(s1.isEmpty())) {
            String sub1 = s1.substring(0,s1.indexOf(" "));
            String sub2 = s1.substring(s1.indexOf(" ")+1);

            int data = testHelper.updateAddress(sub1, sub2);
            if (data<1){
                Message.message(this, "No record found");
            }
            else {
                Message.message(this, data+ " : Rows Successfully updated ");
            }
        } else {
            Message.message(this, "Enter Some Text ");
        }
    }

    public void delete(View view){
        String s1 = name.getText().toString();

        if (!(s1.isEmpty())) {
            String sub1 = s1.substring(0,s1.indexOf(" "));
            String sub2 = s1.substring(s1.indexOf(" ")+1);

            int data = testHelper.deletebyName(sub1, sub2);
            if (data<1){
                Message.message(this, "No record found");
            }
            else {
                Message.message(this, data+ " : Rows Successfully deleted ");
            }
        } else {
            Message.message(this, "Enter Some Text ");
        }
    }


    @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_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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

这是我的activity_main

        <?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/RelativeLayout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        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=".MainActivity"
        android:weightSum="1">

        <TextView
            android:id="@+id/Linealayout1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/userNameTextView"
            android:textSize="20dp" />

        <EditText
            android:id="@+id/userNameEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/PassWordTextView"
            android:textSize="20dp" />

        <EditText
            android:id="@+id/passwordEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:ems="10"
            android:inputType="textPassword" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/SalaryTextView"
            android:textSize="20dp" />

        <EditText
            android:id="@+id/salaryEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/AddressTextView"
            android:textSize="20dp" />

        <EditText
            android:id="@+id/addressEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="addUser"
            android:text="@string/AddUserButton" />

        <Button
            android:id="@+id/detailsButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="BuildTable"
            android:text="Get User Details" />

        <EditText
            android:id="@+id/searchTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:hint="Enter Name of person" />

        <Button
            android:id="@+id/button2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:onClick="getSingleUserDetails"
            android:text="Get User Salary &amp; Address " />

        <Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Update"
            android:id="@+id/button3"
            android:layout_gravity="center_horizontal"
            android:onClick="update" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Delete"
            android:id="@+id/button4"
            android:layout_gravity="center_horizontal"
            android:onClick="delete" />

        <TableLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/main_table"
            android:background="#8cff9d2c"></TableLayout>

    </LinearLayout>
    </ScrollView>

类: Message.java

public class Message {
    public static void message(Context context, String message){
        Toast.makeText(context , message, Toast.LENGTH_LONG).show();
    }
}

类:TestDatabaseAdapter.java

  public class TestDatabaseAdapter {

    TestHelper testHelper;

    public TestDatabaseAdapter(Context context) {
        testHelper = new TestHelper(context);
    }

    public long insertData(String name, String password, String salary, String Address) {

        SQLiteDatabase db = testHelper.getWritableDatabase();

        ContentValues contentValues = new ContentValues();
        contentValues.put(TestHelper.EMPLOYEE_NAME, name);
        contentValues.put(TestHelper.EMPLOYEE_PASSWORD, password);
        contentValues.put(TestHelper.EMPLOYEE_SALARY, salary);
        contentValues.put(TestHelper.EMPLOYEE_ADDRESS, Address);

        long id = db.insert(testHelper.TABLE_NAME, null, contentValues);
        return id;
    }
    public Cursor populateTable(){
        SQLiteDatabase db = testHelper.getReadableDatabase();
        String[] columns = {TestHelper.EMPLOYEE_ID, TestHelper.EMPLOYEE_NAME, TestHelper.EMPLOYEE_PASSWORD, TestHelper.EMPLOYEE_SALARY, TestHelper.EMPLOYEE_ADDRESS};
        Cursor cursor = db.query(TestHelper.TABLE_NAME, columns, null, null, null, null, null);


    return cursor;
    }
    public String getAllData() {
        SQLiteDatabase db = testHelper.getReadableDatabase();

        //select * from EmployeeTable
        String[] columns = {TestHelper.EMPLOYEE_ID, TestHelper.EMPLOYEE_NAME, TestHelper.EMPLOYEE_PASSWORD, TestHelper.EMPLOYEE_SALARY, TestHelper.EMPLOYEE_ADDRESS};
        Cursor cursor = db.query(TestHelper.TABLE_NAME, columns, null, null, null, null, null);

        StringBuffer buffer = new StringBuffer();
        while (cursor.moveToNext()) {
            int c1 = cursor.getColumnIndex(TestHelper.EMPLOYEE_ID);
            int c2 = cursor.getColumnIndex(TestHelper.EMPLOYEE_NAME);
            int c3 = cursor.getColumnIndex(TestHelper.EMPLOYEE_PASSWORD);
            int c4 = cursor.getColumnIndex(TestHelper.EMPLOYEE_SALARY);
            int c5 = cursor.getColumnIndex(TestHelper.EMPLOYEE_ADDRESS);

            int id = cursor.getInt(c1);
            String name = cursor.getString(c2);
            String pass = cursor.getString(c3);
            String salary = cursor.getString(c4);
            String address = cursor.getString(c5);

            buffer.append(id + " " + name + " " + pass + " " + salary + " " + address + "\n");
        }
        return buffer.toString();
    }

    public String getSingleUserDate(String searchName,String searchPass) {
        SQLiteDatabase db = testHelper.getReadableDatabase();

        //select salary & address from EmployeeTable where name = ? AND pass = ?
        String[] columns = {TestHelper.EMPLOYEE_SALARY, TestHelper.EMPLOYEE_ADDRESS};
        String[] selectionArgs={searchName,searchPass};
        Cursor cursor = db.query(TestHelper.TABLE_NAME, columns, TestHelper.EMPLOYEE_NAME + " =? AND "+TestHelper.EMPLOYEE_PASSWORD+ " =?", selectionArgs, null, null, null, null);

        StringBuffer buffer = new StringBuffer();
        while (cursor.moveToNext()) {
         /*   int c1 = cursor.getColumnIndex(TestHelper.EMPLOYEE_ID);
            int c2 = cursor.getColumnIndex(TestHelper.EMPLOYEE_NAME);
            int c3 = cursor.getColumnIndex(TestHelper.EMPLOYEE_PASSWORD);*/
            int c4 = cursor.getColumnIndex(TestHelper.EMPLOYEE_SALARY);
            int c5 = cursor.getColumnIndex(TestHelper.EMPLOYEE_ADDRESS);

        /*    int id = cursor.getInt(c1);
            String name = cursor.getString(c2);
            String pass = cursor.getString(c3);*/
            String salary = cursor.getString(c4);
            String address = cursor.getString(c5);

            buffer.append(/*id + " " + name + " " + pass + " " + */salary + " " + address + "\n");
        }
        return buffer.toString();
    }

    public int updateAddress(String name, String newAdd){
        SQLiteDatabase db = testHelper.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(TestHelper.EMPLOYEE_ADDRESS, newAdd);
        String[] whereArgs ={name};
        int count = db.update(TestHelper.TABLE_NAME, contentValues, TestHelper.EMPLOYEE_NAME + " =? ", whereArgs);
        return count;
    }

    public int deletebyName(String name,String pass){
        SQLiteDatabase db = testHelper.getWritableDatabase();
        String[] whereArgs = {name,pass};
        int count = db.delete(TestHelper.TABLE_NAME, TestHelper.EMPLOYEE_NAME+ "= ? AND "+ TestHelper.EMPLOYEE_PASSWORD+ " =? ",whereArgs);

        return count;
    }


    static class TestHelper extends SQLiteOpenHelper {

        private static final int DATABASE_VERSION = 17;
        private static final String DATABASE_NAME = "TestDB";
        private static final String TABLE_NAME = "EmployeeTable";
        static final String EMPLOYEE_ID = "_id";
        static final String EMPLOYEE_NAME = "Name";
        static final String EMPLOYEE_PASSWORD = "Password";
        static final String EMPLOYEE_SALARY = "Salary";
        static final String EMPLOYEE_ADDRESS = "Address";


        private Context context;

        private static final String CREATE_TABLE_QUERY = "CREATE TABLE " + TABLE_NAME + " (" + EMPLOYEE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + EMPLOYEE_NAME + " VARCHAR(255), " + EMPLOYEE_PASSWORD + " VARCHAR(255) , " + EMPLOYEE_SALARY + " INTEGER , " + EMPLOYEE_ADDRESS + " VARCHAR(255) );";
        private static final String DROP_TABLE_QUERY = "DROP TABLE IF EXISTS " + TABLE_NAME;

        public TestHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            this.context = context;
            Message.message(context, "Constructer Called");

        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            try {
                db.execSQL(CREATE_TABLE_QUERY);
                Message.message(context, "onCreate Called");
            } catch (SQLException e) {
                Message.message(context, "" + e);
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            try {
                db.execSQL(DROP_TABLE_QUERY);
                Message.message(context, "onUpgrade Called");
                onCreate(db);
            } catch (SQLException e) {
                Message.message(context, "" + e);
            }
        }
    }


}

1 个答案:

答案 0 :(得分:0)

我发现我正在使用ViewGroup.LayoutParams

 TextView tv = new TextView(this);
        tv.setLayoutParams(new ViewGroup.LayoutParams(
           ViewGroup.LayoutParams.WRAP_CONTENT,
           ViewGroup.LayoutParams.WRAP_CONTENT));

所以我刚刚将上面的代码更改为TableRow.LayoutParams

 TextView tv = new TextView(this);
        tv.setLayoutParams(new TableRow.LayoutParams(
           TableRow.LayoutParams.WRAP_CONTENT,
           TableRow.LayoutParams.WRAP_CONTENT));

它就像一个魅力。