-3

While inserting List to Realm NullPointerException thrown. Please help me anyone.

Can you suggest me for best practice in Realm DB Management in Android

My Code:

public class DrinksFragment
        extends Fragment {

    private Realm realm;

    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_drinks, container, false);
        Realm.init(getActivity());
        realm = Realm.getDefaultInstance();
        return view;
    }

    public boolean drinksToDB(final List<ProductModel> productModel) {
        realm.executeTransactionAsync(new Realm.Transaction() {
            @Override
            public void execute(Realm bgrealm) {
                RealmList<ProductModel> realproductList = new RealmList<>();
                realproductList.addAll(productModel);
            }
        }, new Realm.Transaction.OnSuccess() {
            @Override
            public void onSuccess() {
                Log.d("REALM_DB_INSERT", "Data Inserted");
            }
        }, new Realm.Transaction.OnError() {
            @Override
            public void onError(Throwable error) {
                Log.d("REALM_DB_INSERT", error.getMessage());
            }
        });

        return true;
    }
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

1 Answers1

0

I advice you to do something like this:

First of all init Realm immediately only once when you open your app:

public class StartApplication
            extends Application {

        @Override
        public void onCreate() {
            super.onCreate();
            Realm.init(getApplicationContext());
        }
}

And then you can get the realm object in this way everywhere:

Realm realm = Realm.getDefaultInstance();
Amir Azizkhani
  • 1,662
  • 17
  • 30
Curio
  • 1,331
  • 2
  • 14
  • 34
  • Yes i'm Already done In Application Class – Natheem Yousuf Dec 23 '17 at 10:45
  • @NatheemYousuf so you don't have to write Realm.init(getActivity()); in your Fragment. Remove that line. – Curio Dec 23 '17 at 10:46
  • No Luck @Curio java.lang.NullPointerException: Attempt to invoke virtual method 'io.realm.RealmAsyncTask io.realm.Realm.executeTransactionAsync(io.realm.Realm$Transaction, io.realm.Realm$Transaction$OnSuccess, io.realm.Realm$Transaction$OnError)' on a null object reference – Natheem Yousuf Dec 23 '17 at 10:51
  • @NatheemYousuf when do you call drinksToDB method? – Curio Dec 23 '17 at 10:53