Using database on recyclerview - firebase

The first activity save some data at the firebase database and i need to show on the second activity using a recyclerview. I'm trying many times and i follow a tutorial, but always the recyclerview isn't displaying anything.
The Firebase was working correctly saving the data, but i can't put at recyclerview.
The activities are:
MenuActivity (recyclerview)
private RecyclerView recyclerView;
private Informações informações;
FirebaseDatabase database;
DatabaseReference myRef;
List<Informações> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("Informações");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
list = new ArrayList<Informações>();
for (DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){
Informações value = dataSnapshot1.getValue(Informações.class);
Informações informações = new Informações();
String empresa = value.getEmpresa();
String setor = value.getSetor();
String data = value.getData();
informações.setEmpresa(empresa);
informações.setSetor(setor);
informações.setData(data);
list.add(informações);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
RecyclerAdapter recyclerAdapter = new RecyclerAdapter(list, MenuActivity.this);
RecyclerView.LayoutManager recyce = new GridLayoutManager(MenuActivity.this,2);
recyclerView.setLayoutManager(recyce);
recyclerView.setAdapter(recyclerAdapter);
The RecyclerAdapter
List<Informações> list;
Context context;
public RecyclerAdapter(List<Informações> list, Context context){
this.list = list;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.adapter_lista,parent,false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder( MyViewHolder holder, int position) {
Informações mylist = list.get( position );
holder.empresa.setText(mylist.getEmpresa());
holder.setor.setText(mylist.getSetor());
holder.data.setText(mylist.getData());
}
#Override
public int getItemCount() {
int arr = 0;
try {
if (list.size() == 0)
{ arr = 0;
} else { arr = list.size(); }
} catch (Exception e) {}
return arr;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView empresa, setor, data;
public MyViewHolder(View itemView) {
super(itemView);
empresa = (TextView) itemView.findViewById(R.id.textEmpresa);
setor = (TextView) itemView.findViewById(R.id.textSetor);
data = (TextView) itemView.findViewById(R.id.textData);
}
}
}
And the Firebase
public class Informações {
private String equipe;
private String empresa;
private String setor;
private String responsavel;
private String visita;
private String ferramenta;
private String data;
public Informações() {
}
public void salvar(){
DatabaseReference firebase = ConfiguracaoFirebase.getFirebaseDatabase();
firebase.child("Informações")
.child( this.empresa )
.setValue( this );
}
public String getVisita() { return visita; }
public void setVisita(String visita) { this.visita = visita; }
public String getFerramenta() { return ferramenta; }
public void setFerramenta(String ferramenta) { this.ferramenta = ferramenta; }
public String getData() { return data; }
public void setData(String data) { this.data = data; }
public String getEquipe() { return equipe; }
public void setEquipe(String equipe) { this.equipe = equipe; }
public String getEmpresa() { return empresa; }
public void setEmpresa(String empresa) { this.empresa = empresa; }
public String getSetor() { return setor; }
public void setSetor(String setor) { this.setor = setor; }
public String getResponsavel() { return responsavel; }
public void setResponsavel(String responsavel) { this.responsavel = responsavel; }
}

Related

How do I change the value of child in firebase using a checkbox click

This is the code am using to fetch data from my firebase realtime database.
private void fetch() {
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("products");
FirebaseRecyclerOptions<Product> options =
new FirebaseRecyclerOptions.Builder<Product>()
.setQuery(query, new SnapshotParser<Product>() {
#NonNull
#Override
public Product parseSnapshot(#NonNull DataSnapshot snapshot) {
return new Product(snapshot.child("id").getValue().toString(),
snapshot.child("name").getValue().toString(),
snapshot.child("price").getValue().toString(),
snapshot.child("sku").getValue().toString(),
snapshot.child("category").getValue().toString(),
snapshot.child("subCategory").getValue().toString(),
snapshot.child("availability").getValue().toString());
}
})
.build();
adapter = new FirebaseRecyclerAdapter<Product, ProductsViewHolder>(options) {
#Override
public ProductsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_product, parent, false);
return new ProductsViewHolder(view);
}
#Override
protected void onBindViewHolder(ProductsViewHolder holder, final int position, final Product model) {
holder.setName(model.getName());
holder.setPrice(model.getPrice());
holder.setSubCategory(model.getSubCategory());
holder.setViewAvailability(model.getAvailability());
//holder.setSku(model.getSku());
holder.root.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Toast.makeText(ProductsActivity.this, model.getId(), Toast.LENGTH_SHORT).show();
}
});
}
};
recyclerView.setAdapter(adapter);
}
This is the product viewHolder
public class ProductsViewHolder extends RecyclerView.ViewHolder{
public CardView root;
public TextView viewSubCategory;
public TextView viewName;
public TextView viewPrice;
//public TextView viewSku;
public CheckBox viewAvailability;
Context context;
public ProductsViewHolder(View itemView) {
super(itemView);
root = itemView.findViewById(R.id.list_product_root);
viewSubCategory = itemView.findViewById(R.id.viewSubCategory);
viewName = itemView.findViewById(R.id.viewName);
viewPrice = itemView.findViewById(R.id.viewPrice);
viewAvailability = itemView.findViewById(R.id.viewAvailability);
//viewAvailability.setOnCheckedChangeListener(this);
}
public void setName(String string) {
viewName.setText(string);
}
public void setViewAvailability(String string) {
if (string.equals("0")){
viewAvailability.setChecked(false);
}else {
viewAvailability.setChecked(true);
}
}
public void setPrice(String string) {
viewPrice.setText(String.format("%,d", Integer.parseInt(string)));
}
/* public void setSku(String string) {
viewSku.setText(string);
}*/
public void setSubCategory(String string) {
viewSubCategory.setText(string);
}
}
veiwAvailaibility is a checkbox, that when checked it should change the value of availability (which is a child of a product) in firebase from 0 to 1 (checked and unchecked respectively). I am failing to get the clicking checking functionality done in the ViewHolder or in my fetch class. Any assistance is appreciated.
private void fetch() {
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("products");
FirebaseRecyclerOptions<Product> options =
new FirebaseRecyclerOptions.Builder<Product>()
.setQuery(query, new SnapshotParser<Product>() {
#NonNull
#Override
public Product parseSnapshot(#NonNull DataSnapshot snapshot) {
return new Product(snapshot.child("id").getValue().toString(),
snapshot.child("name").getValue().toString(),
snapshot.child("price").getValue().toString(),
snapshot.child("sku").getValue().toString(),
snapshot.child("category").getValue().toString(),
snapshot.child("subCategory").getValue().toString(),
snapshot.child("availability").getValue().toString());
}
})
.build();
adapter = new FirebaseRecyclerAdapter<Product, ProductsViewHolder>(options) {
#Override
public ProductsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_product, parent, false);
return new ProductsViewHolder(view);
}
#Override
protected void onBindViewHolder(ProductsViewHolder holder, final int position, final Product model) {
holder.setName(model.getName());
holder.setPrice(model.getPrice());
holder.setSubCategory(model.getSubCategory());
holder.setViewAvailability(model.getAvailability());
holder.viewAvailability.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if(isChecked){
//suggestion.setSelected(true);
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("products").child(model.getId());
Map<String, Object> updates = new HashMap<String,Object>();
updates.put("availability", "1");
ref.updateChildren(updates);
}else {
//suggestion.setSelected(false);
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("products").child(model.getId());
Map<String, Object> updates = new HashMap<String,Object>();
updates.put("availability", "0");
ref.updateChildren(updates);
}
}
});
//holder.setSku(model.getSku());
holder.root.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
};
recyclerView.setAdapter(adapter);
}

Save data from fragment to custom session

I am creating a project in which I am using navigation drawer and on navigation item click it opens a login page and after login it movies to my main activity. Now, I want to save my login details and all data in my custom shared preference from the fragment. After that it on app restarts and I go to navigation login items it should check if the user is already logged in then it should move to an activity otherwise it should run my login fragment
my login fragment
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
CDSMainViewModel =
ViewModelProviders.of(this).get(CDP_MainViewModel.class);
View root = inflater.inflate(R.layout.fragment_cdplogin, container, false);
context = container.getContext();
context = getActivity().getApplicationContext();
session = new Session(context);
if (session.isLoggedIn()) {
Intent itra = new Intent(getActivity().getApplicationContext(), Verification_Activity.class);
startActivity(itra);
getActivity().finish();
}
else{
login_button = root.findViewById(R.id.button_click_login);
edit1 = root.findViewById(R.id.input_username);
edit2 = root.findViewById(R.id.input_password);
layout_1 = root.findViewById(R.id.usnamelayout);
layout_2 = root.findViewById(R.id.password_layout);
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
return root;
}
private void Login_data() {
String URL = "http://117.240.196.238:8080/api/cdp/getAuth";
Log.i("response", URL);
StringRequest jsonObjRequest = new StringRequest(
Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("response_login", response);
parseData1(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("volley", "Error: " + error.getMessage());
showServerConnectionError();
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("AuthID", name);
params.put("AuthPwd", password);
return params;
}
};
RequestQueue queue = SingletonRequestQueue.getInstance(getActivity().getApplicationContext()).getRequestQueue();
queue.add(jsonObjRequest);
}
private void parseData1(String response){
try {
JSONObject json = new JSONObject(response);
int success = json.getInt("success");
String msg = json.getString("message");
if(success == 1){
Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
JSONArray recData = json.getJSONArray("data");
for (int i = 0; i < recData.length(); i++) {
JSONObject c = recData.getJSONObject(i);
String uname = name;
String upass = password;
String emp_id = c.getString("emp_id");
String empname = c.getString("EmpName");
String office = c.getString("OfficeNameFull");
String desig = c.getString("DesignationName");
String mobile = c.getString("EmpMobile");
String office_code = c.getString("OfficeCode");
String OfficeType = c.getString("OfficeType");
String district = c.getString("DistrictCode");
String DistrictName = c.getString("DistrictName");
String designationCode = c.getString("designationCode");
String DesignationName1 = c.getString("DesignationName1");
String DesigShortName = c.getString("DesigShortName");
Log.i("session",district);
//Here my loginsession is not working its not saving my data in my session..
Session.getInstance(getContext()).loginsession(emp_id,uname,upass,empname,office,desig,mobile,office_code,OfficeType,district,DistrictName,designationCode,DesignationName1,DesigShortName);
// String email = SessionManager.getInstance(context).getUserEmail();
// session.loginsession(emp_id,uname,upass,empname,office,desig,mobile,office_code,OfficeType,district,DistrictName,designationCode,DesignationName1,DesigShortName);
Intent its12 = new Intent(getActivity().getApplicationContext(), Verification_Activity.class);
startActivity(its12);
getActivity().overridePendingTransition(R.anim.from_right, R.anim.slide_to_left);
getActivity().finish();
}
} else {
Toast.makeText(context,msg, Toast.LENGTH_LONG).show();
}
}catch(Exception ex){
}
}
}
//Session manager class
package com.example.agridept.domain;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import com.example.agridept.ui.CDP_login.CDP_MainFragment;
public class Session {
private static Session jInstance;
SharedPreferences preferences;
SharedPreferences.Editor editor;
Context context;
int PRIVATE_MODE = 0;
private static final String IS_LOGIN = "IsLoggedIn";
private static final String PREF_NAME = "AndroidHivePref";
String emp_id1,username1,password1 ,empname1 , office1 , desig1, mobile1, office_code1, OfficeType1 , district1 ,DistrictName1 , designationCode1, DesignationName11 , DesigShortName1;
public Session(Context context){
this.context = context;
preferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = preferences.edit();
}
public void loginsession(String emp_id,String username,String password11 ,String empname ,String office ,String desig,String mobile,String office_code,String OfficeType ,String district ,String DistrictName ,String designationCode,String DesignationName1 ,String DesigShortName){
editor.putBoolean(IS_LOGIN, true);
editor.putString(emp_id1,emp_id);
editor.putString(username1,username);
editor.putString(password1,password11);
editor.putString(empname1,empname);
editor.putString(office1,office);
editor.putString(desig1,desig);
editor.putString(mobile1,mobile);
editor.putString(office_code1,office_code);
editor.putString(OfficeType1,OfficeType);
editor.putString(district1,district);
editor.putString(DistrictName1,DistrictName);
editor.putString(designationCode1,designationCode);
editor.putString(DesignationName11,DesignationName1);
editor.putString(DesigShortName1,DesigShortName);
}
public boolean isLoggedIn() {
return preferences.getBoolean(IS_LOGIN, false);
}
public void logoutUser() {
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to Loing Activity
Intent i = new Intent(context, CDP_MainFragment.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
context.startActivity(i);
}
public void clearinfo() {
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
}
public SharedPreferences getPreferences() {
return preferences;
}
public void setPreferences(SharedPreferences preferences) {
this.preferences = preferences;
}
public SharedPreferences.Editor getEditor() {
return editor;
}
public void setEditor(SharedPreferences.Editor editor) {
this.editor = editor;
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
public int getPRIVATE_MODE() {
return PRIVATE_MODE;
}
public void setPRIVATE_MODE(int PRIVATE_MODE) {
this.PRIVATE_MODE = PRIVATE_MODE;
}
public static String getIsLogin() {
return IS_LOGIN;
}
public static String getPrefName() {
return PREF_NAME;
}
public String getEmp_id1() {
return emp_id1;
}
public void setEmp_id1(String emp_id1) {
this.emp_id1 = emp_id1;
}
public String getPassword1() {
return password1;
}
public void setPassword1(String password1) {
this.password1 = password1;
}
public String getEmpname1() {
return empname1;
}
public void setEmpname1(String empname1) {
this.empname1 = empname1;
}
public String getOffice1() {
return office1;
}
public void setOffice1(String office1) {
this.office1 = office1;
}
public String getDesig1() {
return desig1;
}
public void setDesig1(String desig1) {
this.desig1 = desig1;
}
public String getMobile1() {
return mobile1;
}
public void setMobile1(String mobile1) {
this.mobile1 = mobile1;
}
public String getOffice_code1() {
return office_code1;
}
public void setOffice_code1(String office_code1) {
this.office_code1 = office_code1;
}
public String getOfficeType1() {
return OfficeType1;
}
public void setOfficeType1(String officeType1) {
OfficeType1 = officeType1;
}
public String getDistrict1() {
return district1;
}
public void setDistrict1(String district1) {
this.district1 = district1;
}
public String getDistrictName1() {
return DistrictName1;
}
public void setDistrictName1(String districtName1) {
DistrictName1 = districtName1;
}
public String getDesignationCode1() {
return designationCode1;
}
public void setDesignationCode1(String designationCode1) {
this.designationCode1 = designationCode1;
}
public String getDesignationName11() {
return DesignationName11;
}
public void setDesignationName11(String designationName11) {
DesignationName11 = designationName11;
}
public String getDesigShortName1() {
return DesigShortName1;
}
public void setDesigShortName1(String desigShortName1) {
DesigShortName1 = desigShortName1;
}
public static synchronized Session getInstance(Context context) {
if (jInstance != null) {
return jInstance;
} else {
jInstance = new Session(context);
return jInstance;
}
}
}

Correcting a null object reference while adding a recyclerview into a fragment

Trying to implement a recycleview inside of a fragment using a custom adapter and receiving the following error.
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference. AtStoreAdapter.getItemCount(StoreAdapter.java:xx)
I have looked around SO, but have not seen anything that is leading to a solution. Any help would be appreciated.
Android app - Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
and a few others
StoreAdapter
public class StoreAdapter extends RecyclerView.Adapter<StoreAdapter.StoreHolder>{
private LayoutInflater mInflator;
private List<Store> mStore= Collections.emptyList();
private Context mContext;
public StoreAdapter(Context mContext, List<Store> mStore){
mInflator = LayoutInflater.from(mContext);
this.mStore = mStore;
this.mContext = mContext;
}
// Simple nested class that holds the various view components for the adapter
// and as specified in *layout.xml .
public class StoreHolder extends RecyclerView.ViewHolder{
TextView mStoreTitle, mStoreDetails, mStoreCategory;
public StoreHolder (View itemView){
super(itemView);
mStoreTitle = (TextView) itemView.findViewById(R.id.title);
mStoreDetails = (TextView) itemView.findViewById(R.id.details);
mStoreCategory = (TextView) itemView.findViewById(R.id.category);
}
}
// Called when the RecyclerView needs a new RecyclerView.ViewHolder (*Holder)
// to represent an item. We inflate the XML layout and return our view (*Holder)
#Override
public StoreHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflator.inflate(R.layout.todo_list_row, parent,false);
return new StoreHolder(view);
}
// Called by RecyclerView to display the data at the specified position.
// This method needs to update the contents of the view to reflect the item at the
// given position e.g. we are updating the view here with the data
#Override
public void onBindViewHolder(StoreAdapter.StoreHolder holder, int position) {
holder.mStoreTitle.setText(mStore.get(position).getStoreTitle());
holder.mStoreDetails.setText(mStore.get(position).getStoreDetails());
holder.mStoreCategory.setText(mStore.get(position).getStoreCategory());
}
public void setData(List<Store> store){
this.mStore = store;
}
public void delete(int position){
mStore.remove(position);
notifyItemRemoved(position);
}
#Override
public int getItemCount() {
return mStore.size();
}
}
StoreSectionLoader
public class StoreSectionLoader extends AsyncTaskLoader<List<Store>> {
private static final String LOG_TAG = StoreSectionLoader.class.getSimpleName();
private List<Store> mStore;
private ContentResolver mContentResolver;
private Cursor mCursor;
public StoreSectionLoader(Context context, Uri uri, ContentResolver contentResolver){
super(context);
mContentResolver = contentResolver;
}
#Override
public List<Store> loadInBackground() {
String[] projection = {BaseColumns._ID,
RetailFinderContract.RetailFinderColumns.STORE_COMPLETE,
RetailFinderContract.RetailFinderColumns.STORE_CREATED,
RetailFinderContract.RetailFinderColumns.STORE_TITLE,
RetailFinderContract.RetailFinderColumns.STORE_DETAILS,
RetailFinderContract.RetailFinderColumns.STORE_CATEGRORY};
List<Store> entry = new ArrayList<>();
Uri uri = RetailFinderContract.URI_LOCATION_TABLE;
mCursor = mContentResolver.query(uri, projection, null, null, null);
if(mCursor != null){
if(mCursor.moveToFirst()){
do {
int _id = mCursor.getInt(mCursor.getColumnIndex(BaseColumns._ID));
String store_title = mCursor.getString(
mCursor.getColumnIndex(RetailFinderContract.RetailFinderColumns.STORE_TITLE));
String store_details = mCursor.getString(
mCursor.getColumnIndex(RetailFinderContract.RetailFinderColumns.STORE_DETAILS));
String store_category = mCursor.getString(
mCursor.getColumnIndex(RetailFinderContract.RetailFinderColumns.STORE_CATEGRORY));
Store store = new Store(_id,store_title,store_details,store_category);
entry.add(store);
} while (mCursor.moveToNext());
}
}
return entry;
}
#Override
public void deliverResult(List<Store> store) {
if(isReset()){
if (mStore != null){
mCursor.close();
}
}
List<Store> oldStoreList = mStore;
if(mStore == null || mStore.size() == 0 ){
Log.d(LOG_TAG, "+++++++++++++++ No Data returned");
}
mStore = store;
if(isStarted()){
super.deliverResult(store);
}
if(oldStoreList != null && oldStoreList != store){
mCursor.close();
}
}
#Override
protected void onStartLoading() {
if(mStore != null){
deliverResult(mStore);
}
if(takeContentChanged() || mStore == null){
forceLoad();
}
}
#Override
protected void onStopLoading() {
cancelLoad();
}
#Override
protected void onReset() {
onStopLoading();
if(mCursor != null){
mCursor.close();
}
mStore = null;
}
#Override
public void onCanceled(List<Store> store) {
super.onCanceled(store);
if(mCursor != null){
mCursor.close();
}
}
#Override
public void forceLoad() {
super.forceLoad();
}
}
StoreFragment
public class StoreFragment extends Fragment implements
LoaderManager.LoaderCallbacks<List<Store>> {
private static final String LOG_TAG = StoreListFragment.class.getSimpleName();
private StoreAdapter mAdapter;
private static final int LOADER_ID = 1;
private ContentResolver mContentReslover;
private List<Store> mStore;
private Context mContext;
protected RecyclerView mRecyclerView;
private static final String TAG = "RecyclerViewFragment";
private static final String KEY_LAYOUT_MANAGER = "layoutManager";
private enum LayoutManagerType {
GRID_LAYOUT_MANAGER,
LINEAR_LAYOUT_MANAGER
}
protected LayoutManagerType mCurrentLayoutManagerType;
protected RecyclerView.LayoutManager mLayoutManager;
// end added
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
mContentReslover = getActivity().getContentResolver();
getLoaderManager().initLoader(LOADER_ID, null, this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.store_list_row, container, false);
rootView.setTag(TAG);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.t_recycler);
mLayoutManager = new LinearLayoutManager(getActivity());
mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;
if (savedInstanceState != null) {
// Restore saved layout manager type.
mCurrentLayoutManagerType = (LayoutManagerType) savedInstanceState
.getSerializable(KEY_LAYOUT_MANAGER);
}
setRecyclerViewLayoutManager(mCurrentLayoutManagerType);
mAdapter = StoreAdapter(getContext(), mStore); //issue
mRecyclerView.setAdapter(mAdapter);
return rootView;
}
public void setRecyclerViewLayoutManager(LayoutManagerType layoutManagerType) {
int scrollPosition = 0;
// If a layout manager has already been set, get current scroll position.
if (mRecyclerView.getLayoutManager() != null) {
scrollPosition = ((LinearLayoutManager) mRecyclerView.getLayoutManager())
.findFirstCompletelyVisibleItemPosition();
}
switch (layoutManagerType) {
case LINEAR_LAYOUT_MANAGER:
mLayoutManager = new LinearLayoutManager(getActivity());
mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;
break;
default:
mLayoutManager = new LinearLayoutManager(getActivity());
mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;
}
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.scrollToPosition(scrollPosition);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save currently selected layout manager.
savedInstanceState.putSerializable(KEY_LAYOUT_MANAGER, mCurrentLayoutManagerType);
super.onSaveInstanceState(savedInstanceState);
}
#Override
public Loader<List<Store>> onCreateLoader(int id, Bundle args) {
mContentReslover = getActivity().getContentResolver();
return new StoreSectionLoader(getActivity(), RetailFinderContract.URI_STORES_TABLE, mContentReslover);
}
#Override
public void onLoadFinished(Loader<List<Store>> loader, List<Store> store) {
mAdapter.setData(store);
mStore = store;
}
#Override
public void onLoaderReset(Loader<List<Store>> loader) {
mAdapter.setData(null);
}
}

Updated code: Fragment ArrayList of objects not populated on first run

When running the code the ArrayList ArrayOfCategories1 is empty. When navigating to another fragment and back the ArrayList gets populated. I would like to get it populated the first time. Help would be appreciated as I am quite new to Android.
public class TabFragmentOne extends Fragment {
FragmentManager fm = getFragmentManager();
private static ArrayList<CategoryData> ArrayOfCategories = new ArrayList<>();
static ArrayList<CategoryData> ArrayOfCategories2 = new ArrayList<>();
ArrayList<CategoryData> ArrayOfCategories3 = new ArrayList<>();
private static final String ARG_EXAMPLE = "this_is_a_constant";
private String example_data;
public TabFragmentOne() {
}
public static TabFragmentOne newInstance(String example_argument) {
TabFragmentOne tabFragmentOne = new TabFragmentOne();
Bundle args = new Bundle();
args.putString(ARG_EXAMPLE, example_argument);
args.putParcelableArrayList("Categories", ArrayOfCategories2);
String myMessage = "This is working!";
args.putString("message", myMessage );
tabFragmentOne.setArguments(args);
return tabFragmentOne;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
// references to images
int[] mThumbIds = {
R.drawable.aardappelen, R.drawable.bier,
R.drawable.borrelhapjes, R.drawable.broodbeleg_hartig,
R.drawable.broodbeleg_zoet, R.drawable.dessert,
R.drawable.eieren, R.drawable.frisdranken,
R.drawable.fruitsappen, R.drawable.koekjes,
R.drawable.koffie, R.drawable.limonade,
R.drawable.pasta, R.drawable.rijst,
R.drawable.sauzen, R.drawable.vis,
R.drawable.vlees, R.drawable.wasmiddel,
R.drawable.wijn_rood, R.drawable.wijn_wit
};
ArrayList<String> mCategories2 = new ArrayList<String>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String Frank = getArguments().getString("message");
ArrayOfCategories2 = getArguments().getParcelableArrayList("Categories");
System.out.println("Lukt dit1? " + ArrayOfCategories2.size());
System.out.println("Lukt dit2? " + Frank);
// Creating the actual gridview
View view = inflater.inflate(R.layout.activity_collection_view, container, false);
if (ArrayOfCategories2.isEmpty()) {
return view;
} else {
System.out.println("New: " + ArrayOfCategories2.size());
ListAdapter imageAdapterCollectionViewCategories = new ImageAdapterCollectionViewCategories(getActivity(), mThumbIds, ArrayOfCategories2);
GridView gridview = (GridView) view.findViewById(R.id.gridView);
gridview.setAdapter(imageAdapterCollectionViewCategories);
//Click item in gridview
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(getActivity(), "" + position,
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(TabFragmentOne.this.getActivity(), ProductListActivity.class);
// pass the item information
intent.putExtra("categoryName", position);
System.out.print("Test??:" + position + ":test??");
startActivity(intent);
}
});
}
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
//Getting the Firebase Category Data
Firebase mRef;
mRef = new Firebase("x");
mRef.child("categories").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println("There are again " + dataSnapshot.getChildrenCount() + " categories");
ArrayOfCategories2.clear();
for (DataSnapshot categorySnapshot : dataSnapshot.getChildren()) {
CategoryData category = categorySnapshot.getValue(CategoryData.class);
ArrayOfCategories2.add(category);
System.out.println("Categories?: " + ArrayOfCategories2.size());
}
System.out.println("Check3: " + ArrayOfCategories2.get(1).getProductCategory());
class CategoryComparator implements Comparator<CategoryData> {
public int compare(CategoryData left, CategoryData right) {
return left.getProductCategory().compareTo(right.getProductCategory());
}
}
Collections.sort(ArrayOfCategories2, new CategoryComparator());
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.d("MyTag2", "Something went wrong!!");
}
});
}
#Override
public void onStart() {
super.onStart();
}
}
TabBarActivty:
public class TabBarActivity extends AppCompatActivity {
Firebase mRef;
ArrayList<ProductData> ArrayOfProducts = new ArrayList<ProductData>();
ArrayList<ProductData> SectionedArrayOfProducts = new ArrayList<ProductData>();
public static ArrayList<CategoryData> ArrayOfCategories = new ArrayList<>();
ArrayList<SubCategoryData> ArrayOfSubCategories = new ArrayList<SubCategoryData>();
public static ArrayList<String> ArrayOfCategoriesStrings = new ArrayList<>();
private ViewPager viewPager;
private TabLayout tabLayout;
private int[] tabIcons = {R.drawable.ic_products, R.drawable.ic_lists, R.drawable.ic_selections, R.drawable.ic_info, R.drawable.ic_user};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRef = new Firebase("x");
mRef.child("products").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println("There are " + dataSnapshot.getChildrenCount() + " products");
for (DataSnapshot productSnapshot : dataSnapshot.getChildren()) {
ProductData product = productSnapshot.getValue(ProductData.class);
ArrayOfProducts.add(product);
}
class ProductComparator implements Comparator<ProductData> {
public int compare(ProductData left, ProductData right) {
if (right.getProductCategory().equals(left.getProductCategory())) {
if (left.getProductSubCategory().equals(right.getProductSubCategory())) {
return left.getRecalculatedMetricsPricePerUnit().compareTo(right.getRecalculatedMetricsPricePerUnit());
}
return left.getProductSubCategory().compareTo(right.getProductSubCategory());
}
return left.getProductCategory().compareTo(right.getProductCategory());
}
}
Collections.sort(ArrayOfProducts, new ProductComparator());
for (int i = 0; i < ArrayOfProducts.size(); i++) {
String productName = ArrayOfProducts.get(i).getProductName();
Double productPrice = ArrayOfProducts.get(i).getProductPrice();
String productCategory = ArrayOfProducts.get(i).getProductCategory();
String productSubCategory = ArrayOfProducts.get(i).getProductSubCategory();
Double productCount = ArrayOfProducts.get(i).getProductCount();
Double productUnits = ArrayOfProducts.get(i).getProductUnits();
String productUnitType = ArrayOfProducts.get(i).getProductUnitType();
Double pricePerUnit = ArrayOfProducts.get(i).getPricePerUnit();
Double recalculatedMetricUnit = ArrayOfProducts.get(i).getRecalculatedMetricUnit();
Double recalculatedMetricsPricePerUnit = ArrayOfProducts.get(i).getRecalculatedMetricsPricePerUnit();
String supermarketName = ArrayOfProducts.get(i).getSupermarketName();
String updatedby = ArrayOfProducts.get(i).getUpdatedby();
String dateLastUpdate = ArrayOfProducts.get(i).getDateLastUpdate();
Double rating = ArrayOfProducts.get(i).getRating();
Double ratingWeight = ArrayOfProducts.get(i).getRatingWeight();
String ratingDate = ArrayOfProducts.get(i).getRatingDate();
String key = ArrayOfProducts.get(i).getKey();
if (i == 0) {
// Create a ProductData object to store the SubCategorySection
ProductData productData = new ProductData("SubCategorySectionHeader", null, null, (ArrayOfProducts.get(i).getProductSubCategory()), null, null, null, null, null, null, null, null, null, null, null, null, null);
SectionedArrayOfProducts.add(productData);
} else if (!ArrayOfProducts.get(i).getProductSubCategory().equals(ArrayOfProducts.get(i - 1).getProductSubCategory())) {
ProductData productData = new ProductData("SubCategorySectionHeader", null, null, (ArrayOfProducts.get(i).getProductSubCategory()), null, null, null, null, null, null, null, null, null, null, null, null, null);
SectionedArrayOfProducts.add(productData);
System.out.println(productData.getProductName() + " " + productData.getProductSubCategory());
}
// Create a ProductData object to store details
ProductData productData = ArrayOfProducts.get(i);
SectionedArrayOfProducts.add(productData);
System.out.println(SectionedArrayOfProducts.size());
}
System.out.println(SectionedArrayOfProducts.size());
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.d("MyTag2", "Something went wrong!!");
}
});
mRef.child("categories").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println("There are " + dataSnapshot.getChildrenCount() + " categories");
for (DataSnapshot categorySnapshot : dataSnapshot.getChildren()) {
CategoryData category = categorySnapshot.getValue(CategoryData.class);
ArrayOfCategories.add(category);
}
System.out.print("Check5: " + ArrayOfCategories.size());
System.out.println(ArrayOfCategories);
class CategoryComparator implements Comparator<CategoryData>
{
public int compare(CategoryData left, CategoryData right) {
return left.getProductCategory().compareTo(right.getProductCategory());
}
}
Collections.sort(ArrayOfCategories, new CategoryComparator());
System.out.print("Check6: " + ArrayOfCategoriesStrings.size());
Log.d("MyTag", "Oke!");
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.d("MyTag2", "Something went wrong!!");
}
});
mRef.child("subcategories").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println("There are " + dataSnapshot.getChildrenCount() + " subcategories");
for (DataSnapshot subcategorySnapshot : dataSnapshot.getChildren()) {
SubCategoryData subcategory = subcategorySnapshot.getValue(SubCategoryData.class);
ArrayOfSubCategories.add(subcategory);
}
class SubCategoryComparator implements Comparator<SubCategoryData> {
public int compare(SubCategoryData left, SubCategoryData right) {
return left.getProductSubCategory().compareTo(right.getProductSubCategory());
}
}
Collections.sort(ArrayOfSubCategories, new SubCategoryComparator());
System.out.println(ArrayOfSubCategories.get(1).getProductCategory());
Log.d("MyTag", "Oke!");
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.d("MyTag2", "Something went wrong!!");
}
});
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
tabLayout.getTabAt(3).setIcon(tabIcons[3]);
tabLayout.getTabAt(4).setIcon(tabIcons[4]);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(TabFragmentOne.newInstance("this data is for fragment 1"), "products", ArrayOfCategories);
adapter.addFragment(TabFragmentTwo.newInstance("this data is for fragment 2"), "lists", ArrayOfCategories);
adapter.addFragment(TabFragmentThree.newInstance("this data is for fragment 3"), "selections", ArrayOfCategories);
adapter.addFragment(TabFragmentFour.newInstance("this data is for fragment 4"), "info", ArrayOfCategories);
adapter.addFragment(TabFragmentFive.newInstance("this data is for fragment 5"), "user", ArrayOfCategories);
viewPager.setAdapter(adapter);
}
}
ViewPagerAdapter:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private ArrayList<Fragment> mFragmentList = new ArrayList<>();
private ArrayList<String> mFragmentListTitles = new ArrayList<>();
private ArrayList<CategoryData> categoryDataArrayList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title, ArrayList<CategoryData> arrayOfCategories){
mFragmentList.add(fragment);
mFragmentListTitles.add(title);
categoryDataArrayList = arrayOfCategories;
}
#Override public CharSequence getPageTitle(int position) {
return mFragmentListTitles.get(position);
}
}

ListView/adapter throwing IndexOutOfBound

I have a listview with a getCount() of 7. I want all 7 items to be shown regardless if any data from my database is available to populate them. If no data is available then an item should just be blank with predetermined text.
When I have not hardcoded 7 database entries beforehand to go into the 7 views then I get an indexoutofbound exception when running the app due to the 7 items not being able to be populated accordingly. This happens in ListMealsAdapter.java when method Meal currentItem = getItem(position); is called and triggers public Meal getItem(int position).
I am looking for a condition statement that I can use for my listview/adapter that can handle an empty database so that the index does not go out of bounds. Also, is the BaseAdapter suited for what I want to do?
MainActivity.java
public class MainActivity extends BaseActivity {
public static final String TAG = "MainActivity";
private ListView mListviewMeals;
private MealDAO mMealDao;
private List<Meal> mListMeals;
private ListMealsAdapter mAdapter;
private SQLiteDatabase mDatabase;
DatabaseHelper mDbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activateToolbar(1);
// initialize views
initViews();
// fill the dailyListView
mMealDao = new MealDAO(this);
mListMeals = mMealDao.getAllMeals();
mAdapter = new ListMealsAdapter(this, mListMeals, MainActivity.this);
mListviewMeals.setAdapter(mAdapter);
}
private void initViews() {
this.mListviewMeals = (ListView) findViewById(R.id.view_daily_list);
}
ListMealsAdapter.java
public class ListMealsAdapter extends BaseAdapter {
public static final String TAG = "ListMealsAdapter";
Activity mActivity;
private List<Meal> mItems;
private LayoutInflater mInflater;
public ListMealsAdapter(Context context, List<Meal> listMeals, Activity activity) {
super();
mActivity = activity;
this.setItems(listMeals);
this.mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return 7;
}
#Override
public Meal getItem(int position) {
return (getItems() != null && !getItems().isEmpty()) ? getItems().get(position) : null;
}
#Override
public long getItemId(int position) {
return (getItems() != null && !getItems().isEmpty()) ? getItems().get(position).getId() : position;
}
#Override
public View getView(int position, final View convertView, final ViewGroup parent) {
View v = convertView;
final ViewHolder holder;
if (v == null) {
v = mInflater.inflate(R.layout.list_item_daily, parent, false);
holder = new ViewHolder();
holder.txtDescription = (TextView) v.findViewById(R.id.txtBreakfast);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
// fill row data
Meal currentItem = getItem(position);
if (currentItem != null) {
holder.txtDescription.setText(currentItem.getDescription());
}
return v;
}
public List<Meal> getItems() {
return mItems;
}
public void setItems(List<Meal> mItems) {
this.mItems = mItems;
}
class ViewHolder {
TextView txtDescription;
}
}
Meal.java
public class Meal implements Serializable {
public static final String TAG = "Meal";
private static final long serialVersionUID = -7406082437623008161L;
private long mId;
private int mType;
private String mDescription;
public Meal() {
}
public Meal(int type, String description) {
this.mType = type;
this.mDescription = description;
}
public long getId() {
return mId;
}
public void setId(long mId) {
this.mId = mId;
}
public int getType() {
return mType;
}
public void setType(int mType) {
this.mType = mType;
}
public String getDescription() {
return mDescription;
}
public void setDescription(String mDescription) {
this.mDescription = mDescription;
}
}
MealDAO.java
public class MealDAO {
public static final String TAG = "MealDAO";
private SQLiteDatabase mDatabase;
private DatabaseHelper mDbHelper;
private Context mContext;
private String[] mAllColumns = { DatabaseHelper.COLUMN_MEAL_ID,
DatabaseHelper.COLUMN_MEAL_TYPE, DatabaseHelper.COLUMN_MEAL_DESCRIPTION};
public MealDAO(Context context) {
this.mContext = context;
mDbHelper = new DatabaseHelper(context);
// open the database
try {
open();
} catch (SQLException e) {
Log.e(TAG, "SQLException on opening database " + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException {
mDatabase = mDbHelper.getWritableDatabase();
}
public void close() {
mDbHelper.close();
}
public List<Meal> getAllMeals() {
List<Meal> listMeals = new ArrayList<Meal>();
Cursor query = mDatabase.rawQuery("SELECT * from meal", null);
if(query.moveToFirst()) {
do {
// Cycle through all records
Meal meal = cursorToMeal(query);
listMeals.add(meal);
} while(query.moveToNext());
}
return listMeals;
}
public Meal getMealById(long id) {
Cursor cursor = mDatabase.query(DatabaseHelper.TABLE_MEALS, mAllColumns,
DatabaseHelper.COLUMN_MEAL_ID + " = ?",
new String[] { String.valueOf(id) }, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
Meal meal = cursorToMeal(cursor);
return meal;
}
protected Meal cursorToMeal(Cursor cursor) {
Meal meal = new Meal();
meal.setId(cursor.getLong(0));
meal.setType(cursor.getInt(1));
meal.setDescription(cursor.getString(2));
return meal;
}
}
After a LOT of trial and error I finally found an acceptable solution to my problem. What I did was to add a default row to my database for the view items that I wanted to have a predetermined database entry when no data had been entered beforehand.
I then made sure to start at index 2, making sure that index 1 would be reserved for my default value. If the index comes out of bounds then the exception is caught and the default database entry will be added to the array.
public Meal getItem(int position) {
Meal result;
try {
result = (getItems() != null && !getItems().isEmpty()) ? getItems().get(position) : null;
} catch (Exception e) {
Meal default = getItem(0);
return default;
}
return result;
}
Meal currentItem = getItem(position + 1);
if (currentItem != null) {
holder.txtDescription.setText(currentItem.getDescription());
}
With that change things have been running smooth ever since. I hope this can help someone else as well.

Resources