Implementing recycler view using sugar ORM - android

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" />

Related

How to create 2 columns in a databinded recyclerview adapter in android java

I am aware of what to do normally by means of a GridLayoutManager but as I've been using Google's GithubBrowserSample (Java) but I am unable to replicate the process using this method.
Tried changing the xml's span count but i am using the androidx version and seemingly doesn't play ball
My Main Fragment:
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
categoryViewModel = ViewModelProviders.of(this, viewModelFactory).get(CategoryViewModel.class);
refreshAndObserve();
CategoryListAdapter cvAdapter = new CategoryListAdapter(dataBindingComponent);
binding.get().categoryList.setAdapter(cvAdapter);
adapter = new AutoClearedValue<>(this, cvAdapter);
}
My Adapter:
public class CategoryListAdapter extends DataBoundListAdapter<Category, ListItemCategoryBinding> {
private final androidx.databinding.DataBindingComponent dataBindingComponent;
public CategoryListAdapter(DataBindingComponent dataBindingComponent) {
this.dataBindingComponent = dataBindingComponent;
}
#Override
protected ListItemCategoryBinding createBinding(ViewGroup parent) {
ListItemCategoryBinding binding = DataBindingUtil
.inflate(LayoutInflater.from(parent.getContext()), R.layout.list_item_category,
parent, false, dataBindingComponent);
return binding;
}
}
Thank you.
This can be done via the XML it seems:
app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
app:spanCount="2"

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

Accessing realm database across activities

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

Refreshing data display on a fragment

I have two fragments on a view pager.
I once had to move data from fragment B to A and refresh the data displayed on A and I did it with getItemPosition.
For some reason, the same method doesn't work when I try to reset all data..
In my adapter i have :
public void refresh()
{
notifyDataSetChanged();
}
#Override
public int getItemPosition( Object obj )
{
return POSITION_NONE;
}
in fragment where I click 'reset' :
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
notTriedPasswordsList = PagerActivity.mainList;
.....
....
resetButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick( View v )
{
PagerActivity.resetPasswords();
PagerActivity.viewPagerAdapter.refresh();
}});
viewPager activity hosting both fragments:
public static void resetPasswords()
{
mainList.addAll( 0, historyList );
historyList.clear();
PagerActivity.viewPagerAdapter.refresh();
}
Main fragment where the pass is displayed :
#Override
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState )
{
View view = inflater.inflate(R.layout.fragment_main, container, false);
.....
nextCodeDisplay = ( TextView ) view.findViewById( R.id.passwordDisplayTextView );
nextCodeDisplay.setText( notTriedPasswordsList.get( 0 ).getPasswordString() );
....
nextButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
notTriedPasswordsList.remove( 0 );
if( notTriedPasswordsList.size() > 0 && !(notTriedPasswordsList.get( 0 ).getTried()) )
{
nextCodeDisplay.setText( notTriedPasswordsList.get( 0 ).getPasswordString() );
}
}
PagerActivity is treated like a static class, and you can only access static methods and member data and objects in this way. About code:
notTriedPasswordsList = PagerActivity.mainList;
Note: So now PagerActivity can access static mainList object, or notTriedPasswordsList (sharing the same memory). But this is the only object you can access since your code references static methods.
On code PagerActivity.viewPagerAdapter.refresh(), I am not clear on what data this refreshes since I don't see the enough code, again refresh() must be a static method. With code notifyDataSetChanged(), there must be a direct link between viewPagerAdapter and the data object, probably an ArrayList. Certainly I don't see any direct relation between the two.
Perhaps you want code like:
viewPagerAdapter pagerAdapter = new viewPagerAdapter();
This way you can have the relationship between the adapter and possibly an ArrayList object. The benefit of creating an instance with new is that it saves data and the state inside the class in the form of an object, in my sample that is pagerAdapter.
I could not suggest specific set of codes for now since I don't see sufficient amount of it for me to fix. Perhaps you can fix code first and then we all can contribute.
Your call to PagerActivity.viewPagerAdapter.refresh(); won't cause your fragment to be redrawn. Instead you should access your fragment directly and create a custom refreshUI() method in it.
public void refreshUI(){
nextCodeDisplay.setText( notTriedPasswordsList.get( 0 ).getPasswordString() );
}
I suggest to change your approach. I've uploaded a simple project to my dropbox public folder. Here you can find a reference implementation of how two fragments managed by a ViewPager can share information. The first Fragment - Fragment#1 - simply displays a String that is generated by Fragment#2. Fragment#2 has a button that, when clicked, sends a random String to Fragment#1 through the Activity. No need to refresh viewpager, no need of static methods, simple and working. I guess you can adapt this example to your needs.
As you said that you want to refresh your data, personally i would like to suggest to use swipe refresh layout. It will be very useful for this purpose and stylish as well. Following is the code.
Swipe_Refresh_layout.xml
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
/>
</android.support.v4.widget.SwipeRefreshLayout>
And following is the activity i am using for this layout.
public class LatestNewsFragment extends Fragment implements OnRefreshListener ,OnScrollListener{
SwipeRefreshLayout swipeLayout;
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
=
View rootView = inflater.inflate(R.layout.Swipe_Refresh_layout, container, false);
swipeLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
return rootView;
}
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override public void run() {
swipeLayout.setRefreshing(false);
additemstatus();
}
}, 5000);
}
Now in overridden refresh method you can refresh or load your data. I hope this will be very helpful for your support.

Android-add value to a listview in a fragment via edittext from another fragment

i got a problem here. As the title said, i want to update a listview in a fragment adding a value from an edittext of another fragment. My main activity is a navigation drawer. My fragment with the listview is the Fragment_hotels and the other fragment witch contains the edittext is the FragmentAddHotel. I want to add in the listview (with the hotels) a new hotel.
Can someone explain how to do that?
Code given below:
Fragment_hotels:
public class Fragment_hotels extends Fragment {
public static boolean flag=false;
public void Add(){
Target.add("Hotel");
Target.add("Hotel1");
Target.add("Hotel2");
}
static ArrayList<String> Target = new ArrayList<String>();
#Override
public View onCreateView(
LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_hotels, container,false);
ListView listView = (ListView) view.findViewById(R.id.list);
if (flag==false){
this.Add();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),R.layout.mytextview,R.id.tv, Target);
adapter.setNotifyOnChange(true);
// Assign adapter to ListView
listView.setAdapter(adapter);
return view;
}
}
And FragmentAddHotel:
public class FragmentAddHotel extends Fragment {
public View onCreateView(
LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_add_hotel, container, false);
return rootView;
}
}
I got an edittext and a button on my FragmentAddHotel layout.
How can i get the value from edittext and add it on the listview?
Sorry if a similar question has already been answered but i am junior programmer.
Tnx in advance :)
To update view in class from another one you can use EventBus library here is the link
Just register you first class by adding:
EventBus.getDefault().register(this); //in your listener class that contains the listview at onCreate method.
Also implement your receiver method:
public void onEventMainThread(String hotelName) {
// Add the hotelName in your Target array list and then notify your adapter by adapter.notifyDataSetChanged();
}
To send data from your fragment just use :
EventBus.getDefault().post("edittextvalue");
Also don't forget to call :
EventBus.getDefault().unregister(this); // In your listener class onDestroy() method.
In YourActivity:
Fragment_hotels frag_hotels;
void addItem(String item){
frag_hotels.addItemToList(item);
}
Fragment_hotels:
List<String> hotelList;
ArrayAdapter<String> adapter;
void addItemToList(String item){
hotelList.add(item);
adapter.notifyDataSetChanged();
}
In FragmentAddHotel:
// you should call whenever adding is need in fragment
((YourActivity)getActivity()).addItem("Your Item");
Through YourActivity, you can communicate each fragment.

Categories

Resources