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

Android 如何在数据插入SQLite后立即更新listview,android,Android,我有一个名为Custom的类,它扩展了片段。在CreateView中,它将通过在视图v中传递来调用同一类中的populateListView方法。单击fab按钮后,它将打开一个名为CustomForm的新活动,这是一个允许用户填写的表单,从而将数据插入SQLite数据库 @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle s

我有一个名为Custom的类,它扩展了片段。在CreateView中,它将通过在视图v中传递来调用同一类中的populateListView方法。单击fab按钮后,它将打开一个名为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);
        }
    }
}

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

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

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

若要在将项插入数据库后立即更新Listview。只用

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

下面是我说过的一个例子:

DBAdapter

如您所见,getRow被getItem替换

list_item.xml



以下是我说过的一个例子:

DBAdapter

如您所见,getRow被getItem替换

list_item.xml


更好的做法是创建游标适配器,然后只需调用swapCursor():

但在您的情况下,您有一个SimpleCorsorAdapter,您希望从其他活动访问它,因此您可以尝试以下方法:

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

希望这能有所帮助。更好的做法是创建游标适配器,然后只需调用swapCursor():

但在您的情况下,您有一个SimpleCorsorAdapter,您希望从其他活动访问它,因此您可以尝试以下方法:

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

希望这有帮助

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

public Cursor cursor;
然后创建下一段代码

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

最后,将这个updateList()方法放入onClick()方法中。首先,应该将游标变量移出populateListView方法。并在自定义片段中声明它

public Cursor cursor;
然后创建下一段代码

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

最后,将这个updateList()方法放入onClick()方法中

显示适配器请在更新数据后调用
myCursorAdapter.notifyDataSetChanged()显示适配器更新数据后,请调用
myCursorAdapter.notifyDataSetChanged()
在我的CustomForm类中,我应该扩展其他类吗?因为我看不到notifyDataSetChanged();method@SimonHomyCursorAdapter.notifyDataSetChanged();不适合您?请尝试将
扩展BaseAdapter
添加到您的dbAdapter。您不能调用dbAdapter.notifyDataSetChanged();dbAdapter不是适配器不能放线,因为myCursorAdapter来自自定义类,但不在CustomForm类中在我的CustomForm类中,我应该扩展其他类吗?因为我看不到notifyDataSetChanged();method@SimonHomyCursorAdapter.notifyDataSetChanged();不适合您?请尝试将
扩展BaseAdapter
添加到您的dbAdapter。您不能调用dbAdapter.notifyDataSetChanged();dbAdapter不是适配器不能放线,因为myCursorAdapter来自自定义类,但不在CustomForm classI中。我发现我的问题是“finish();”我替换finish();为了重新打开mainactivity类解决我的问题,我发现我的问题是“finish();”我替换finish();为了重新打开mainactivity类,解决了我的问题