使用 SQLite 数据库的数据未显示在 RecyclerView 中

Data is not being displayed in the RecyclerView using SQLite Database

我正在使用 SQLite 数据库存储数据并将数据显示到 RecyclerView。我能够将数据存储到数据库,但是数据没有显示到 RecyclerView.I 需要关闭并重新启动应用程序,然后只有数据显示在 RecyclerView 中。

以下屏幕截图显示 Add_Data Activity,因为我输入了姓名、年龄和国家/地区的值

Add_Data Activity

下面是RecyclerView的截图,我需要重启应用,RecyclerView才会出现用户详情

RecyclerView Output

MainActivity.java

public class MainActivity extends AppCompatActivity
{
RecyclerView recyclerView;
MyAdapter madapter;
ArrayList<Model> models = new ArrayList<>();
DatabaseHelper myDB;

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

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

    recyclerView = (RecyclerView) findViewById(R.id.id_recyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    madapter = new MyAdapter(this,models);

    retrieveData();

}

public void retrieveData()
{
    Cursor c = myDB.getAllUserData();
    while (c.moveToNext())
    {
        int id = c.getInt(0);
        String name = c.getString(1);
        String age = c.getString(2);
        String country = c.getString(3);

        Model m = new Model(id,name,age,country);
        models.add(m);
    }

    if (!(models.size()<1))
    {
        recyclerView.setAdapter(madapter);
    }
}

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

DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "profile.db";
    public static final String TABLE_NAME = "profile_table";
    public static final String COL_1 = "ID";
    public static final String COL_2 = "NAME";
    public static final String COL_3 = "AGE";
    public static final String COL_4 = "COUNTRY";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(" create table " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, AGE TEXT, COUNTRY TEXT)");
    }

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

    public boolean addData(String name, String age, String country) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(DatabaseHelper.COL_2, name);
        cv.put(DatabaseHelper.COL_3, age);
        cv.put(DatabaseHelper.COL_4, country);
        long res = db.insert(TABLE_NAME, null, cv);
        if (res == -1)
            return false;
        else
            return true;
    }

    public Cursor getAllUserData() {
        SQLiteDatabase db = this.getWritableDatabase();
        String[] columns = {DatabaseHelper.COL_1, DatabaseHelper.COL_2,
                DatabaseHelper.COL_3, DatabaseHelper.COL_4};
        return db.query(DatabaseHelper.TABLE_NAME, columns, null, null, null, null, null);
    }

}

MyAdapter.java

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>
{
Context c;
ArrayList<Model> models;

public MyAdapter(Context c, ArrayList<Model> models) {
    this.c = c;
    this.models = models;
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
{
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row,null);
    return new MyViewHolder(v);
}

@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position)
{
    holder.userName.setText(models.get(position).getName());
    holder.userAge.setText(models.get(position).getAge());
    holder.userCountry.setText(models.get(position).getCountry());
}

@Override
public int getItemCount() {
    return models.size();
}

public class MyViewHolder extends RecyclerView.ViewHolder
{
    TextView userName,userAge,userCountry;

    public MyViewHolder(View itemView)
    {
        super(itemView);

        userName = (TextView) itemView.findViewById(R.id.textViewNameHere);
        userAge = (TextView) itemView.findViewById(R.id.textViewAgeHere);
        userCountry = (TextView) itemView.findViewById(R.id.textViewCountryHere);
    }
}
}

Model.java (POJO class)

public class Model
{
private int id;
private String name,age,country;

public Model(int id, String name, String age, String country)
{
    this.id = id;
    this.name = name;
    this.age = age;
    this.country = country;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getAge() {
    return age;
}

public void setAge(String age) {
    this.age = age;
}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}
}

Add_Data.java

public class Add_Data extends AppCompatActivity
{
EditText name,age,country;
Button save_user;
DatabaseHelper myDB;


@Override
 protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add__data);

    name = (EditText) findViewById(R.id.etname);
    age = (EditText) findViewById(R.id.etage);
    country = (EditText) findViewById(R.id.etcountry);
    save_user = (Button) findViewById(R.id.save_user);
   myDB = new DatabaseHelper(this);


    save_user.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            boolean isInserted = myDB.addData(name.getText().toString(),
                    age.getText().toString(),
                    country.getText().toString());

            if (isInserted = true)
            {
                Toast.makeText(Add_Data.this, "Saved", Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(Add_Data.this, "Error", Toast.LENGTH_SHORT).show();
            }


            finish();

        }
    });

}
}

移动

retrieveData();

onResume()方法。

另外,不相关但是,这一行是错误的:

if (isInserted = true)

应该是

if (isInserted == true)if (isInserted)

编辑:

此外,

制作retrieveData()函数的第一条指令models.clear();

 if (!(models.size()<1))
{
    recyclerView.setAdapter(madapter);
}

即使列表仍为空,您也应该设置适配器。

在你的适配器中,做一个像这样的刷新函数

    public void refresh(List<Model> models) {       
this.models = models;
 this.notifyDataSetChanged(); 
}

然后在检索数据时调用 madapter.refresh();