列表显示使用 MVVM 和 sqlite 的错误条目 [英] list is showing incorrect entry using MVVM and sqlite

查看:42
本文介绍了列表显示使用 MVVM 和 sqlite 的错误条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

im using sqlite with mvvm..but when i click add new and submit comming back to listing page it is not updated record in list.but when i kill app again come to list page it is showing record with duplicate entries of same record.i dont know where my code is getting wrong..plz help

数据库助手:-

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;
}

}

主要活动(列表页面):-

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();
}

推荐答案

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

Here I see you are having problems with LiveData.

您的 LiveData 似乎在您的活动的 onResume() 上调用 viewModel.getAllNotes() 时出现问题.

Your LiveData seems to be having problems calling viewModel.getAllNotes() on the onResume() of your activity.

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

With you calling viewModel.getAllNote(), it actually returns LiveData, you don't set the value for that LiveData. That's why when you call viewModel.getAllNote() the LiveData allNotesLivedata is not triggered.

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

LiveData allNotesLivedata only actually triggers in Constructor of ViewModel via repository.getAllData(). repository.getAllData() is actually where you set the value for LiveData.

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

Replace the function getAllNotes() in the ViewModel in the following way:

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

编辑 1:

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

I am seeing you have duplicate entity. it's onResume() that is called multiple times in the Activity's lifecycle.

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

And when you call onResume(), you call the function getAllData() in DbHelper. You are setting the value for LiveData to listofMap.

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

I see you are not resetting the old list, and you are adding each new item received from SQLite to the old list. That results in listofMap consisting of old item + new item of SQLite (includes all previous record + new record). So please reset listofMap before adding new item from SQLite.

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

这篇关于列表显示使用 MVVM 和 sqlite 的错误条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆