数据插入SQLite后如何立即更新listview

时间:2016-03-18 11:30:13

标签: android

我有一个名为Custom的类,它扩展了片段。 OnCreateView它将通过将视图v传入其中来调用同一类中的populateListView方法。点击fab buttom,它将打开一个名为CustomForm的新活动,这是一个允许用户填写的表格,以便将数据插入到SQLite数据库中。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    final View v = inflater.inflate(R.layout.fragment_custom, container, false);
    openDB();

    ListView myList = (ListView) v.findViewById(R.id.customlistview);
    populateListView(v);
    View fabbutton = v.findViewById(R.id.fab);
    fabbutton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent myIntent = new Intent(getActivity(), CustomForm.class);
            startActivity(myIntent);

        }
    });
    return v;
}

public void populateListView(View v) {
    Cursor cursor = dbAdapter.getAllRows();
    String[] fromFieldNames = new String[]{DBAdapter.KEY_DRUG_NAME, DBAdapter.KEY_DRUG_OTHER_NAME, DBAdapter.KEY_DRUG_DOSE_1};
    int[] toViewIDs = new int[]{R.id.lineone, R.id.linetwo, R.id.dose1};
    SimpleCursorAdapter myCursorAdapter;
    myCursorAdapter = new SimpleCursorAdapter(getContext(), R.layout.custom_row, cursor, fromFieldNames, toViewIDs, 0);
    ListView myList = (ListView) v.findViewById(R.id.customlistview);
    myList.setAdapter(myCursorAdapter);

}

这是CustomForm类

public class CustomForm extends AppCompatActivity {
        View create = findViewById(R.id.create);
        create.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "Drug Item Created", Toast.LENGTH_SHORT).show();
                if (!TextUtils.isEmpty(custom_drug_name_main.getText())) {
                    dbAdapter.insertRow(custom_drug_name_main.getText().toString(), custom_drug_name_other.getText().toString(), dose1.getText().toString());

                } else {

                }
                finish();



            }
        });
}

这是我的适配器类

public class DBAdapter {

    private static final String TAG = "DBAdapter"; //used for logging database version changes

    // Field Names:
    public static final String KEY_ROWID = "_id";
    public static final String KEY_DRUG_NAME = "drugName";
    public static final String KEY_DRUG_OTHER_NAME = "drugOtherName";
    public static final String KEY_DRUG_DOSE_1 = "dose1";

    public static final String[] ALL_KEYS = new String[]{KEY_ROWID, KEY_DRUG_NAME, KEY_DRUG_OTHER_NAME,KEY_DRUG_DOSE_1};

    // DataBase info:
    public static final String DATABASE_NAME = "custom_drug";
    public static final String DATABASE_TABLE = "custom_drug_table";
    public static final int DATABASE_VERSION = 3; // The version number must be incremented each time a change to DB structure occurs.

    //SQL statement to create database
    private static final String DATABASE_CREATE_SQL =
            "CREATE TABLE " + DATABASE_TABLE
                    + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                    + KEY_DRUG_NAME + " TEXT NOT NULL, "
                    + KEY_DRUG_OTHER_NAME + " TEXT,"
                    + KEY_DRUG_DOSE_1 + " TEXT NOT NULL"
                    + ");";

    private final Context context;
    private DatabaseHelper myDBHelper;
    private SQLiteDatabase db;

    public DBAdapter(Context ctx) {
        this.context = ctx;
        myDBHelper = new DatabaseHelper(context);
    }

    // Open the database connection.
    public DBAdapter open() {
        db = myDBHelper.getWritableDatabase();
        return this;
    }

    // Close the database connection.
    public void close() {
        myDBHelper.close();
    }

    // Add a new set of values to be inserted into the database.
    public long insertRow(String drugName, String drugOtherName, String dose1) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_DRUG_NAME, drugName);
        initialValues.put(KEY_DRUG_OTHER_NAME, drugOtherName);
        initialValues.put(KEY_DRUG_DOSE_1, dose1);

        // Insert the data into the database.
        return db.insert(DATABASE_TABLE, null, initialValues);
    }

    // Delete a row from the database, by rowId (primary key)
    public boolean deleteRow(long rowId) {
        String where = KEY_ROWID + "=" + rowId;
        return db.delete(DATABASE_TABLE, where, null) != 0;
    }

    public void deleteAll() {
        Cursor c = getAllRows();
        long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
        if (c.moveToFirst()) {
            do {
                deleteRow(c.getLong((int) rowId));
            } while (c.moveToNext());
        }
        c.close();
    }

    // Return all data in the database.
    public Cursor getAllRows() {
        String where = null;
        Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
        }
        return c;
    }

    // Get a specific row (by rowId)
    public Cursor getRow(long rowId) {
        String where = KEY_ROWID + "=" + rowId;
        Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
                where, null, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
        }
        return c;
    }

    // Change an existing row to be equal to new data.
    public boolean updateRow(long rowId, String drugName, String drugOtherName) {
        String where = KEY_ROWID + "=" + rowId;
        ContentValues newValues = new ContentValues();
        newValues.put(KEY_DRUG_NAME, drugName);
        newValues.put(KEY_DRUG_OTHER_NAME, drugOtherName);
        // Insert it into the database.
        return db.update(DATABASE_TABLE, newValues, where, null) != 0;
    }


    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase _db) {
            _db.execSQL(DATABASE_CREATE_SQL);
        }

        @Override
        public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading application's database from version " + oldVersion
                    + " to " + newVersion + ", which will destroy all old data!");

            // Destroy old database:
            _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

            // Recreate new database:
            onCreate(_db);
        }
    }
}

我的问题是:如何从Custom类调用populateListView方法,以便在插入数据后立即更新listview。我是编程新手,我希望我的问题清楚。谢谢。

4 个答案:

答案 0 :(得分:2)

这是我说的一个例子:

将对DBAdapter

   public class DBAdapter extends BaseAdapter {
    private static final String TAG = "DBAdapter"; //used for logging database version changes

    // Field Names:
    public static final String KEY_ROWID = "_id";
    public static final String KEY_DRUG_NAME = "drugName";
    public static final String KEY_DRUG_OTHER_NAME = "drugOtherName";
    public static final String KEY_DRUG_DOSE_1 = "dose1";

    public static final String[] ALL_KEYS = new String[]{KEY_ROWID, KEY_DRUG_NAME, KEY_DRUG_OTHER_NAME,KEY_DRUG_DOSE_1};

    // DataBase info:
    public static final String DATABASE_NAME = "custom_drug";
    public static final String DATABASE_TABLE = "custom_drug_table";
    public static final int DATABASE_VERSION = 3; // The version number must be incremented each time a change to DB structure occurs.

    //SQL statement to create database
    private static final String DATABASE_CREATE_SQL =
            "CREATE TABLE " + DATABASE_TABLE
                    + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                    + KEY_DRUG_NAME + " TEXT NOT NULL, "
                    + KEY_DRUG_OTHER_NAME + " TEXT,"
                    + KEY_DRUG_DOSE_1 + " TEXT NOT NULL"
                    + ");";

    private final Context context;
    private DatabaseHelper myDBHelper;
    private SQLiteDatabase db;

    public DBAdapter(Context ctx) {
        this.context = ctx;
        myDBHelper = new DatabaseHelper(context);
    }

    // Open the database connection.
    public DBAdapter open() {
        db = myDBHelper.getWritableDatabase();
        return this;
    }

    // Close the database connection.
    public void close() {
        myDBHelper.close();
    }

    // Add a new set of values to be inserted into the database.
    public long insertRow(String drugName, String drugOtherName, String dose1) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_DRUG_NAME, drugName);
        initialValues.put(KEY_DRUG_OTHER_NAME, drugOtherName);
        initialValues.put(KEY_DRUG_DOSE_1, dose1);

        // Insert the data into the database.
        return db.insert(DATABASE_TABLE, null, initialValues);
    }

    // Delete a row from the database, by rowId (primary key)
    public boolean deleteRow(long rowId) {
        String where = KEY_ROWID + "=" + rowId;
        return db.delete(DATABASE_TABLE, where, null) != 0;
    }

    public void deleteAll() {
        Cursor c = getAllRows();
        long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
        if (c.moveToFirst()) {
            do {
                deleteRow(c.getLong((int) rowId));
            } while (c.moveToNext());
        }
        c.close();
    }

    // Return all data in the database.
    public Cursor getAllRows() {
        String where = null;
        Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
        }
        return c;
    }

    // Change an existing row to be equal to new data.
    public boolean updateRow(long rowId, String drugName, String drugOtherName) {
        String where = KEY_ROWID + "=" + rowId;
        ContentValues newValues = new ContentValues();
        newValues.put(KEY_DRUG_NAME, drugName);
        newValues.put(KEY_DRUG_OTHER_NAME, drugOtherName);
        // Insert it into the database.
        return db.update(DATABASE_TABLE, newValues, where, null) != 0;
    }

    @Override
    public int getCount() {
        String where = null;
        Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
        }
        return c.getCount();
    }

    @Override
    public Cursor getItem(int position) {
        String where = KEY_ROWID + "=" + position;
        Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
                where, null, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
        }
        return c;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null)
            convertView = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);

        Cursor c = getItem(position);
        ((TextView) convertView.findViewById(R.id.whatYouWant)).setText(c.getString(0)); // Replace with what you want

        return convertView;
    }


    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase _db) {
            _db.execSQL(DATABASE_CREATE_SQL);
        }

        @Override
        public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading application's database from version " + oldVersion
                    + " to " + newVersion + ", which will destroy all old data!");

            // Destroy old database:
            _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

            // Recreate new database:
            onCreate(_db);
        }
    }
}

正如您所看到的,getRow被getItem替换。

list_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:id="@+id/whatYouWant"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
</LinearLayout>

答案 1 :(得分:2)

更好的做法是创建一个CursorAdapter,然后你只需要调用swapCursor():

adapter.swapCursor(cursor_update);

但是在你的情况下,你有一个你想从其他活动中访问的SimpleCursorAdapter,所以你可以试试这个:

public class CustomForm extends AppCompatActivity {
        View create = findViewById(R.id.create);
        create.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "Drug Item Created", Toast.LENGTH_SHORT).show();
                if (!TextUtils.isEmpty(custom_drug_name_main.getText())) {
                    dbAdapter.insertRow(custom_drug_name_main.getText().toString(), custom_drug_name_other.getText().toString(), dose1.getText().toString());

                } else {

                }
                Intent myIntent = new Intent(getActivity(), yourLastActivity.class);
                startActivity(myIntent);
            }
        });
}

执行此操作以调用populateListView(v);当你回到最后一个活动时,在onCreateView()中:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    final View v = inflater.inflate(R.layout.fragment_custom, container, false);
    openDB();

    ListView myList = (ListView) v.findViewById(R.id.customlistview);
    populateListView(v); // we are trying to call this after the dbAdapter.insertRow

希望这有帮助

答案 2 :(得分:1)

首先,您应该将光标变量移出populateListView方法。并在自定义片段中声明它。

public Cursor cursor;

然后创建下一段代码

public void updateList() {
     cursor = dbAdapter.getAllRows();
     myCursorAdapter.notifyDataSetChanged();
}

最后将这个updateList()方法放入你的onClick()方法

答案 3 :(得分:0)

如果要在将项目插入数据库后立即更新Listview。只需使用

dbAdapter.insertRow(custom_drug_name_main.getText().toString(), custom_drug_name_other.getText().toString(), dose1.getText().toString());
dbAdapter.notifyDataSetChanged();