I'm trying to pass an Image/Poster between activities through intent. I have used Picasso library and Recycler Adapter. but I'm unable to set the image in bundle extras after getting intent. after Year and title.
public class ShowMovieDetails extends AppCompatActivity implements OnNetworkCallHandled,RecyclerViewAdapter.OnClickListener {
private RecyclerViewAdapter adapter;
public RecyclerView recyclerView;
private DataWrapper list;
public Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_movie_details);
context=this;
Intent intent = getIntent();
String movieName = intent.getExtras().getString("moviename", "");
if (movieName != null) {
new MovieTask(movieName, this).execute();
}
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
public void onNetworkcallSuccess(Object object) {
//json to gson
String result = (String) object;
Gson gson = new Gson();
list = gson.fromJson(result, DataWrapper.class);
adapter = new RecyclerViewAdapter(list.getSearch(),this, this);
recyclerView.setAdapter(adapter);
System.out.print(result);
System.out.println("On success");
}
#Override
public void onNetworkcallFailure(Object object) {
System.out.println("On failure");
}
#Override
public void onClick(View view, int position, long itemId) {
startActivity(position);
System.out.println();
}
private void startActivity(int position) {
Intent intent = new Intent(this, DetailActivity.class);
Bundle extras = new Bundle();
extras.putString("Title", list.getSearch().get(position).getTitle());
extras.putString("Year", list.getSearch().get(position).getYear());
extras.putString("Poster",list.getSearch().get(position).getPoster());
intent.putExtras(extras);
startActivity(intent);
}
}
and the other class where m setting things in extras
public class DetailActivity extends AppCompatActivity {
private TextView Title;
private TextView Year;
private ImageView Image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
Title = (TextView) findViewById(R.id.Title);
Year = (TextView) findViewById(R.id.Year);
Image = (ImageView) findViewById(R.id.iVPoster);
if (intent != null) {
String title = extras.getString("Title");
String year=extras.getString("Year");
String image=extras.getString("Poster");
Title.setText(title);
Year.setText(year);
System.out.println();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
my recyclerAdapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MovieDetailsHolder> {
private ArrayList<MovieDetails> movieDetails;
private Context context;
private OnClickListener onClick;
RecyclerViewAdapter(ArrayList<MovieDetails> movieDetails, Context context, OnClickListener onClick) {
this.onClick = onClick;
this.movieDetails = movieDetails;
this.context = context;
}
#Override
public MovieDetailsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view, parent, false);
return new MovieDetailsHolder(view);
}
#Override
public void onBindViewHolder(MovieDetailsHolder holder, final int position) {
holder.tVMovieName.setText(movieDetails.get(position).getTitle());
Picasso
.with(context)
.load(movieDetails.get(position).getPoster())
.into(holder.iVPoster);
holder.setOnClickListener(onClick);
}
#Override
public int getItemCount() {
return movieDetails.size();
}
public static class MovieDetailsHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private OnClickListener onClickListener;
CardView cv;
TextView tVMovieName;
ImageView iVPoster;
MovieDetailsHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.cardView);
tVMovieName = (TextView) itemView.findViewById(R.id.tVMovieName);
iVPoster = (ImageView) itemView.findViewById(R.id.iVPoster);
itemView.setOnClickListener(this);
}
public void setOnClickListener(OnClickListener onClickListener) {
this.onClickListener = onClickListener;
}
#Override
public void onClick(View v) {
onClickListener.onClick(v, getPosition(), getItemId());
}
}
public interface OnClickListener {
public void onClick(View view, int position, long itemId);
}
}
In your startActivity() function, just as you got Title,Year and Poster; also get the url to the image.
This answer will help you.
Related
I want to create an onclick listener that reads the String from one TextView and then I somehow pass that string onto the main activity in order to open a third activity
So my main activity looks like this
public class AdvancedResults extends AppCompatActivity {
private RecyclerView mRecyclerView;
private AdvancedAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private ArrayList<String> mNames = new ArrayList<>();
private ArrayList<String> mImageUrls = new ArrayList<>();
private ArrayList<String> saved_recipes_with_ingredients = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_advanced_results);
advancedList.add(new AdvancedItem(R.drawable.ic_android, "test1", "test2");
advancedList.add(new AdvancedItem(R.drawable.ic_android, "test3", "test4");
mRecyclerView = findViewById(R.id.recyclerView1);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new AdvancedAdapter(advancedList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new AdvancedAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
// I want to open a new activity and append the string from the TextView here (maybe with get/set)
}
});
}
And my recycler adapter looks like this
public class AdvancedAdapter extends RecyclerView.Adapter<AdvancedAdapter.AdvancedViewHolder> {
private ArrayList<AdvancedItem> mAdvancedList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public static class AdvancedViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public TextView mTextView1;
public TextView mTextView2;
public AdvancedViewHolder(View itemView, final OnItemClickListener listener) {
super(itemView);
mImageView = itemView.findViewById(R.id.imageViewADV);
mTextView1 = itemView.findViewById(R.id.textViewADV1);
mTextView2 = itemView.findViewById(R.id.textViewADV2);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
int position = getAdapterPosition();
//how do I get the string from the TextView and pass it onto the main class?
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
}
}
public AdvancedAdapter(ArrayList<AdvancedItem> advancedList) {
mAdvancedList = advancedList;
}
#Override
public AdvancedViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.advanced_item, parent, false);
AdvancedViewHolder evh = new AdvancedViewHolder(v, mListener);
return evh;
}
#Override
public void onBindViewHolder(AdvancedViewHolder holder, int position) {
AdvancedItem currentItem = mAdvancedList.get(position);
holder.mImageView.setImageResource(currentItem.getImageResource());
holder.mTextView1.setText(currentItem.getText1());
holder.mTextView2.setText(currentItem.getText2());
}
#Override
public int getItemCount() {
return mAdvancedList.size();
}
i'm just not sure how im supposed to do that and what method to use.
So if you want the text from the text view you do:
String text = textViewId.getText();
But in your case you want to add the text for each one of the views on the list
So on the adapter how make a on click listener:
if (listener != null) {
int position = getAdapterPosition();
String text = mTextView1.getText();
Intent i = new Intent(getApplicationContext(), YourActitivity.class);
i.putExtra("nameYouWant", text)
startActivity(i);
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
Now on your activity :
String text = intent.getStringExtra("nameYouWant");
You can use interface to pass the second String param. So just add one String param like this -
public interface OnItemClickListener {
void onItemClick(int position, String text);
}
And in adapter pass the string on click of the item along with the position
listener.onItemClick(position, mTextView1.getText().toString());
And in the activity, you will receive the String text, from there you can pass it to ThirdActivity via bundle.
mAdapter.setOnItemClickListener(new AdvancedAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position, String textData) {
Intent i = new Intent(this, ThirdActivity.class);
i.putExtra("TEXT_KEY", textData);
}
});
Hope it will help!!
I want to pass a string value from my adapter class to my fragment. I tried storing the string in a bundle. To retrieve the value i used Bundle b = getArguments(); b.getString("key") the problem is im getting a null pointer exception. Below is the code that saves the string in a bundle. So my question is how can i pass a string value from adapterA to fragmentB.
Thanks in advance.
Adapter.java
public class ToDoRecyclerViewAdapter extends RecyclerView.Adapter<ToDoRecyclerViewAdapter.ViewHolder> {
private Context context;
private List<Aktivnost_> mValues;
private final OnListFragmentInteractionListener mListener;
public ToDoRecyclerViewAdapter td;
public ToDoRecyclerViewAdapter(List<Aktivnost_ > items, Context context, OnListFragmentInteractionListener listener) {
mValues = items;
mListener = listener;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_todo, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.mItem = mValues.get(position);
holder.mContentView.setText(mValues.get(position).getNaziv());
holder.mDateView.setText(mValues.get(position).getDatum());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (null != mListener) {
mListener.onListFragmentInteraction(holder.mItem);
Intent i = new Intent(context.getApplicationContext(), PodrobnostiActivity.class);
i.putExtra("task_id", mValues.get(position).getId_());
context.getApplicationContext().startActivity(i);
Toast.makeText(v.getContext(), "task - " + mValues.get(position).getId_(), Toast.LENGTH_SHORT).show();
}
}
});
holder.mView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
AlertDialog.Builder adb = new AlertDialog.Builder(v.getContext());
CharSequence meni[] = new CharSequence[] {"DOING", "FINISHED"};
adb.setItems(meni, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0) {
Bundle b = new Bundle();
DoingFragment d = new DoingFragment();
mValues.get(i).setStanje("doing");
b.putString("doing", mValues.get(i).getStanje());
d.setArguments(b);
} else {
mValues.get(i).setStanje("koncano");
}
}
});
AlertDialog alertDialog = adb.create();
alertDialog.setCancelable(true);
alertDialog.show();
return true;
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mContentView;
public final TextView mDateView;
public long id;
public Aktivnost_ mItem;
public ViewHolder(View view) {
super(view);
mView = view;
this.id = id;
mDateView = (TextView) view.findViewById(R.id.Date);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
And i want to get the value i set in bundle in this fragment.
Fragment.java
public class DoingFragment extends Fragment {
DoingFragmentRecyclerViewAdapter mAdapter;
private OnListFragmentInteractionListener mListener;
public DoingFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_doingfragment_list, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.list_doing);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
mAdapter = new DoingFragmentRecyclerViewAdapter(listAktivnosti(),mListener);
recyclerView.setAdapter(mAdapter);
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnListFragmentInteractionListener {
void onListFragmentInteraction1(Aktivnost_ item);
}
AppDatabase db;
public void openDB() {
db = new AppDatabase(getContext());
db.open();
}
Aktivnost_ ak;
List<Aktivnost_> array;
public List<Aktivnost_> listAktivnosti() {
array = new ArrayList<>();
openDB();
Bundle b = getArguments();
Cursor cursor = db.getAllRows(b.getString("doing"));
while(cursor.moveToNext()) {
ak = new Aktivnost_();
ak.setId_(cursor.getLong(cursor.getColumnIndex("_id")));
ak.setNaziv(cursor.getString(cursor.getColumnIndex("naziv")));
ak.setDatum(cursor.getString(cursor.getColumnIndex("datum")));
ak.setFk_projekt(cursor.getInt(cursor.getColumnIndex("fk_projekt")));
ak.setUdeleženci(cursor.getString(cursor.getColumnIndex("udelezenci")));
ak.setStanje(cursor.getString(cursor.getColumnIndex("stanje")));
array.add(ak);
}
return array;
}
}
From the code, I can see you are only setting the Bundle parameters in Fragment object, but not using that fragment object further.
You need to display that fragment object first, then it will reflect into your target fragment.
Recycle view not displaying data its shows an empty screen, It displays data when I go back and click the icon again. Not sure why I'm facing this problem.Please check the activity, adaptor and fragment code below. I'm new to android and I'm doing my capstone project it would be great if you can help me.
public class AppDetailsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("App Details");
setContentView(R.layout.activity_app);
AppDetailsFragment newFragment = new AppDetailsFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.recordAppFragmentContainer, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
public void refreshAppDuration(View v) {
Intent intent = new Intent(this, AppDetailsActivity.class);
startActivity(intent);
}
protected void onPause() {
super.onPause();
}
protected void onStop() {
super.onStop();
}
protected void onDestroy() {
super.onDestroy();
}
public void onBackAppDuration(View v) {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
Adaptor
public class AppDetailsAdaptor extends RecyclerView.Adapter<AppDetailsAdaptor.ViewHolder> {
private List<AppUsage> mApps;
private Context mContext;
public AppDetailsAdaptor(Context context, List<AppUsage> apps) {
mApps = apps;
mContext = context;
}
private Context getContext() {
return mContext;
}
#Override
public AppDetailsAdaptor.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View appUsageView = inflater.inflate(R.layout.item_app_details, parent, false);
// Return a new holder instance
AppDetailsAdaptor.ViewHolder viewHolder = new AppDetailsAdaptor.ViewHolder(appUsageView);
return viewHolder;
}
#Override
public void onBindViewHolder(AppDetailsAdaptor.ViewHolder viewHolder, final int position) {
// Get the data model based on position
final AppUsage ch = mApps.get(position);
// Set item views based on your views and data model
viewHolder._appTextView.setText(ch.getAppName());
viewHolder._durationTextView.setText(ch.getDurationInMinutes());
viewHolder._dateTextView.setText(ch.getDate().substring(0,10));
final String key = ch.getKey();
}
#Override
public int getItemCount() {
return mApps.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView _appTextView;
public TextView _durationTextView;
public TextView _dateTextView;
super(itemView);
_appTextView = (TextView) itemView.findViewById(R.id.rvs_app_name);
_durationTextView = (TextView) itemView.findViewById(R.id.rvs_app_duration);
_dateTextView =(TextView) itemView.findViewById(R.id.rvs_app_date);
}
}
}
Fragment
public class AppDetailsFragment extends Fragment {
final FirebaseDatabase database = FirebaseDatabase.getInstance();
ArrayList<AppUsage> appList = new ArrayList<>();
ArrayList<AppUsage> appListTemp = new ArrayList<>();
ArrayList<AppUsage> appListAdaptor = new ArrayList<>();
ArrayList<AppUsage> appObject = new ArrayList<>();
ArrayList<AppUsage> appListDate = new ArrayList<>();
private AppDetailsFragment.OnFragmentInteractionListener mListener;
private RecyclerView rvApp;
private RecyclerView.Adapter appAdaptor;
private RecyclerView.LayoutManager eLayoutManager;
private EditText date;
private static final int DIALOG_DATE_PICKER = 100;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_app_list, container, false);
rvApp = (RecyclerView) rootView.findViewById(R.id.rvAppList);
rvApp.setHasFixedSize(true);
eLayoutManager = new LinearLayoutManager(getActivity());
rvApp.setLayoutManager(eLayoutManager);
appList = getAllAppRecords();
appAdaptor = new AppDetailsAdaptor(getActivity(), appList);
rvApp.setAdapter(appAdaptor);
return rootView;
}
public ArrayList<AppUsage> getAllAppRecords(){
DatabaseReference ref = database.getReference();
ref.child("AppUsage").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
appObject.clear();
HashMap<String,Object> app = null;
Iterator<DataSnapshot> items = dataSnapshot.getChildren().iterator();
while(items.hasNext()){
DataSnapshot item = items.next();
Log.e("Listener",item.toString() );
app =(HashMap<String, Object>) item.getValue();
appObject.add(new AppUsage(app.get("appName").toString(),app.get("durationInMinutes").toString(),app.get("date").toString(),item.getKey()));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return appObject;
}
I want to display number of total items of my recyclerview in a textview. If new item is added or deleted that textview should be update. And also calculate total price of items in a list of Items in a recyclerview and display in a textview below recyclerview list.
Below is my recyclerview adapter:
public class CartAdapter extends RecyclerView.Adapter<CartAdapter.ViewHolder> {
private List<ProductView.Data> productData = Collections.emptyList();
static List<ProductModel> productModelList;
static Context context;
DatabaseHandler mDatabaseHandler;
public CartAdapter(Context context, List<ProductModel> dbList ){
this.productModelList = new ArrayList<ProductModel>();
this.context = context;
this.productModelList = dbList;
mDatabaseHandler = new DatabaseHandler( context );
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View cartListView = inflater.inflate(R.layout.list_item_cart, parent, false);
// Return a new holder instance
ViewHolder viewHolder = new ViewHolder(context,cartListView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.tvProductName.setText(productModelList.get(position).getTitle());
holder.tvProductPrice.setText(productModelList.get(position).getPrice());
Glide
.with(context)
.load(productModelList.get(position).getImageUrl())
.into(holder.imgProduct);
// holder.tvProductStatus.setText(productModelList.get(position).getIsAvailable());
holder.tvSize.setText(productModelList.get(position).getSize());
holder.tvProductQuantity.setText(Integer.toString(productModelList.get(position).getQuantity()));
holder.tvColor.setText(productModelList.get(position).getColor());
//holder.tvMaterial.setText(productModelList.get(position).getMaterial());
holder.imgDelete.setClickable(true);
holder.imgDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String idForDelete = String.valueOf(productModelList.get(position).getVariantId());
mDatabaseHandler.deleteARow(idForDelete);
productModelList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position,productModelList.size());
}
});
}
#Override
public int getItemCount() {
return productModelList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvProductName, tvProductPrice, tvProductQuantity,tvColor,
tvSize;
ImageView imgProduct;
ImageButton imgDelete;
Context context;
public ViewHolder(Context mContext, View itemView) {
super(itemView);
this.tvProductName = (TextView) itemView.findViewById(R.id.tv_cart_product_name);
this.tvProductPrice = (TextView) itemView.findViewById(R.id.tv_cart_product_price);
this.tvProductQuantity = (TextView) itemView.findViewById(R.id.tv_cart_product_Quantity);
this.imgProduct = (ImageView) itemView.findViewById(R.id.img_cart_item_product);
this.tvColor = (TextView)itemView.findViewById(R.id.tv_color);
this.tvSize = (TextView) itemView.findViewById(R.id.tv_size);
this.imgDelete = (ImageButton) itemView.findViewById(R.id.img_cart_delete);
// store the context ///
this.context = mContext;
}
}
and java Class:
public class CartActivity extends AppCompatActivity {
DatabaseHandler helper;
List<ProductModel> dbList;
RecyclerView mRecyclerView;
Toolbar toolbar;
Button btnCheckout, btnContinueShopping;
TextView tvTotalNoOfItems, tvTotalPrice;
String p;
String i;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
p = getIntent().getStringExtra("variant_id");
i = getIntent().getStringExtra("product_id");
Bundle extras = getIntent().getExtras();
if (extras != null) {
p = extras.getString("variant_id");
i= extras.getString("product_id");
}
toolbar = (Toolbar) findViewById(R.id.customToolBar);
setSupportActionBar(toolbar);
setTitle("Check-out");
toolbar.setTitleTextColor(Color.BLACK);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
helper = new DatabaseHandler(this);
dbList= new ArrayList<ProductModel>();
dbList = helper.getDataFromDB();
mRecyclerView = (RecyclerView)findViewById(R.id.rv_cart_item_list);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new CartAdapter(this,dbList);
mRecyclerView.setAdapter(mAdapter);
tvTotalNoOfItems = (TextView)findViewById(R.id.tvTotalCartItems);
tvTotalPrice = (TextView)findViewById(R.id.tvTotalCartItemsPrice);
String totalPrice = "";
for (int i = 0; i<dbList.size(); i++)
{
totalPrice = totalPrice + dbList.get(i).getPrice().toString();
}
tvTotalPrice.setText(totalPrice);
btnContinueShopping = (Button)findViewById(R.id.btnBackToProductActivity);
btnContinueShopping.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent launchCOllectionActivity = new Intent(CartActivity.this, CollectionActivity.class);
startActivity(launchCOllectionActivity);
finish();
}
});
btnCheckout = (Button)findViewById(R.id.btn_checkout);
btnCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent launchCheckoutActivity = new Intent(CartActivity.this,CheckoutActivity.class);
startActivity(launchCheckoutActivity);
}
});
}
}
First, add following getter to your adapter:
public List<ProductModel> getItems(){
return productModelList;
}
Then, you can subscribe on adapter data change and do the following:
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onChanged () {
tvTotalNoOfItems.setText(mAdapter.getItemCount());
String totalPrice = "";
for (int i = 0; i < ((CartAdapter)mAdapter).getItems().size(); i++) {
totalPrice = totalPrice + ((CartAdapter)mAdapter).getItems().get(i).getPrice().toString();
}
tvTotalPrice.setText("" + totalPrice);
}
});
just add this line below the adapter set line
tvTotalNoOfItems.setText(mAdapter.getCount());
and add this into you adapter class where you delete action perform
String totalPrice = "";
((CartActivity)context).tvTotalNoOfItems.setText(getCount());
for (int i = 0; i<productModelList.size(); i++)
{
totalPrice = totalPrice + productModelList.get(i).getPrice().toString();
}
((CartActivity)context).tvTotalPrice.setText(""+totalPrice);
Just public you textview like this
public TextView tvTotalNoOfItems, tvTotalPrice;
I made a question earlier about how to swap from listview to a recyclerview. However I noticed that with my change my update and delete didn't get saved. Which from my understanding has something to do with cursors being needed to update the contents. However currenty I am stuck with the following error
showAdapter = new ShowsAdapter(this, shows); // the error
Error:(68, 50) error: incompatible types: List cannot be converted to Cursor
private List<Show> shows;
private ShowsAdapter showAdapter;
private RecyclerView recyclerView;
private DataSource datasource;
public static final String INTENT_DETAIL_ROW_NUMBER = "Row number";
public static final String INTENT_DETAIL_REMINDER_TEXT = "Reminder text";
public static final int REQUESTCODE = 2;
public static final String EXTRA_SHOW_ID = "extraShowId";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
datasource = new DataSource(this);
datasource.open();
recyclerView = (RecyclerView) findViewById(R.id.main_list);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayoutManager);
//recyclerView.setAdapter(showAdapter);
updateUI();
//registerForContextMenu(recyclerView);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.taskView);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivityForResult(new Intent(MainActivity.this, CreateShowActivity.class), 1);
}
});
}
private void updateUI() {
shows = datasource.getAllShows();
if (showAdapter == null) {
showAdapter = new ShowsAdapter(this, shows); // the error
recyclerView.setAdapter(showAdapter);
} else {
showAdapter.notifyDataSetChanged();
}
}
My Adapter:
private List<Show> mShows;
private Context mContext;
private Cursor mShowsCursor;
public void updateList(List<Show> newlist) {
// Set new updated list
mShows.clear();
mShows.addAll(newlist);
notifyDataSetChanged();
}
public ShowsAdapter(Context mContext, Cursor cursor) {
this.mContext = mContext;
this.mShowsCursor = cursor;
}
#Override
public ShowsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(android.R.layout.simple_list_item_1, null);
// Return a new holder instance
ShowsAdapter.ViewHolder viewHolder = new ShowsAdapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ShowsAdapter.ViewHolder holder, final int position) {
if (mShowsCursor != null && mShowsCursor.moveToPosition(position)) {
holder.textView.setText(mShowsCursor.getString(mShowsCursor.getColumnIndex(MySQLiteHelper.COLUMN_SHOW)));
}
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, EditShowActivity.class);
intent.putExtra(INTENT_DETAIL_ROW_NUMBER, position);
intent.putExtra(INTENT_DETAIL_REMINDER_TEXT, holder.textView.getText());
((MainActivity) mContext).startActivityForResult(intent, REQUESTCODE);
}
});
holder.mView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
mShows.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position,mShows.size());
return true;
}
});