簡體   English   中英

SQLite數據庫信息到ListView的結構

[英]Structure for SQLite database info to ListView

我在這里看到了一些答案,但是很多答案要么使我煩惱,要么無法將它們與我的應用程序聯系起來。 我在想,是否有人對我分解一點,因為我是編程新手。

我正在嘗試使用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>

您需要創建一個適配器。 您需要在其中通過

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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM