无法访问我的Realm数据库的初始数据内容

时间:2017-07-24 06:26:51

标签: android android-fragments realm android-fragmentactivity realm-mobile-platform

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

    }
}

我制作了一个包含2个Recyclerviews的Android应用程序。两者都有各自的Realm数据库。 First Recyclerview显示类别。当我点击任何项目时,它会为我打开第二个Recyclerview(包含子类别)。我能够为Categories recyclerview加载初始数据,但当我点击其中的任何项目时,它会打开一个空白的recyclerview(理想情况下应显示SubCategories初始数据Realm数据库中的内容)

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


}

0 个答案:

没有答案