1
// Category Adapter which open the second fragment containing the blank recyclerview(which should ideally contain intial data.)

public class MyCategoryAdapter extends RecyclerView.Adapter<MyCategoryHolder> {

    private Context context;
    private ArrayList<Categories> categories;

    private Context context1;


    public MyCategoryAdapter(Context context, ArrayList<Categories> categories) {
        this.context = context;
        this.categories = categories;
    }

    @Override
    public MyCategoryHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.category_model, parent, false);
        context1 = parent.getContext();
        return new MyCategoryHolder(v);
    }

    @Override
    public void onBindViewHolder(MyCategoryHolder holder, final int position) {

        Categories c = categories.get(position);
        holder.categoryText.setText(c.getName());
        holder.categoryIdText.setText(c.getId());

        //item click
        holder.setItemClickListener(new ItemClickListener() {
            @Override
            public void onItemClick(int pos) {
                Toast.makeText(context.getApplicationContext(), Integer.toString(pos), Toast.LENGTH_SHORT).show();
                openActivity();
            }
        });

    }

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

    private void openActivity()
    {
        FragmentActivity fragment = ((FragmentActivity)context1);
        fragment.getSupportFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.fragment_container, new SubCategoryFragment()).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit();

    }
}

I have made an android app containing of 2 Recyclerviews. Both have their individual Realm databases. First Recyclerview displays the Categories. When I click on any items, it opens the second Recyclerview for me (containing Subcategories). I am able to load the initial data for the Categories recyclerview but when i click on any items in it, it opens a blank recyclerview (ideally should display the contents from the SubCategories intial data Realm database)

//Realm for SubCategories

public class SubCategories extends RealmObject{

    private String name;
    private String id;

    public String getName() {
        return name;
    }

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

    public String getId() {
        return id;
    }

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

//Categories intial data 


public class CategoriesInitialData implements Realm.Transaction {
    @Override
    public void execute(Realm realm) {

        Categories categories = new Categories();

        categories.setName("Animals");
        categories.setId("0");
        realm.insertOrUpdate(categories);

        categories.setName("Birds");
        categories.setId("1");
        realm.insertOrUpdate(categories);

        categories.setName("Mountains");
        categories.setId("2");
        realm.insertOrUpdate(categories);

        categories.setName("Instagram");
        categories.setId("3");
        realm.insertOrUpdate(categories);

        categories.setName("Facebook");
        categories.setId("4");
        realm.insertOrUpdate(categories);

        categories.setName("Twitter");
        categories.setId("5");
        realm.insertOrUpdate(categories);

        categories.setName("OnePlus");
        categories.setId("6");
        realm.insertOrUpdate(categories);

        categories.setName("Apple");
        categories.setId("7");
        realm.insertOrUpdate(categories);

        categories.setName("Samsung");
        categories.setId("8");
        realm.insertOrUpdate(categories);

        categories.setName("Laptops");
        categories.setId("9");
        realm.insertOrUpdate(categories);

        categories.setName("Food");
        categories.setId("10");
        realm.insertOrUpdate(categories);

        categories.setName("Lifestyle");
        categories.setId("11");
        realm.insertOrUpdate(categories);

    }

    @Override
    public int hashCode() {
        return CategoriesInitialData.class.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        return obj != null && obj instanceof CategoriesInitialData;
    }
}

// SubCategories Initial Data


public class SubCategoriesInitialData implements Realm.Transaction {
    @Override
    public void execute(Realm realm) {


        SubCategories subCategories = new SubCategories();

        subCategories.setName("Animals1");
        subCategories.setId("0");
        realm.insertOrUpdate(subCategories);


        subCategories.setName("Animals2");
        subCategories.setId("0");
        realm.insertOrUpdate(subCategories);


        subCategories.setName("Animals3");
        subCategories.setId("0");
        realm.insertOrUpdate(subCategories);


        subCategories.setName("Birds1");
        subCategories.setId("1");
        realm.insertOrUpdate(subCategories);


        subCategories.setName("Birds2");
        subCategories.setId("1");
        realm.insertOrUpdate(subCategories);


        subCategories.setName("Birds3");
        subCategories.setId("1");
        realm.insertOrUpdate(subCategories);

    }

    @Override
    public int hashCode() {
        return SubCategoriesInitialData.class.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        return obj != null && obj instanceof SubCategoriesInitialData;
    }
}

// Category Fragment


public class CategoryFragment extends Fragment {

    Realm realm;
    MyCategoryAdapter myCategoryAdapter;
    RealmChangeListener realmChangeListener;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {


        View myView = inflater.inflate(R.layout.fragment_categories,container,false);
        final RecyclerView rv = (RecyclerView) myView.findViewById(R.id.categoryRV);
        rv.setLayoutManager(new LinearLayoutManager(this.getActivity()));


        //Realm configuration
        Realm.init(getContext());
        RealmConfiguration configuration = new RealmConfiguration.Builder().initialData(new CategoriesInitialData()).deleteRealmIfMigrationNeeded().build();
        realm = Realm.getInstance(configuration);


        //Save
        final CategoriesRealmHelper helper = new CategoriesRealmHelper(realm);
        //Categories categories = new Categories();
        //categories.setName("Last Category");
        //helper.save(categories);


        //retrieve
        helper.retrieveCategories();


        //setup adapter
        myCategoryAdapter = new MyCategoryAdapter(getContext(), helper.refreshCategories());
        rv.setAdapter(myCategoryAdapter);


        //data change
        realmChangeListener = new RealmChangeListener() {
            @Override
            public void onChange(Object element) {
                //refresh
                myCategoryAdapter = new MyCategoryAdapter(getContext(), helper.refreshCategories());
                rv.setAdapter(myCategoryAdapter);
            }
        };

        //add changes to realm
        realm.addChangeListener(realmChangeListener);


        return myView;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        realm.removeChangeListener(realmChangeListener);
        realm.close();

    }


    @Override
    public void onStop() {
        super.onStop();
    }
}

// SubCategories Fragment


public class SubCategoryFragment extends Fragment {

    Realm realm;
    MySubCategoryAdapter mySubCategoryAdapter;
    RealmChangeListener realmChangeListener;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {



        View myView = inflater.inflate(R.layout.fragment_subcategories, container, false);
        final RecyclerView rv = (RecyclerView) myView.findViewById(R.id.subcategoryRV);
        rv.setLayoutManager(new LinearLayoutManager(this.getActivity()));


        //Realm configuration
        Realm.init(getContext());
        RealmConfiguration configuration = new RealmConfiguration.Builder().initialData(new SubCategoriesInitialData()).deleteRealmIfMigrationNeeded().build();
        realm = Realm.getInstance(configuration);

        //Save
        final SubCategoriesRealmHelper helper = new SubCategoriesRealmHelper(realm);
        //SubCategories subCategories = new SubCategories();
        //subCategories.setName("Hello");
        //helper.save(subCategories);



        //retrieve
        helper.retrieveSubCategories();

        //setting up adapter
        mySubCategoryAdapter = new MySubCategoryAdapter(getContext(), helper.refreshSubCategories());
        rv.setAdapter(mySubCategoryAdapter);


        //data change
        realmChangeListener = new RealmChangeListener() {
            @Override
            public void onChange(Object element) {
                //refresh
                mySubCategoryAdapter = new MySubCategoryAdapter(getContext(), helper.refreshSubCategories());
                rv.setAdapter(mySubCategoryAdapter);
            }
        };

        //add changes to realm
        realm.addChangeListener(realmChangeListener);


        return  myView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        realm.removeChangeListener(realmChangeListener);
        realm.close();
    }

    @Override
    public void onStop() {
        super.onStop();
    }
}

// Realm Helper class. I also have a CategoriesRealmHelper class having similar methods


public class SubCategoriesRealmHelper {

    Realm realm;
    boolean saved;
    RealmResults<SubCategories> subCategories;


    public SubCategoriesRealmHelper(Realm realm) {
        this.realm = realm;
    }

    //Writing data to subcategories database
    public boolean save(final SubCategories subCategories)
    {
        if(subCategories == null)
        {
            saved = false;
        }
        else
        {
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {

                    try{

                        realm.copyToRealm(subCategories);
                        saved = true;
                    }catch (RealmException e)
                    {
                        e.printStackTrace();
                        saved = false;
                    }
                }
            });
        }
        return saved;
    }


    //reading data from subcategories database
    public void retrieveSubCategories()
    {
        subCategories = realm.where(SubCategories.class).findAll();
    }


    //refreshing subcategories data
    public ArrayList<SubCategories> refreshSubCategories()
    {
        ArrayList<SubCategories> latest = new ArrayList<>();
        for (SubCategories s : subCategories) {
            latest.add(s);
        }
        return latest;
    }

}

//Main Acitivity

public class MainActivity extends AppCompatActivity {

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


    void openFragment(){
        getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, new CategoryFragment()).commit();
    }

}

//Realm for Categories

public class Categories extends RealmObject {


    private String name;
    private String id;

    public String getName() {
        return name;
    }

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

    public String getId() {
        return id;
    }

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


}
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
parth shah
  • 11
  • 3
  • Hi @parth, This is really a pretty big bunch of code for someone to go through. I've only had time to scan it but I can find several questionable practices. Best practice for a Fragment to get a ref to its Activity, for instance, is here: https://stackoverflow.com/questions/13116104/best-practice-to-reference-the-parent-activity-of-a-fragment . Also, you are using a raw type here: `RealmChangeListener realmChangeListener;` . There is also no need to call `Realm.init` so often: Call it once in your Application. If you can trim this to a more specific question, I will try to answer. – G. Blake Meike Jul 26 '17 at 16:14
  • @G.BlakeMeike Thanks for pointing out my mistakes. About the question, I found a work around for it. There seemed to be a problem with using two realms. I am currently using a normal list to store the categories and realm to store the subcategories. – parth shah Aug 06 '17 at 11:30

0 Answers0