SQLite数据库信息到ListView的结构

时间:2016-04-25 04:07:52

标签: android database sqlite listview simplecursoradapter

我在这里看到了一些答案,但是很多答案要么是我的头脑还是我无法将它们与我的应用程序联系起来。我想知道是否有人可以为我打破一点,因为我对编程很陌生。

我正在尝试用Android中的SQLite数据库中的数据填充ExpandableListView。我有一个名为DatabaseHelper的类,它创建数据库/表并添加和删除数据,我甚至可以通过Cursor调用信息来显示AlertDialog中的数据。但是,我正在尝试将此信息动态加载到ExpandableListView中。

我在数据库助手中有这个方法:

public Cursor getAllData() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("SELECT * FROM "+ TABLE_NAME, null);
    return res;

返回一个包含表格的Cursor对象。然而,为了填充ListView,我的理解是我还需要使用SimpleCursorAdapter并将其应用于ListView。我是否需要为SimpleCursorAdapter创建一个单独的类?如果是这样,那么我如何将SimpleCursorAdaptor应用于我的expandableListView?

我的所有代码如下。

MainActivity.java

public class MainActivity extends AppCompatActivity {

DatabaseHelper myDb;
EditText editName, editSurname, editAge;
Button btnAddData, btnViewAll;
ListView listView;
private SimpleCursorAdapter dataAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    myDb = new DatabaseHelper(this);
    Cursor c = myDb.getReadableDatabase().rawQuery("SELECT * FROM " + DatabaseHelper.TABLE_NAME, null);



    editName = (EditText) findViewById(R.id.editText_Name);
    editSurname = (EditText) findViewById(R.id.editText_Surname);
    editAge = (EditText) findViewById(R.id.editText_Age);
    btnAddData = (Button) findViewById(R.id.button_add);
    btnViewAll = (Button) findViewById(R.id.button_viewAll);
    listView = (ListView) findViewById(R.id.expandableListView);






    displayListView();
    AddData();
    viewAll();
}

private void displayListView() {

    Cursor cursor = myDb.getAllData();

    String[] columns = new String[] {
        DatabaseHelper.COL1,
        DatabaseHelper.COL2,
        DatabaseHelper.COL3,
        DatabaseHelper.COL4
    };

    int[] to = new int[] {
      R.id.textView2,
      R.id.textView4,
      R.id.textView6,
    };

    dataAdapter = new SimpleCursorAdapter(
            this, R.layout.listlayout,
            cursor,
            columns,
            to,
            0);


    listView.setAdapter(dataAdapter);


}

public void viewAll() {
    btnViewAll.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Cursor res = myDb.getAllData();
                    if (res.getCount() == 0) {
                        // show message (no data in table)
                        showMessage("Error", "No Data Found");
                        return;
                    }

                    StringBuffer buffer = new StringBuffer();
                    while (res.moveToNext()) {
                        buffer.append("ID: "+ res.getString(0) + "\n");
                        buffer.append("Name: "+ res.getString(1) + "\n");
                        buffer.append("Surname: "+ res.getString(2) + "\n");
                        buffer.append("Age: "+ res.getString(3) + "\n");
                    }

                    showMessage("Data", buffer.toString());

                }
            }
    );
}




public void showMessage(String title, String message){
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setCancelable(true);
    builder.setTitle(title);
    builder.setMessage(message);
    builder.show();

}

public void AddData() {
    btnAddData.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Boolean isInserted = myDb.insertData(editName.getText().toString(),
                            editSurname.getText().toString(),
                            editAge.getText().toString());

                    if(isInserted = true) {
                        Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Data is not Inserted", Toast.LENGTH_SHORT).show();
                    }
                }
            }
    );
}

}

DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper{

public static final String DATABASE_NAME = "People.db";
public static final String TABLE_NAME = "people_table";
public static final String COL1 = "ID";
public static final String COL2 = "NAME";
public static final String COL3 = "SURNAME";
public static final String COL4 = "AGE";



public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);

}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,SURNAME TEXT,AGE INTEGER)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
}

public boolean insertData(String name, String surname, String age) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL2, name);
    contentValues.put(COL3, surname);
    contentValues.put(COL4, age);
    long result = db.insert(TABLE_NAME, null, contentValues);
    if (result == -1)
        return false;
    else
        return true;

}

public Cursor getAllData() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("SELECT * FROM "+ TABLE_NAME, null);
    return res;
}
}

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<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.welcometech.database.MainActivity">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Name"
    android:id="@+id/textView"
    android:layout_alignParentTop="true"
    android:layout_toLeftOf="@+id/editText_Name"
    android:layout_toStartOf="@+id/editText_Name" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Surname"
    android:id="@+id/textView2"
    android:layout_below="@+id/textView"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginTop="44dp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Age"
    android:id="@+id/textView3"
    android:layout_marginTop="37dp"
    android:layout_below="@+id/textView2"
    android:layout_toLeftOf="@+id/editText_Age"
    android:layout_toStartOf="@+id/editText_Age" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/editText_Name"
    android:layout_alignTop="@+id/textView"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_toRightOf="@+id/textView2"
    android:layout_toEndOf="@+id/textView2" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/editText_Surname"
    android:layout_above="@+id/textView3"
    android:layout_alignRight="@+id/editText_Name"
    android:layout_alignEnd="@+id/editText_Name"
    android:layout_toRightOf="@+id/textView2"
    android:layout_toEndOf="@+id/textView2" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/editText_Age"
    android:layout_alignBottom="@+id/textView3"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_toRightOf="@+id/textView2"
    android:layout_toEndOf="@+id/textView2" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Add Data"
    android:id="@+id/button_add"
    android:layout_centerVertical="true"
    android:layout_below="@+id/textView3"
    android:layout_marginTop="20dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="View All"
    android:id="@+id/button_viewAll"
    android:layout_alignTop="@+id/button_add"
    android:layout_toRightOf="@+id/button_add"
    android:layout_toEndOf="@+id/button_add" />

<ExpandableListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/expandableListView"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/button_add" />
</RelativeLayout>

listlayout.xml

<?xml version="1.0" encoding="utf-8"?>
<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.welcometech.database.MainActivity">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Name"
    android:id="@+id/textView"
    android:layout_alignParentTop="true"
    android:layout_toLeftOf="@+id/editText_Name"
    android:layout_toStartOf="@+id/editText_Name" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Surname"
    android:id="@+id/textView2"
    android:layout_below="@+id/textView"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginTop="44dp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Age"
    android:id="@+id/textView3"
    android:layout_marginTop="37dp"
    android:layout_below="@+id/textView2"
    android:layout_toLeftOf="@+id/editText_Age"
    android:layout_toStartOf="@+id/editText_Age" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/editText_Name"
    android:layout_alignTop="@+id/textView"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_toRightOf="@+id/textView2"
    android:layout_toEndOf="@+id/textView2" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/editText_Surname"
    android:layout_above="@+id/textView3"
    android:layout_alignRight="@+id/editText_Name"
    android:layout_alignEnd="@+id/editText_Name"
    android:layout_toRightOf="@+id/textView2"
    android:layout_toEndOf="@+id/textView2" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/editText_Age"
    android:layout_alignBottom="@+id/textView3"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_toRightOf="@+id/textView2"
    android:layout_toEndOf="@+id/textView2" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Add Data"
    android:id="@+id/button_add"
    android:layout_centerVertical="true"
    android:layout_below="@+id/textView3"
    android:layout_marginTop="20dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="View All"
    android:id="@+id/button_viewAll"
    android:layout_alignTop="@+id/button_add"
    android:layout_toRightOf="@+id/button_add"
    android:layout_toEndOf="@+id/button_add" />

<ExpandableListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/expandableListView"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/button_add" />
</RelativeLayout>

1 个答案:

答案 0 :(得分:0)

您需要创建一个适配器。你需要通过

ArrayList <HashMap<String,String>>

您的 getAllData()方法应如下所示:

public ArrayList<HashMap<String,String>> getAllData(){
        SQLiteDatabase db = this.getWritableDatabase();

        ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
        HashMap<String,String> hashmap;

        String query_select = "SELECT column1, column2 FROM tablename ;

        Cursor cursor = db.rawQuery(query_select,null);
        if (cursor.moveToFirst()) {
            do {
                hashMap = new HashMap<String,String>();
                hashMap.put("column1", cursor.getString(0));
                hashMap.put("column2",cursor.getString(1));
                list.add(hashmap);
            } while (cursor.moveToNext());
        }
        cursor.close();

        return list;
    }

此方法将返回ArrayList,您需要将其设置为适配器,然后将适配器设置为ListView。