Java.lang.ClassCastException error and app crashes - java

Error Log I'm stuck here I've tried many solutions but same error
java.lang.ClassCastException: com.beauty.fashion.style.KidsNavigationDrawerActivity cannot be cast to com.beauty.fashion.style.interfaces.UpdateOrderTotal
at com.beauty.fashion.style.adapters.CheckoutAdapter.<init>(CheckoutAdapter.java:38)
at com.beauty.fashion.style.fragment.OrderConfirmationFragment.onCreateView(OrderConfirmationFragment.java:109)
This is my android code
public CheckoutAdapter(Context context, List<ProductModel> list) {
this.context = context;
this.list = list;
inflater = LayoutInflater.from(context);
callback = (UpdateOrderTotal) context; //This is line 38 of CheckoutAdapter
helper = new FashionDbHelper(context);
utils = new CartUtils(context);
}
This is where I'm getting products to cart list and app is crashing
if (utils.getCartList().getValue() != null) {
cartList.addAll(utils.getCartList().getValue());
if (cartList != null && cartList.size() > 0) {
linearEmptyCart.setVisibility(View.GONE);
cvGrandTotal.setVisibility(View.VISIBLE);
adapter = new CheckoutAdapter(getActivity(), cartList); //This is line 109
rvConfirmOrder.setAdapter(adapter);
rvConfirmOrder.setLayoutManager(new LinearLayoutManager(getActivity()));
calculateTotal(cartList);
} else {
linearEmptyCart.setVisibility(View.VISIBLE);
cvGrandTotal.setVisibility(View.GONE);
}
} else {
cvGrandTotal.setVisibility(View.GONE);
linearEmptyCart.setVisibility(View.VISIBLE);
}

You need KidsNavigationDrawerActivity to implement UpdateOrderTotal interface.
Something like this:
public class KidsNavigationDrawerActivity extends AppCompatActivity implements UpdateOrderTotal {
// your Activity code here
}

I've done it by myself after implementing interface to KidsNavigationDrawer activity

Related

How to update LiveData from another class?

I have this on my GroupDescriptionActivity class:
GroupDescriptionViewModel mFavViewModel;
ArrayList<String> mFav;
mFavViewModel = new ViewModelProvider(this).get(GroupDescriptionViewModel.class);
final Observer<ArrayList<String>> favsObserver = new Observer<ArrayList<String>>() {
#Override
public void onChanged(#Nullable final ArrayList<String> updatedList) {
if (mFav == null) {
mFav = updatedList;
ArrayAdapter arrayAdapter = new ArrayAdapter(context, android.R.layout.simple_expandable_list_item_1, mFav);
partecipants.setAdapter(arrayAdapter);
}
}
};
And in my GroupDescriptionViewModel:
public class GroupDescriptionViewModel extends AndroidViewModel {
private static MutableLiveData<ArrayList<String>> mFavs;
public GroupDescriptionViewModel(#NonNull Application application) {
super(application);
}
public static MutableLiveData<ArrayList<String>> getFavs(ArrayList<HashMap> partecipants) {
if (mFavs == null) {
mFavs = new MutableLiveData<>();
}
loadFavs(partecipants);
return mFavs;
}
public static void loadFavs(ArrayList<HashMap> partecipants) {
ArrayList<String> newFavs = new ArrayList<>();
for (HashMap member : partecipants) {
newFavs.add(member.get("mail").toString());
}
mFavs.setValue(newFavs);
}
}
I then have a firestore database change listener in the Source.java file. How can I update my ListView which is in the activity GroupDescription from Source.java?
I tried in Source.java
GroupDescriptionViewModel.getFavs((ArrayList<HashMap>) ((HashMap) arr.get(2)).get("partecipants"));
but didn't work. ((ArrayList<HashMap>) ((HashMap) arr.get(2)).get("partecipants") is my new array for the updates.
So I would like the new data to be entered from source via livedata, and my listview to update in real time
if Source.Java has a listener, why not implement it in the activity GroupDescription? or make an instance of Source.java in your viewModel and set the listener interface there and postValue of your MutableLiveData() inside the listener interface and observe it in your activity? from there you can notify your recyclerView adapter.

how to pass interface in fragment throw adapter?

In Home Fragment
userListAdapter = new UserListAdapter(getActivity(), response.getTray(), ?);
RVUserList.setAdapter(userListAdapter);
in Adapter
public UserListAdapter(Context context, ArrayList<TrayModel> list, UserListInterface listInterface) {
this.context = context;
this.trayModelArrayList = list;
this.userListInterface = listInterface;
}
and also implement UserListInterface in fragment
userListAdapter = new UserListAdapter(getActivity(), response.getTray(), new UserListInterface(){
// interface methods
});
RVUserList.setAdapter(userListAdapter);
userListAdapter = new UserListAdapter(getActivity(), response.getTray(), HomeFragment.this::userListClick);
RVUserList.setAdapter(userListAdapter);

How to prevent RecyclerView re-add items causing double of the same list after moving back from a new activity (MVVM)

I am learning RecyclerView in MVVM pattern from a youtube video. I create a recycler view to load very simple items. It works fine, but when I navigate to a new activity and then come back to the activity using Recycler View. My items in the list is duplicated. For example, my recycler view shows 2 items like Item1 and Item2. After I move to a new activity and return back, the list become Item1, Item 2, Item1 and Item2. So, each time I move to the new activity and return back, it keep doubling more and more. I only want the recycler view load one time, how can I solve this problem? Thank you.
My repo:
public class DWCategoryRepository {
private static DWCategoryRepository instance;
private ArrayList<DWCategories> dataSet = new ArrayList<>();
public static DWCategoryRepository getInstance() {
if (instance == null){
instance = new DWCategoryRepository();
}
return instance;
}
public MutableLiveData<List<DWCategories>> getDWCategories(){
setDWCategories();
MutableLiveData<List<DWCategories>> data = new MutableLiveData<>();
data.setValue(dataSet);
return data;
}
private void setDWCategories() {
dataSet.add(new DWCategories("Item1"));
dataSet.add(new DWCategories("Item2"));
}
}
My ViewModel:
public class MainWalletViewModel extends ViewModel {
private MutableLiveData<List<DWCategories>> mCategories;
private DWCategoryRepository mRepo;
public void init(){
if (mCategories != null) {
return;
}
mRepo = DWCategoryRepository.getInstance();
mCategories = mRepo.getDWCategories();
}
public LiveData<List<DWCategories>> getDWCategories(){
return mCategories;
}
}
View:
public class MainWalletActivity extends DWBaseActivity implements WalletCategoryAdapter.OnCategoryListener {
private WalletCategoryAdapter mWalletCategoryAdapter;
private MainWalletViewModel mMainWalletViewModel;
private RecyclerView mRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initializeDataBinding();
}
private void initializeDataBinding() {
MainWalletActivityBinding dataBinding = DataBindingUtil.setContentView(this, R.layout.main_wallet_activity);
setSupportActionBar(dataBinding.walletToolbar);
//Enable Back button on Toolbar
showBackArrowOnToolbar();
//Get Categories from View Model
initCategories();
//Set up adapter
mWalletCategoryAdapter = new WalletCategoryAdapter(this, mMainWalletViewModel.getDWCategories().getValue(), this);
//Set adapter to Recycler view
mRecyclerView = dataBinding.walletCategoryRV;
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mWalletCategoryAdapter);
//Add divider to Recycler view
mRecyclerView.addItemDecoration(new DividerItemDecoration(MainWalletActivity.this,
DividerItemDecoration.VERTICAL));
}
private void initCategories(){
mMainWalletViewModel = ViewModelProviders.of(this).get(MainWalletViewModel.class);
mMainWalletViewModel.init();
mMainWalletViewModel.getDWCategories().observe(this, new Observer<List<DWCategories>>() {
#Override
public void onChanged(#Nullable List<DWCategories> dwCategories) {
mWalletCategoryAdapter.notifyDataSetChanged();
}
});
}
}
You are calling setDWCategories in your getter.
public MutableLiveData<List<DWCategories>> getDWCategories(){
setDWCategories(); // <- Remove this line!
MutableLiveData<List<DWCategories>> data = new MutableLiveData<>();
data.setValue(dataSet);
return data;
}
You should only initialize your repo data once. Maybe do it in your getInstance() method if you are ok, starting over every time you run the app.

ListView doesn't refresh when I delete something

I have an custom adapter that is giving me problem. When I add or edit something it updates the listview but when I delete it doesn't.
Code when I remove something:
private ArrayList<Teams> m_orders = null;
private TeamsAdapter m_adapter;
private ListView lstv;
...
private void deleteTeam(int indexRemove){
hasKeys.remove(hasKeys.indexOf(m_orders.get(indexRemove).getTeamName()));
Menu.teams.remove(m_orders.get(indexRemove).getTeamName());
m_orders.remove(indexRemove);
m_adapter.notifyDataSetChanged();
}
I tried use a Runnable, but without success.
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if(m_orders != null && m_orders.size() > 0){
m_adapter.notifyDataSetChanged();
for(int i=0;i<m_orders.size();i++)
m_adapter.add(m_orders.get(i));
}
m_adapter.notifyDataSetChanged();
}
};
My onCreate method:
lstv = findViewById(R.id.teamsList);
m_orders = new ArrayList<Teams>();
this.m_adapter = new TeamsAdapter(this, R.layout.row, m_orders);
lstv.setAdapter(this.m_adapter);
You have to remove an item from the ArrayList which is inside the Adapter class. So you need to write your delete function inside the adapter class. In this way will able to delete items and update listview by calling notifyDataSetChanged() method.
You are creating an m_adapter with m_orders dataset, but you are removing item from m_teams dataset, make no sense, they are different instances.
final List<Teams> mTeams = new ArrayList<>();
TeamsAdapter mAdapter;
onCreate() {
mAdapter = new TeamsAdapter(this, R.layout.row, mTeams);
ListView listView = (ListView) findViewById(R.id.teamsList);
listView.setAdapter(mAdapter);
}
addTeams(Collection<Teams> items) {
mTeams.addAll(items);
mAdapter.notifyDataSetChanged();
}
deleteTeam(int index) {
mTeams.remove(index);
mAdapter.notifyDataSetChanged();
}

getView() in ArrayAdapter not getting called from AsyncTask

In one of my android activity, I've a ListView lvFeedsList.
Each row element in the listView will contain 3 textViews - RSSFeedName, publishDate & feedLength
The contents of the feeds is retrived from a HTTPRsponse.
I'm fetching this response in an AsyncTask.
So, in the doInBackground(), I've send the HTTPRequest & received & parsed the response & prepared the ArrayList containing 3 above mentioned information.
Then inside the doInBackground() only, I'm creating the customized ArrayAdapter for forming the 3 TextViews in row element.
My intetions are to set this adapter on ListView in onPostExecute().
But, when I run the application, the ListView does not display anything.
I tried to debug & it seems like getView() in the ArrayAdapter class is not getting called. (But I'm not sure if this is the reason).
Here is the code, sorry for the length...it seemed necessary.
Activity Code:
public class GenericFeedsActivity extends Activity{
private ListView lvFeedsList;
private ArrayList<FeedsClass> feedList;
protected void onCreate(Bundle savedInstanceState) {
...
lvFeedsList = (ListView) findViewById(R.id.lvFeedsList);
lvFeedsList.setOnItemClickListener(this);
lvFeedsList.setEnabled(false);
...
new AsyncResponseHandler(this).execute();
}
class AsyncResponseHandler extends AsyncTask {
Context context;
FeedListAdapter adapter;
public AsyncResponseHandler(Context c) {
this.context = c;
}
#Override
protected Object doInBackground(Object... params) {
...
/*
* Sending HTTPRequest to a URL & getting list of feeds
* Saving this list of feeds in a ArrayList -feedList, containing elements of type FeedsClass (declared above)
* Below line parses the HTTPResponse XML & stores various information in feedList.
*/
feedList = utils.parseRssResponseXML(in); // Working fine, geeting elements
adapter = new FeedListAdapter(
GenericFeedsActivity.this, feedList);
in.close();
return null;
}
protected void onPostExecute(Object e) {
// Setting Arrayadapter
lvFeedsList.setAdapter(adapter);
lvFeedsList.setEnabled(true);
}
}
}
Adapter Code:
public class FeedListAdapter extends ArrayAdapter {
private Context context;
private ArrayList<FeedsClass> feedList;
public FeedListAdapter(Context c, ArrayList<FeedsClass> data) {
super(c, R.layout.rowlayout);
this.context = c;
this.feedList = data;
}
class ViewHolder {
TextView tvFeedName;
TextView tvFeedPubDate;
TextView tvFeedLength;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflator.inflate(R.layout.rowlayout, null);
holder = new ViewHolder();
holder.tvFeedName = (TextView) row.findViewById(R.id.tvFeedName);
holder.tvFeedPubDate = (TextView) row.findViewById(R.id.tvFeedPubDate);
holder.tvFeedLength = (TextView) row.findViewById(R.id.tvFeedLength);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
// Getting values of feedName, publishDate & feedLength
String feedName = feedList.get(position).getTitle();
String feedDate = feedList.get(position).getPublishDate();
String feedLength = feedList.get(position).getStreamLength();
holder.tvFeedName.setText(feedName);
holder.tvFeedPubDate.setText(feedDate);
holder.tvFeedLength.setText(feedLength);
}
return row;
}
}
The issue is that you are subclassing ArrayAdapter. This doesn't work because ArrayAdapter internally thinks you do not have any elements in your data; it doesn't just magically know to look in the lvFeedsList variable because the data set it uses is internal.
Instead, in your constructor make sure to call this constructor instead:
Adapter code:
public FeedListAdapter(Context c, ArrayList<FeedsClass> data) {
super(c, R.layout.rowlayout, data); // add 'data'
this.context = c;
this.feedList = data;
}
Which will make everything work correctly.
adapter.notifyDataSetChanged()
could help at the end on of AsyncResponseHandler.onPostExecute(). If not - check whether ArrayList which hold data for adapter is empty or not.

Categories

Resources