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

时间:2018-07-25 14:05:29

标签: android android-recyclerview android-sqlite android-arrayadapter

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

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

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类)

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

        }
    });

}
}

2 个答案:

答案 0 :(得分:0)

移动

retrieveData();

转到onResume()方法。

也没有关系,但是这一行是错误的:

if (isInserted = true)

应该是

if (isInserted == true)if (isInserted)

编辑:

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

答案 1 :(得分:0)

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

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

在适配器中,执行如下刷新功能

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

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