Correcting a null object reference while adding a recyclerview into a fragment - android-fragments

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

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

java.lang.NumberFormatException: Invalid int: "130 PHP"

I dont know how to solve this problem
i cant find my error in codes
pls help me solve it :( thanks!
private void loadListFood() {
cart = new Database(this).getCarts();
adapter = new CartAdapter(cart,this);
recyclerView.setAdapter(adapter);
int total = 0;
for(Order order:cart)
total+=(Integer.parseInt(order.getPrice()))*(Integer.parseInt(order.getQuantity()));
Locale locale = new Locale("en", "US");
NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
txtTotalPrice.setText(fmt.format(total));
}
i am being redirected to
total+=(Integer.parseInt(order.getPrice()))*(Integer.parseInt(order.getQuantity()));
here is my adapter codes
public class CartAdapter extends RecyclerView.Adapter<CartViewHolder>{
private List<Order> listData = new ArrayList<>();
private Context context;
public CartAdapter(List<Order> cart, Cart cart1)
{
}
#Override
public CartViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View itemView = inflater.inflate(R.layout.cartlayout,parent,false);
return new CartViewHolder(itemView);
}
#Override
public void onBindViewHolder(CartViewHolder holder, int position) {
TextDrawable drawable = TextDrawable.builder()
.buildRound(""+listData.get(position).getQuantity(), Color.RED);
holder.img_cart_count.setImageDrawable(drawable);
int price = (Integer.parseInt(listData.get(position).getPrice()))*(Integer.parseInt(listData.get(position).getQuantity()));
holder.txt_price.setText(price);
holder.txt_cart_name.setText(listData.get(position).getProductName());
}
#Override
public int getItemCount() {
return listData.size();
}
}
From JavaDoc: The method Integer.parseInt(String s) throws a NumberFormatException
if the string does not contain a parsable integer.
That means, method order.getPrice() or order.getQuantity() returns "130 PHP" which is not a valid Integer.
Your real problem might be: Why the method returns a String and not Integer because you have to parse your String now. Pretty error prone and bad practice.
If your GUI element (or whatever) does not fit with Integer, at least remove your "PHP" out of the input field and you might be able to parse your String without manipulate it with some String helper methods.
class CartViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
, View.OnCreateContextMenuListener {
public TextView txt_cart_name,txt_price;
public ImageView img_cart_count;
private ItemClickListener itemClickListener;
public void setTxt_cart_name(TextView txt_cart_name) {
this.txt_cart_name = txt_cart_name;
}
public CartViewHolder(View itemView) {
super(itemView);
txt_cart_name = (TextView)itemView.findViewById(R.id.cart_item_name);
txt_price = (TextView)itemView.findViewById(R.id.cart_item_Price);
img_cart_count = (ImageView)itemView.findViewById(R.id.cart_item_count);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onClick(View view) {
}
#Override
public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
contextMenu.setHeaderTitle("Selecione uma Ação");
contextMenu.add(0,0,getAdapterPosition(),Common.DELETE);
}
}
public class CartAdapter extends RecyclerView.Adapter<CartViewHolder> {
private List<Order> listData = new ArrayList<>();
private Context context;
public CartAdapter(List<Order> listData, Context context) {
this.listData = listData;
this.context = context;
}
#Override
public CartViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View itemView = inflater.inflate(R.layout.cart_layout,parent,false);
return new CartViewHolder(itemView);
}
#Override
public void onBindViewHolder(CartViewHolder holder, int position) {
TextDrawable drawable = TextDrawable.builder()
.buildRound(""+listData.get(position).getQuantity(), Color.BLUE);
holder.img_cart_count.setImageDrawable(drawable);
Locale locale = new Locale("pt","BR");
NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
int price = (Integer.parseInt(listData.get(position).getPrice()))*(Integer.parseInt(listData.get(position).getQuantity()));
holder.txt_price.setText(fmt.format(price));
holder.txt_cart_name.setText(listData.get(position).getProductName());
}
#Override
public int getItemCount() {
return listData.size();
}
}

android fragment reloading (onCreate) each time when back Button pressed

I am new in android using fragments in my Project. first time my fragment is creating then api called and get data load in fragment. here when i clicked at any item i replaced fragment by another fragment there also another api called and load data to fragment.
now here problem situation generated for me.
from here i back Button pressed.
fragment reloading same as first time creating but it should be show data as i left before going to next fragment.
so please provide me solution how i can get same data as i left means savedInstanceState data.
im my first fragment getCategory method call Api and get Data first time when i choose any category i replace fragment with another fragment but when i m returning same getCategory method recall perform same process as it first time.
fragment should not call api method again on backpressed it should show same category on this i clicked before.
my first fragment where calling api......
public class LandingFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private GridLayoutManager gridLayoutManager;
private static RecyclerView category_Grid;
private Fragment myFragment = null;
ProgressBar mProgressView;
View mLoginFormView;
private Category category;
private CategoryAdapter categoryAdapter;
private List<CategoryObject> rowListItem;
private String productId;
private OnFragmentInteractionListener mListener;
public LandingFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment LandingFragment.
*/
// TODO: Rename and change types and number of parameters
public static LandingFragment newInstance(String param1, String param2) {
LandingFragment fragment = new LandingFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.fragment_landing, container, false);
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initViews(view);
RecyclerViewListeners();
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private void initViews(final View v) {
mLoginFormView = (View)v.findViewById(R.id.mainView);
mProgressView = (ProgressBar)v.findViewById(R.id.login_progress);
category_Grid = (RecyclerView)v.findViewById(R.id.cat_grid);
category_Grid.setHasFixedSize(true);
gridLayoutManager = new GridLayoutManager(getActivity(), 3);
category_Grid.setLayoutManager(gridLayoutManager);
}
private void RecyclerViewListeners(){
category_Grid.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), category_Grid, new ItemClickListener(){
#Override
public void onClick(View view, int position) {
String entityId = rowListItem.get(position).getCategoryId();
String catName = rowListItem.get(position).getName();
Integer ishave = rowListItem.get(position).getIshaveSubcategories();
if(ishave==1) {
myFragment = SubcategoryFragment.newInstance(""+catName, "" + entityId);
ActivityUtils.launchFragementWithAnimation(myFragment, getActivity());
}else{
myFragment = ProductListFragment.newInstance("", "" + entityId);
ActivityUtils.launchFragementWithAnimation(myFragment, getActivity());
}
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
public void getCategory() {
showProgress(true);
String URL = getResources().getString(R.string.category_api);
StringRequest req = new StringRequest(Request.Method.POST,URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.v("Response:%n %s", response);
Gson gson = new GsonBuilder().serializeNulls().create();
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("status").equals(getResources().getString(R.string.response_success))){
category = gson.fromJson(response, Category.class);
rowListItem = category.getCategory();
if(navigationUpdated){
someEventListener.someEvent(rowListItem);
navigationUpdated = false;
}
Log.d("CATEGORYID::::::::",""+rowListItem.get(1).getCategoryId());
categoryAdapter = new CategoryAdapter(getActivity(),rowListItem);
category_Grid.setAdapter(categoryAdapter);
categoryAdapter.notifyDataSetChanged();
return;
}
else if (jsonObject.getString("status").equals(getResources().getString(R.string.login_Er_respose))){
Log.e("","ERRORRRRRR");
return;
}
} catch (JSONException e) {
showProgress(false);
Log.e("My App", "Could not parse malformed JSON: \"" + response + "\"");
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
showProgress(false);
VolleyLog.e("Error: ", error.getMessage());
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
AppController.getInstance().addToRequestQueue(req);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
You can check your rowListItem.size(), if it's size is 0 then call getCategory() service, otherwise load your data from your rowListItem. Here is sample code which I am using to load data from arraylist if it is not empty:
if (mArrayArticle.size() == 0) {
isDataLoading = true;
mRecyclerList.setVisibility(View.INVISIBLE);
getCategory();
} else {
mHomeItemAdapter = new HomeItemAdapter(getActivity(), mArrayArticle, this);
mRecyclerList.setAdapter(mHomeItemAdapter);
}
Here mArrayArticle is my ArrayList, Hope it will help you.
for more clarification i want to tell..
how i implement the #Bhvk_AndroidBee solution
fragment backpressed call onActivityCreated Method so first overridethis method in fragment
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//here you can check null condition for rowListItem
}
}
inside onActivityCreated method I checked the condition like that
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(rowListItem!=null){
categoryAdapter = new CategoryAdapter(getActivity(),rowListItem);
category_Grid.setAdapter(categoryAdapter);
categoryAdapter.notifyDataSetChanged();
}else {
//call the method for first time creating your view
getCategory();
}
}
hope this would be helpfull for more strugglers like me...

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.

how to get the data and update to UI when new record available in SqliteDB?

I am working on a sample application by communicate with .net web service.In my application I am getting records from web service into my activity class then i am displaying entire records in ListView by using ArrayAdapter and also i am running a service class at background process for get the latest record from web service when the new records are available from web service then i am saving those records in to SQLite data base.This process is happening at back ground.Here i would like to get the latest data from SQLite DB and append to my ListView.
I have implemented Activity class as follows:
public class GetMsgsScreen extends ListActivity
{
private LayoutInflater mInflater;
private Vector<RowData> data;
RowData rd;
static String[] userName = null;
static String[] usrMessages = null;
private Integer[] imgid = null;
ShoutRepeatService bg;
////////////////////////////////////////////////////
List<Message> resultShoutMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
resultMessage = new ParseXml().convertMessages(new Model().getMessages("0"));
usrMessages = new String[resultMessage.size()];
userName = new String[resultMessage.size()];
imgid = new Integer[resultMessage.size()];
getSharedPreferences("Values", 0).edit().putString("msgid",resultMessage.get(0).getMessageID()).commit();
for(int i=0;i<resultMessage.size();i++)
{
Log.v("GetMsgsScreen", "resultMessage*******>>>>"+resultMessage.get(i).getMessageText());
Log.v("GetMsgsScreen", "resultNames*******>>>>"+resultMessage.get(i).getUserFirstName());
usrMessages[i] = resultMessage.get(i).getMessageText();
userName[i] = resultMessage.get(i).getUserFirstName();
imgid[i] = R.drawable.person;
}
///////////////////////////////////////////////////////
mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
for(int i=0;i<userName.length;i++){
try {
rd = new RowData(i,userName[i],usrMessages[i]);
} catch (ParseException e) {
e.printStackTrace();
}
data.add(rd);
}
CustomAdapter adapter = new CustomAdapter(this, R.layout.list, R.id.usrName, data);
setListAdapter(adapter);
bindService(new Intent(GetMsgsScreen.this, RepeatService.class), mConnection, Context.BIND_AUTO_CREATE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getListView().setTextFilterEnabled(true);
}
#Override
protected void onDestroy() {
unbindService(mConnection);
super.onDestroy();
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
bg = ((RepeatService.MyBinder) binder).getService();
Toast.makeText(GetMsgsScreen.this, "Connected",
Toast.LENGTH_SHORT).show();
}
public void onServiceDisconnected(ComponentName className) {
bg = null;
}
};
public void onListItemClick(ListView parent, View v, int position, long id) {
Toast.makeText(getApplicationContext(), "You have selected "
+(position+1)+"th item", Toast.LENGTH_SHORT).show();
}
private class CustomAdapter extends ArrayAdapter<RowData> {
public CustomAdapter(Context context, int resource, int textViewResourceId, List<RowData> objects) {
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
TextView name = null;
TextView messages = null;
ImageView i11=null;
RowData rowData= getItem(position);
if(null == convertView){
convertView = mInflater.inflate(R.layout.list, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
name = holder.gettitle();
name.setText(rowData.mName);
messages = holder.getdetail();
messages.setText(rowData.mMessage);
i11=holder.getImage();
i11.setImageResource(imgid[rowData.mId]);
return convertView;
}
private class ViewHolder {
private View mRow;
private TextView names = null;
private TextView messageText = null;
private ImageView i11=null;
public ViewHolder(View row) {
mRow = row;
}
public TextView gettitle() {
if(null == names){
names = (TextView) mRow.findViewById(R.id.usrName);
}
return names;
}
public TextView getdetail() {
if(null == messageText){
messageText = (TextView) mRow.findViewById(R.id.msgText);
}
return messageText;
}
public ImageView getImage() {
if(null == i11){
i11 = (ImageView) mRow.findViewById(R.id.img);
}
return i11;
}
}
}
}
I have implemented background service class as follows:
public class RepeatService extends Service
{
List<Message> resultMessage;
String[] userNameLatest = null;
String[] usrMessagesLatest = null;
String[] usrMessageID = null;
String msgID = null;
private Timer timer = new Timer();
private static final long UPDATE_INTERVAL = 500;
SQLiteDB db;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
pollForUpdates();
super.onCreate();
}
private void pollForUpdates() {
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Log.v("!!!!!!!!!!!!!!!!", "service is calling");
msgID = getSharedPreferences("Values", 0).getString("msgid","");
resultMessage = new ParseXml().convertMessages(new Model().getMessages(msgID));
usrMessagesLatest = new String[resultMessage.size()];
userNameLatest = new String[resultMessage.size()];
usrMessageID = new String[resultMessage.size()];
db = new SQLiteDB();
for(int i=0;i<resultMessage.size();i++)
{
Log.v("RepeatService", "getMessageID------>"+resultMessage.get(i).getMessageID());
Log.v("RepeatService", "getMessageText------>"+resultMessage.get(i).getMessageText());
Log.v("RepeatService", "getUserFirstName------>"+resultMessage.get(i).getUserFirstName());
usrMessagesLatest[i] = resultMessage.get(i).getMessageText();
userNameLatest[i] = resultMessage.get(i).getUserFirstName();
usrMessageID[i] = resultMessage.get(i).getMessageID();
//Save the data into Sqlite db here
db.insertValues(usrMessageID[i], userNameLatest[i], usrMessagesLatest[i], RepeatService.this);
}
}
}, 0, UPDATE_INTERVAL);
Log.v(getClass().getSimpleName(), "Timer started.");
}
public class MyBinder extends Binder {
ShoutRepeatService getService()
{
return ShoutRepeatService.this;
}
}
}
The above class always run at back ground if any new record available from web service then store the record into Sqlite db.
From the above code i can save the data in to Sqlite data base then
How can i show the latest record to my ListView on My Activity class?
please any body help me with code explanation.........
I would probably use a BroadcastReceiver that is notified from the service when something new has been added. It could then update your list. Also look at LocalBroadcastManager since all the communication is in your app.

Resources