Accessing realm database across activities - android

I have 3 different activities. 1 extends Application and realm is configured in this activity. 2. Data is added to Realm from 2nd activity . 3. Data is to be displayed in the 3rd activity. I am unable to do the 3rd part. I am unable to get an instance of Realm in the 3rd activity. The following is Application(1st activity that I mentioned)
#Override
public void onCreate() {
super.onCreate();
Realm.init(this);
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder().build();
Realm.setDefaultConfiguration(realmConfiguration);
}
the following is the code for adding data to realm which is in a fragment inside 2nd activity(PurchaseDetailsActivity).
private void addDataToRealm(DBPurchase model) {
mRealm.beginTransaction();
DBPurchase dbPurchaseModel = new DBPurchase();
dbPurchaseModel.setId(id);
dbPurchaseModel.setAmountPayed(model.getAmountPayed());
dbPurchaseModel.setCredit(model.getCredit());
mRealm.insertOrUpdate(dbPurchaseModel);
mRealm.commitTransaction();
id++;
the last one is the fragment which is inside 3rd Activity.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_purchase_items, container, false);
purchaseTotalListAdapter = new PurchaseTotalListAdapter(getContext(), mDBPurchaseArrayList, PurchasesTotalListFragment.this);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(purchaseTotalListAdapter);
Realm.getDefaultInstance();
return view;
}

Related

How to add items in a recycler view from a different class

Have implemented a recycler view found on my notification fragments on adding itesm on the same fragments no problem occurs but when i try to add items from another fragment it throws and eror JavaNullPointException.
here is my fragment that has the recycler view
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View v = inflater.inflate (R.layout.fragment_notificationcict, container, false);
notimodels = new ArrayList<> ();
mRecyclerView = v.findViewById(R.id.notificationsRecycler);
fillNotification (R.drawable.logo, "OCApp", "Welcome to Online Clearance Application,Get cleared now , avoid queing up in offices , save time and money.",+ minutes+"min");
// get data from the notificiation
return v;
}
#Override
public void onStart() {
super.onStart ();
swipeRefreshLayout.setRefreshing(true);
fillNotification (R.drawable.logo, "OCApp", "Welcome to Online Clearance Application,Get cleared now , avoid queing up in offices , save time and money.",+ minutes+"min");
}
public void fillNotification(int mImage, String mtext, String mtext2, String mDate)
{
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager (getContext ());
mAdapter = new NotificationAdapter (notimodels);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
notimodels.add (0,new NotificationModel (mImage,mtext,mtext2,mDate));
}
}
**When i try to call the function from other fragments like tis forexample""
NotificationFragmentCict notificationFragmentCict =new NotificationFragmentCict ();
notificationFragmentCict.fillNotification (R.drawable.bursar, "Bursar", "your clreard","min");
My App crushes and throws this error
Process: com.univibezstudios.ocappservice.ocapp, PID: 3380
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference
The problem is this one This error is showing because your fragment's view is not created yet. That's why recyclerview is null and you're invoking setHasFixedSize(...) method on you null recyclerview. but icant solve it any help guys
You need to initialize the recycler view which you left out of the function fillNotification:
mRecyclerView = v.findViewById(R.id.notificationsRecycler);
you also need the ArrayList in the second fragment:
notimodels = new ArrayList<> ();

How to correctly add code to a Fragment with a Recycler view in XML?

I have only the mainActivity and I use 3 fragnments and navigate through them with a bottomnav. All good until now, Im able to run the app on the emulator but when I select this fragment with my RecyclerView I get this error message and the app crashes
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference
I've seen a lot of alike answers and try to make my way arround but no success, so Im thinking Im not putting the code in the correct way or in the correct places, can you give me some advice?
Here is the Fragment code
public class administrador_atletas extends Fragment {
//Lista de atletas
public List<lista_atletas> lista_atl;
public RecyclerView rcc_lista_atletas;
public lista_atletas_adaptador adaptador_lista_atletas;
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_administrador_atletas, container, false);
rcc_lista_atletas = (RecyclerView)view.findViewById(R.id.recycler_administrador_atletas);
return view;
}
#Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
LinearLayoutManager linear = new LinearLayoutManager(this.getActivity());
linear.setOrientation(LinearLayoutManager.VERTICAL);
rcc_lista_atletas.setLayoutManager(linear);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// do your variables initialisations here except Views!!!
data();
iniciar_adaptador_atletas();
}
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
}
public void data(){
lista_atl = new ArrayList<>();
lista_atl.add(new lista_atletas("Astrid Ruvalcaba Ramos", "Esgrima"));
lista_atl.add(new lista_atletas("Daniel Sanchez Cuevas", "G. Artistica"));
lista_atl.add(new lista_atletas("Alexa Luna Contreras", "TKD"));
lista_atl.add(new lista_atletas("Paul Carillo Mendez", "Natacion"));
lista_atl.add(new lista_atletas("Karen Mendoza Galindo", "Boxeo"));
lista_atl.add(new lista_atletas("Marco Torres Miranda", "Tiro con arco"));
}
public void iniciar_adaptador_atletas(){
adaptador_lista_atletas = new lista_atletas_adaptador(lista_atl);
rcc_lista_atletas.setAdapter(adaptador_lista_atletas);
}
Thanks in advance
EDIT: I just moved
data();
iniciar_adaptador_atletas();
Bellow
rcc_lista_atletas.setLayoutManager(linear);
In onCreateView so I have this
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_administrador_atletas, container, false);
rcc_lista_atletas = (RecyclerView)view.findViewById(R.id.recycler_administrador_atletas);
LinearLayoutManager linear = new LinearLayoutManager(this.getActivity());
linear.setOrientation(LinearLayoutManager.VERTICAL);
rcc_lista_atletas.setLayoutManager(linear);
data();
iniciar_adaptador_atletas();
return view;
}
And it worked, now Im able to enter the fragment with my data
Many thanks to all, your info was very useful!
As the error message says, you are calling the method setAdapter on a null-valued variable (probably rcc_lista_atletas).
While the error is not exactly in the source code you published (you should update your post with the full code), I suppose one of the methods, data() or iniciar_adaptador_atletas(), is calling 'setAdapter'.
You must remember that onCreate is executed before onCreateView. So, you're probably calling setAdapter before the onCreateView is executed and, doing so, rcc_lista_atletas is still null. Move data() and iniciar_adaptador_atletas() to the line before "return view;" in onCreateView and test it again.
This is the best we can do without checking you full code.
It seems, you try to connect adapter to recyclerView before created recyclerView. So, try to move iniciar_adaptador_atletas(); to the bottom of
rcc_lista_atletas = (RecyclerView)view.findViewById(R.id.recycler_administrador_atletas);

Implementing recycler view using sugar ORM

i am trying to display data from a textview on an activity onto a recycler view on a fragment. I have an adapter class to implement the adapter methods. however when i click the fragment the app closes and the .count method remains unable to be resolved. the code is attached below;
public class NotesXFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View noteview = inflater.inflate(R.layout.fragment_notes, container, false);
note_fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), AddNote.class));
}
});
RecyclerView recyclerView = (RecyclerView) noteview.findViewById(R.id.note_rv);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
// notesDbAdapter = new NotesDbAdapter(getActivity(),notes);
// recyclerView.setAdapter(notesDbAdapter);
notecount = Note.count(Note.class);
if(notecount>=0){
notes = Note.listAll(Note.class);
notesDbAdapter = new NotesDbAdapter(getActivity(),notes);
recyclerView.setAdapter(notesDbAdapter);
}
return noteview }
}
Please check if you're correctly importing the Note class. Moreover, you can try to get the count using the SugarRecord class, i find it to work better than using the normal classes.
notecount = SugarRecord.count(Note.class);
Please check if you're using the most recent version of the library.
Additionally, whenever you update your schema, please increment your DB version in your AndroidManifest.xml file.
<meta-data android:name="VERSION" android:value="2" />

private variable inside fragment are all null, why?

I have of null object inside a fragment. The basic idea is that I have an activity that fetches a database asynchronously. However my recyclerview where I will populate the data lives into a fragment. The pseudo-code is more or less
ACTIVITY:
public void onCreate(Bundle savedInstanceState) {
//kicks off a query to the server
mData = new Gson().fromJson(getIntent().getExtras().getString(Constants.MYDATA), MyData.class);
if (mVenue == null) {
finish();
return;
}
// a bunch of stuff
// create a fragment
mMyFrag = new MyFrag();
}
public void CallBackWhenDone(final List<DataSet> dataset) {
// notify the frag that we are done
mMyFrag.notifyDataSetChanged(messages);
}
FRAGMENT:
private RecyclerView mRV;
private ParentActivity mActivity;
private ActivityAsynchData mAsynchData;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.recycler, container, false);
mRV = (RecyclerView) view.findViewById(R.id.list);
mRV.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext(), LinearLayoutManager.VERTICAL, false));
if (null != mActivity) {
mAsynchData = mActivity.GetAsynchData();
}
if (null != mAsynchData) {
mRV.setAdapter(new MyRecyclerAdapter(getActivity(), mAsynchData));
}
}
// mRV is null when the activity "CallBackWhenDone" calls the frag
// all private variables are gone! why?
public void notifyDataSetChanged(final List<Message> messages) {
MyRecyclerAdapter adapter = ((MyRecyclerAdapter) mRV.getAdapter());
adapter.setMessageList(messages);
adapter.notifyDataSetChanged();
}
I ended up hacking my recycler (mRV in this case) view to be static, but this looks super hacked.
any way around? In other words how can I fetch my "mRV" after the fragment has been created and the private vars are all gone.
What i could understand is, that you initialised the fragment and try to access the recycler view in that but its throwing you null. I am not surprised to see it being as null. The way you have called the method is not correct.You need to get the hosted and already running fragment, instance try doing this:
if you are using support fragment use getSupportFragmentManager instead of getFragmentManager.
MyFrag fragment = (MyFrag) getFragmentManager().findFragmentById(R.id.fragmentHolder);
fragment.<specific_function_name>();
Here , the R.id.fragmentHolder is the id of the frame layout or any layout that you are using to host your fragment inside the an activity.
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragmentHolder"
android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>

RecyclerView crashes when used in fragment but not in activity

I was using a recyclerview in an activity and now decided to use it in a fragment instead. Now my code crashes at layoutmanager = new LinearLayoutManager (globalContext); with a NullPointerException.
I have no idea why. As I said it worked perfectly fine when used in activity.
I'm using Xamarin but that really doesn't make any difference.
I have only included the first parts of the code as app crashes before reaching others.
private Context globalContext = null;
RecyclerView recyclerview;
RecyclerView.LayoutManager layoutmanager;
NewsAdapter adapter;
public LatestNewsFragment()
{
this.RetainInstance = true;
}
public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = inflater.Inflate(Resource.Layout.fragment_latestnews, null);
// Get our RecyclerView layout:
recyclerview = view.FindViewById<RecyclerView> (Resource.Id.recyclerView);
return view;
}
public override async void OnActivityCreated(Bundle savedInstanceState)
{
base.OnActivityCreated(savedInstanceState);
globalContext = this.Context;
//............................................................
// Layout Manager Setup:
// Use the built-in linear layout manager:
layoutmanager = new LinearLayoutManager (globalContext);
// Plug the layout manager into the RecyclerView:
recyclerview.SetLayoutManager (layoutmanager);
//............................................................
// Adapter Setup:
// Create an adapter for the RecyclerView, and pass it the
// data set to manage:
var rest = new RestAccess();
var listofarticles = await rest.ListArticlesAsync("somesource", "1");
adapter = new NewsAdapter (listofarticles, globalContext);
// Register the item click handler (below) with the adapter:
adapter.ItemClick += OnItemClick;
// Plug the adapter into the RecyclerView:
recyclerview.SetAdapter (adapter);
}
// Handler for the item click event:
void OnItemClick (object sender, int position)
{
// Display a toast that briefly shows the enumeration of the selected photo:
int photoNum = position + 1;
Toast.MakeText(globalContext, "This is card number " + photoNum, ToastLength.Short).Show();
}
}
Edit:
So I changed the OnCreateView to :
public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = inflater.Inflate(Resource.Layout.fragment_latestnews, null);
// Get our RecyclerView layout:
recyclerview = view.FindViewById<RecyclerView> (Resource.Id.recyclerView);
// Plug the layout manager into the RecyclerView:
recyclerview.SetLayoutManager (new LinearLayoutManager (Activity));
return view;
}
And still getting nullpointer exception at recyclerview.SetLayoutManager (new LinearLayoutManager (Activity));
Edit 2:
variable recyclerview is actually null. Don't know why.
Answer:
My app was crashing for two reasons:
1- layoutmanager must be defined in OnCreateView but I was doing it in OnActivityCreated.
2- My fragment layout file didn't include the RecyclerView.
You need to set LayoutManager in onCreateView() after initializing RecyclerView, instead of setting in onActivityCreated():
mRecyclerView = (RecyclerView)v.findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(newLinearLayoutManager(mRecyclerView.getContext()));
Instead of this.Context use getActivity() to get Context in Fragment class. Change:
globalContext = this.Context;
to
globalContext = getActivity();
Try with getActivity()
layoutmanager = new LinearLayoutManager (getActivity());

Categories

Resources