JasonM JasonM - 15 days ago 6
Android Question

Retrieving DB information using RecyclerView and Fragments


  1. How can I Retrieve data in CategoryListFragment with 'getCategories()?'
    I've GetAllValues() function in MyDBHelper, but not sure how to use it @fragments class, because I can't initialize MyDBHelper object correctly, when I try it.

  2. What's wrong with my MainActivity - where I try to add fragment. It gives me error, but I can't see why.



RECYCLERVIEW folder:

Category.java

public class Category {
private String name;

public Category(String name) {
this.name = name;
}

public String getName() {
return name;
}

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


CategoryAdapter.java

public class CategoryAdapter extends RecyclerView.Adapter<ViewHolder> {

Context c;
ArrayList<Category> Categories;

public CategoryAdapter(Context c, ArrayList<Category> Categories) {
this.c = c;
this.Categories = Categories;
}
// INITIALIZE HOLDER
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {

View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.rec_item, null);
ViewHolder holder = new ViewHolder(v);
return holder;
}
// BIND DATA TO VIEWS
@Override
public void onBindViewHolder(ViewHolder holder, final int position) {

holder.mNameTextView.setText(Categories.get(position).getName());
//LISTENER
holder.setItemClickListener(new itemClickListener() {
@Override
public void onItemClick(View v, int pos) {
//
}
});
}

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


ViewHolder.java

public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
// Views

TextView mNameTextView;
itemClickListener icl;

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

// Get references to image and name.
mNameTextView = (TextView) itemView.findViewById(R.id.name);

itemView.setOnClickListener(this);
}

public void setItemClickListener(itemClickListener icl)
{
this.icl = icl;
}

@Override
public void onClick(View v){
this.icl.onItemClick(v, getPosition());
}}


itemClickListener.java

public interface itemClickListener {
void onItemClick(View v, int pos);
}


FRAGMENT

public class CategoryListFragment extends Fragment {
@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState){
final View view = inflater.inflate(R.layout.rec_item, container, false);

//RECYCLERVIEW
RecyclerView rv = (RecyclerView) view.findViewById(R.id.recycler_view);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(this.getActivity());
rv.setAdapter(new CategoryAdapter(this.getActivity(), getCategories()));


return view;
}


private ArrayList<Category> getCategories () {
ArrayList<Category> categories = new ArrayList<>();

//HOW TO RETRIEVE DATA FROM DB HERE?

return categories;
}


MyDBHelper.class

public class MyDatabaseHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME="CategoryDatabase";

public MyDatabaseHelper(Context context) {

super(context, DATABASE_NAME, null, 1);

}

@Override

public void onCreate(SQLiteDatabase database) {

database.execSQL("CREATE TABLE Category (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT);");

}

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

db.execSQL("DROP TABLE IF EXISTS Category");

onCreate(db);

}

public void addCategory(String name)

{

ContentValues values=new ContentValues(1);

values.put("name", name);

getWritableDatabase().insert("Category", "name", values);

}

public Cursor getCategories()

{

Cursor cursor = getReadableDatabase().rawQuery("select * from Category", null);

return cursor;

}

public ArrayList<String> GetAllValues()
{
String aTable = "Category"; // Table's name
ArrayList<String> list = new ArrayList<String>();
Cursor cursor = getCategories();
if (cursor.moveToFirst())
{
do
{
list.add(cursor.getString(0));
}
while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed())
{
cursor.close();
}

return list;
}
}


MainActivity:

public class MainActivity extends AppCompatActivity {


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

fill_with_data();

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

CategoryListFragment fragment = new CategoryListFragment();
fragmentTransaction.add(R.id.root_layout, fragment);
fragmentTransaction.commit();

}


private void fill_with_data(){
MyDatabaseHelper mDB = new MyDatabaseHelper(this);
// Adding categories to DB - TEST
mDB.addCategory("Example1");
mDB.addCategory("John");
mDB.addCategory("Michael");
mDB.addCategory("TEST");

}
}

Answer

In your fragment class initialize MyDatabaseHelper object like this

MyDatabaseHelper dbHelper = new MyDatabaseHelper(getActivity()); 

and in the getCategories method fetch it like this

ArrayList<String> list = dbHelper.GetAllValues();

EDIT:

public ArrayList<String> GetAllValues()
{
String aTable = "Category"; // Table's name
ArrayList<Category> list = new ArrayList<>();
Cursor cursor =  getCategories();
if (cursor.moveToFirst())
{
    do
    {
       Category cat  = new Category(cursor.getString(0));
        list.add(cat);
    }
    while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed())
{
    cursor.close();
}

return list;

}

Comments