【问题标题】:list is showing incorrect entry using MVVM and sqlite列表使用 MVVM 和 sqlite 显示不正确的条目
【发布时间】:2021-08-27 09:04:38
【问题描述】:

我使用带有 mvvm 的 sqlite ..但是当我单击添加新并提交返回到列表页面时,它没有更新列表中的记录。但是当我再次杀死应用程序进入列表页面时,它显示的记录具有相同的重复条目记录。我不知道我的代码哪里出错了..请帮助

数据库助手:-

public class DbHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 2;

static final String DATABASE_NAME = "kuncorosqlite.db";

public static final String TABLE_SQLite = "sqlite";

public static final String COLUMN_ID = "id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_ADDRESS = "address";
ArrayList<HashMap<String, String>> listofMaps = new ArrayList();

public DbHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    final String SQL_CREATE_MOVIE_TABLE = "CREATE TABLE " + TABLE_SQLite + " (" +
            COLUMN_ID + " INTEGER PRIMARY KEY autoincrement, " +
            COLUMN_NAME + " TEXT NOT NULL, " +
            COLUMN_ADDRESS + " TEXT NOT NULL" +
            " )";

    db.execSQL(SQL_CREATE_MOVIE_TABLE);
}

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

public MutableLiveData<ArrayList<HashMap<String, String>>> getAllData() {
    MutableLiveData<ArrayList<HashMap<String, String>>> wordList;
    wordList = new MutableLiveData<ArrayList<HashMap<String, String>>>();
    String selectQuery = "SELECT * FROM " + TABLE_SQLite;
    SQLiteDatabase database = this.getWritableDatabase();
    Cursor cursor = database.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
        do {
            HashMap<String, String> map = new HashMap<String, String>();
            map.put(COLUMN_ID, cursor.getString(0));
            map.put(COLUMN_NAME, cursor.getString(1));
            map.put(COLUMN_ADDRESS, cursor.getString(2));
            

            listofMaps.add(map);

            wordList.postValue(listofMaps);
        } while (cursor.moveToNext());
    }

    Log.e("select sqlite ", "" + wordList);

    database.close();
    return wordList;
}

public void insert(String name, String address) {
    SQLiteDatabase database = this.getWritableDatabase();
    String queryValues = "INSERT INTO " + TABLE_SQLite + " (name, address) " +
            "VALUES ('" + name + "', '" + address + "')";

    Log.e("insert sqlite ", "" + queryValues);
    database.execSQL(queryValues);
    database.close();
}

public void update(int id, String name, String address) {
    SQLiteDatabase database = this.getWritableDatabase();

    String updateQuery = "UPDATE " + TABLE_SQLite + " SET "
            + COLUMN_NAME + "='" + name + "', "
            + COLUMN_ADDRESS + "='" + address + "'"
            + " WHERE " + COLUMN_ID + "=" + "'" + id + "'";
    Log.e("update sqlite ", updateQuery);
    database.execSQL(updateQuery);
    database.close();
}

public void delete(int id) {
    SQLiteDatabase database = this.getWritableDatabase();

    String updateQuery = "DELETE FROM " + TABLE_SQLite + " WHERE " + COLUMN_ID + "=" + "'" + id + "'";
    Log.e("update sqlite ", updateQuery);
    database.execSQL(updateQuery);
    database.close();
}

}

视图模型:-

public class Viewmodell extends AndroidViewModel {

private DbHelper repository ;
 MutableLiveData<ArrayList<HashMap<String, String>>> allNotesLivedata;
public Viewmodell(@NonNull Application application) {
    super(application);
    repository = new DbHelper(application);
    allNotesLivedata = repository.getAllData();
}
void insert(String name,String Address) {
    repository.insert(name,Address);
}
void update(int id, String name, String address) {
    repository.update(id,name,address);
}
void delete(int id) {
    repository.delete(id);
}
public LiveData<ArrayList<HashMap<String, String>>> getAllNotes() {
    return allNotesLivedata;
}

}

ma​​inactivity(列表页面):-

public class MainActivity extends AppCompatActivity {

ListView listView;
AlertDialog.Builder dialog;
List<Data> itemList = new ArrayList<Data>();
Adapter adapter;
DbHelper SQLite = new DbHelper(this);
Viewmodell viewmodell;
public static final String TAG_ID = "id";
public static final String TAG_NAME = "name";
public static final String TAG_ADDRESS = "address";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    SQLite = new DbHelper(getApplicationContext());
    viewmodell = ViewModelProviders.of(this).get(Viewmodell.class);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    listView = (ListView) findViewById(R.id.list_view);

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this, AddEdit.class);
            startActivity(intent);
        }
    });

    adapter = new Adapter(MainActivity.this, itemList);
    listView.setAdapter(adapter);
    listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            final String idx = itemList.get(position).getId();
            final String name = itemList.get(position).getName();
            final String address = itemList.get(position).getAddress();
            Intent intent = new Intent(MainActivity.this, DetailsAct.class);
            intent.putExtra(TAG_ID, idx);
            intent.putExtra(TAG_NAME, name);
            intent.putExtra(TAG_ADDRESS, address);
            startActivity(intent);
        }
    });

    getAllData();

}

private void getAllData() {
    viewmodell.getAllNotes();
    viewmodell.allNotesLivedata.observe(this, new Observer<ArrayList<HashMap<String, String>>>() {
        @Override
        public void onChanged(ArrayList<HashMap<String, String>> hashMaps) {
            for (int i = 0; i < hashMaps.size(); i++) {
                String id = hashMaps.get(i).get(TAG_ID);
                String poster = hashMaps.get(i).get(TAG_NAME);
                String title = hashMaps.get(i).get(TAG_ADDRESS);

                Data data = new Data();

                data.setId(id);
                data.setName(poster);
                data.setAddress(title);

                itemList.add(data);
            }

            adapter.notifyDataSetChanged();
        }


    });
}

@Override
protected void onResume() {
    super.onResume();
    itemList.clear();
    getAllData();
}

【问题讨论】:

  • 它只在 onchanged 里面..正确查看@a_local_nobody
  • 啊,我明白了,我的错
  • 你需要调试你的代码才能知道发生了什么故障。代码没有问题
  • @KaruneshPalekar 如果用postvalue 替换为setvalue 则重复问题消失...但在恢复列表时不会更新...仅在杀死应用程序然后打开应用程序然后在列表中显示记录
  • @a_local_nobody 现在在 onResume 中有问题

标签: java android mvvm android-viewmodel android-mvvm


【解决方案1】:

我看到您在使用 LiveData 时遇到问题。

您的 LiveData 似乎无法在您的活动的 onResume() 上调用 viewModel.getAllNotes()

当您调用viewModel.getAllNote() 时,它实际上会返回 LiveData,您无需为该 LiveData 设置值。这就是为什么当您调用 viewModel.getAllNote() 时 LiveData allNotesLivedata 不会被触发。

LiveData allNotesLivedata 仅通过repository.getAllData()ViewModel 的构造函数中实际触发。 repository.getAllData() 实际上是您设置 LiveData 值的位置。

将ViewModel中的函数getAllNotes()替换为如下方式:

public LiveData<ArrayList<HashMap<String, String>>> getAllNotes() {
    return repository.getAllData();
}

编辑 1:

我看到你有重复的实体。 onResume() 在 Activity 的生命周期中被多次调用。

当你调用onResume() 时,你调用了DbHelper 中的函数getAllData()。您将 LiveData 的值设置为 listofMap

我看到您没有重置旧列表,而是将从 SQLite 收到的每个新项目添加到旧列表中。这导致listofMap 由旧项目 + SQLite 的新项目组成(包括所有以前的记录 + 新记录)。所以请在从 SQLite 添加新项目之前重置listofMap

public class DbHelper extends SQLiteOpenHelper {
    public MutableLiveData<ArrayList<HashMap<String, String>>> getAllData() {
        ...
        if (cursor.moveToFirst()) {
            listofMap = new ArrayList();
            // Continue your code
            do {
                ...
            }
        }
    }
}

【讨论】:

  • oncreate 上出现重复条目​​(第一次)
  • 在返回列表活动时添加新记录后,会看到新记录 n 也再次重复输入项...现在总共 4 次重复加上一条新记录 onResume
  • 可能是什么问题? @Duong
  • 因为您在onResume() 调用它。而在DbHelpergetAllData() 函数中,您是在说每次调用getAllData() 时都会向listofMaps 添加新值。你应该在添加之前清除listofMaps
  • @IRONMAN 我已经更新了评论。
猜你喜欢
  • 1970-01-01
  • 2018-08-11
  • 1970-01-01
  • 2013-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-07
相关资源
最近更新 更多