Android SimpleCursorAdapter + ListView无法正常工作

时间:2015-11-19 17:44:11

标签: android listview

在线演讲期间,我正在进行Android开发,此时陷入困境。我编写了与教师完全相同的代码,它从DB获取一些数据并通过ListView将其显示在屏幕上,但它没有任何错误地工作。

下面有2个xml文件和1个java代码。

虽然有人已经对此提出疑问,但我无法找到适合我的问题的答案

名为" onButton4Clicked()"可能是问题,但不确定,所以我分享文件中的所有内容。

MainActivity.java

package org.androidtown.mydatabase;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {
    EditText editText; EditText editText2; TextView textView; String databaseName; String tableName;
    SQLiteDatabase database;
    CustomerDatabaseHelper databaseHelper;

    ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = (EditText) findViewById(R.id.editText);
        editText2 = (EditText) findViewById(R.id.editText2);
        textView = (TextView) findViewById(R.id.textView);

        listView = (ListView) findViewById(R.id.listView);
    }

    public void onButton1Clicked(View v){
        databaseName = editText.getText().toString();
        try{
            databaseHelper = new CustomerDatabaseHelper(getApplicationContext(), databaseName, null, 2);
            database = databaseHelper.getWritableDatabase();

            println("Database has been opened : " + databaseName);
        } catch(Exception e){
            e.printStackTrace();
        }
    }

    public void onButton2Clicked(View v){
        //createTable();
    }

    public void createTable(SQLiteDatabase db){
        tableName = editText2.getText().toString();
        try{
            if(db != null){
                db.execSQL("CREATE TABLE if not exists " + tableName + "("
                        + "_id integer PRIMARY KEY autoincrement, "
                        + "name text, "
                        + "age integer, "
                        + "mobile text"
                        + ")");
                println("Table Created : " + tableName);
            } else {
                println("Should open Database first");
            }
        } catch(Exception e){
            e.printStackTrace();
        }
    }

    public void changeTable(SQLiteDatabase db){
        try{
            if(db != null){
                db.execSQL("CREATE TABLE if not exists " + "PRODUCT" + "("
                        + "_id integer PRIMARY KEY autoincrement, "
                        + "name text, "
                        + "price integer"
                        + ")");
                println("Add Additional Table : " + "PRODUCT");
            } else {
                println("Should open Database first");
            }
        } catch(Exception e){
            e.printStackTrace();
        }
    }

    public void onButton3Clicked(View v){
        try{
            if(tableName == null){
                tableName = editText2.getText().toString();
            }

            if(database != null){
                database.execSQL("INSERT INTO " + tableName + "(name, age, mobile) VALUES "
                        + "('David', 20, '010-1000-1000')");

                println("Data has been added ");
            } else {
                println("Should open Database first");
            }
        } catch(Exception e){
            e.printStackTrace();
        }
    }

    public void onButton4Clicked(View v){
        try{
            if(tableName == null){
                tableName = editText2.getText().toString();
            }

            if(database != null){
                Cursor cursor = database.rawQuery("SELECT _id, name, age, mobile FROM " + tableName, null);

                startManagingCursor(cursor);

                String[] columns = new String[] {"name", "age", "mobile"};
                int[] to = new int[] {R.id.textView2, R.id.textView3, R.id.textView4};

                SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.customer_item, cursor, columns, to);
                listView.setAdapter(adapter);
                adapter.notifyDataSetChanged();

                int count = cursor.getCount();
                println("Counted Result Record : " + count);

                for (int i = 0; i < count; i++){
                    cursor.moveToNext();
                    int _id = cursor.getInt(0);
                    String name = cursor.getString(1);
                    int age = cursor.getInt(2);
                    String mobile = cursor.getString(3);

                    println("Record #" + i + " : " + _id + name + ", " + age + ", " + mobile);
                }

                cursor.close();

                println("Inquired Data ");
            } else {
                println("Should open Database first");
            }
        } catch(Exception e){
            e.printStackTrace();
        }
    }
    private void println(String data){
        textView.append(data + "\n");
    }

    class CustomerDatabaseHelper extends SQLiteOpenHelper {

        CustomerDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
        }

        @Override
        public void onOpen(SQLiteDatabase db) {
            super.onOpen(db);
            Toast.makeText(getApplicationContext(), "onOpen() in Helper has been called", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            Toast.makeText(getApplicationContext(), "onCreate() in Helper has been called", Toast.LENGTH_LONG).show();

            createTable(db);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Toast.makeText(getApplicationContext(),
                    "onUpgrade() in Helper has been called : " + oldVersion + "->" + newVersion, Toast.LENGTH_LONG).show();

            changeTable(db);
        }

    }

    @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中

<LinearLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <EditText
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:id="@+id/editText"
            android:text="customer.db" />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="1. Open Database"
            android:id="@+id/button"
            android:onClick="onButton1Clicked" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <EditText
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:id="@+id/editText2"
            android:text="customer" />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="2. Create Table"
            android:id="@+id/button2"
            android:onClick="onButton2Clicked" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="3. Insert Data"
            android:id="@+id/button3"
            android:onClick="onButton3Clicked" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="4. Inquire Data"
            android:id="@+id/button4"
            android:onClick="onButton4Clicked" />
    </LinearLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_below="@+id/button"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:background="#aaff66">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/textView">
        </TextView>
    </ScrollView>

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listView" />


</LinearLayout>

customer_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="228dp"
        android:layout_height="wrap_content"
        android:id="@+id/textView2"
        android:textSize="30dp" />

    <TextView
        android:layout_width="227dp"
        android:layout_height="wrap_content"
        android:id="@+id/textView3"
        android:textSize="26dp" />

    <TextView
        android:layout_width="213dp"
        android:layout_height="wrap_content"
        android:id="@+id/textView4"
        android:textSize="20dp"
        android:textColor="#ffff0000" />
</LinearLayout>

1 个答案:

答案 0 :(得分:1)

你不应该关闭光标!

//cursor.close();