how to use getItemCount for show all ViewHolder in recyclerAdapter? - android-recyclerview

how to use getItemCount for show all ViewHolder in recyclerAdapter?
I want show all viewHolder in recycler and in getItemCount What should i write؟
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<ModelItem_slider> requestItemsSlider;
private ArrayList<ModelItem_volume> requestItemsVolume;
private ArrayList<ModelItem_volume2> requestItemsVolume2;
private ArrayList<ModelItem_numbers> requestItemsNumber;
private ArrayList<ModelItem_news> requestItemsNews;
private Object[] myData;
private Context context;
public RecyclerAdapter(Context context
, ArrayList<ModelItem_slider> requestItems
, ArrayList<ModelItem_volume> requestItems1
, ArrayList<ModelItem_numbers> requestItems2
, ArrayList<ModelItem_news> requestItems3
, ArrayList<ModelItem_volume2> requestItems4
) {
this.context = context;
this.requestItemsSlider = requestItems;
this.requestItemsVolume = requestItems1;
this.requestItemsNumber = requestItems2;
this.requestItemsNews = requestItems3;
this.requestItemsVolume2 = requestItems4;
}
// viewHolders
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case 0:
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_slider, parent, false);
return new SliderViewHolder(view);
case 1:
View view2 = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_volume, parent, false);
return new VolumeViewHolder(view2);
case 2:
View view3 = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_news, parent, false);
return new NewsViewHolder(view3);
case 3:
View view4 = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_volume2, parent, false);
return new Volume2ViewHolder(view4);
default:
View view1 = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_number, parent, false);
return new NumberViewHolder(view1);
}
}
/// onBind and position
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof SliderViewHolder) {
final ModelItem_slider modelItem = requestItemsSlider.get(position);
((SliderViewHolder) holder).textSliderView.image(modelItem.getUrl());
((SliderViewHolder) holder).sliderLayout.addSlider(((SliderViewHolder) holder).textSliderView);
} else if (holder instanceof NumberViewHolder) {
final ModelItem_numbers modelItem_numbers = requestItemsNumber.get(position);
((NumberViewHolder) holder).name_number.setText(modelItem_numbers.getName_number());
((NumberViewHolder) holder).value_nubmer.setText(modelItem_numbers.getValue_number());
((NumberViewHolder) holder).profit_number.setText(modelItem_numbers.getProfit_number());
} else if (holder instanceof NewsViewHolder) {
final ModelItem_news modelItem1 = requestItemsNews.get(position);
((NewsViewHolder) holder).news.setText(modelItem1.getNews());
((NewsViewHolder) holder).news1.setText(modelItem1.getNews1());
} else if (holder instanceof VolumeViewHolder) {
ModelItem_volume modelItem_volume = requestItemsVolume.get(position);
((VolumeViewHolder) holder).name_volume.setText(modelItem_volume.getName_volume());
((VolumeViewHolder) holder).value_volume.setText(modelItem_volume.getValue_volume());
((VolumeViewHolder) holder).profit_volume.setText(modelItem_volume.getProfit_volume());
}else if (holder instanceof Volume2ViewHolder) {
ModelItem_volume2 modelItem_volume2 = requestItemsVolume2.get(position);
((Volume2ViewHolder) holder).name2.setText(modelItem_volume2.getName2());
((Volume2ViewHolder) holder).value2.setText(modelItem_volume2.getValue2());
((Volume2ViewHolder) holder).profit2.setText(modelItem_volume2.getProfit2());
}
}
#Override
public int getItemViewType(int position) {
return position > 0 ? 1 : 0;
}
/// i need help here
#Override
public int getItemCount() {
return requestItemsSlider.size();
}
in my activity and recuclerAdapter is not null in my project
this is for example
recyclerAdapter = new RecyclerAdapter(BaseActivity.getContext(), null, null, null, null, null);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(BaseActivity.getContext());
linearLayoutManager.setOrientation(LinearLayout.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(recyclerAdapter);
Inside the return.What amount to put To show all the cells.

I think you can use it like this:
#Override
public int getItemCount() {
return 2;
}

Related

spinner selected value returns to old value when recyclerview row is clicked

i have created an android application using xamarin.android. the application has a recyclerview that contains a spinner. what i want is when the user selects an item from the spinner, i need to change the value of the corresponding column and row in the datatable and i need the new value to be displayed in the spinner in the recyclerview in the row where the spinner value is selected. the problem is that whenever a value is selected, when another row is clicked, the old value of the spinner is displayed. i tried a lot of ways like the code in the following link: https://www.codeproject.com/articles/1033283/android-recycler-view-with-spinner-item-change-sel, but it didn't work. this is my code:
public class recyclerview_viewholder : RecyclerView.ViewHolder
{
public TextView rownbr, laborname;
public EditText overtime;
public LinearLayout linearLayout;
public Spinner days;
public recyclerview_viewholder(View itemView, Action<int> listener)
: base(itemView)
{
rownbr = itemView.FindViewById<TextView>(Resource.Id.rownbr);
laborname = itemView.FindViewById<TextView>(Resource.Id.laborname);
days = itemView.FindViewById<Spinner>(Resource.Id.days);
overtime = itemView.FindViewById<EditText>(Resource.Id.overtime);
linearLayout = itemView.FindViewById<LinearLayout>(Resource.Id.linearLayout);
itemView.Click += (sender, e) => listener(base.LayoutPosition);
}
public class recyclerviewAdapter : RecyclerView.Adapter
{
// Event handler for item clicks:
public event EventHandler<int> ItemClick;
// public event EventHandler<AdapterView.ItemSelectedEventArgs> SpinnerItemSelectionChanged;
public static DataTable summary_Requests = new DataTable();
//Context context;
public readonly new_schedule context;
public static int selected_pos = -1;
RecyclerView recyclerView;
FloatingActionButton delete;
public recyclerviewAdapter(new_schedule context, DataTable sum_req, RecyclerView recyclerView)
{
this.context = context;
summary_Requests = sum_req;
this.recyclerView = recyclerView;
}
public override RecyclerView.ViewHolder
OnCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.From(parent.Context).
Inflate(Resource.Layout.recycler_view_new_schedule_data, parent, false);
recyclerview_viewholder vh = new recyclerview_viewholder(itemView, OnClick);
vh.days.ItemSelected += (sender, e) =>
{
Spinner spinner = (Spinner)sender;
int position = Convert.ToInt32(spinner.Tag);
summary_Requests.Rows[position]["dayNbr"] = Convert.ToDecimal(spinner.GetItemAtPosition(e.Position).ToString());
};
vh.overtime.TextChanged += (sender, e) =>
{
if (vh.overtime.Text != "")
try
{
int position = vh.LayoutPosition;
summary_Requests.Rows[position]["overtimeHours"] = Convert.ToInt32(vh.overtime.Text);
user.zero_val = "Not_exist";
}
catch (System.FormatException exp)
{
var icon = AppCompatResources.GetDrawable(context.Context, Resource.Drawable.error_ic);
icon.SetBounds(0, 0, 50, 50);
vh.overtime.SetError("unit must be integer not decimal", icon);
user.zero_val = "exits";
}
else if (vh.overtime.Text == "")
{
var icon = AppCompatResources.GetDrawable(context.Context, Resource.Drawable.error_ic);
icon.SetBounds(0, 0, 50, 50);
vh.overtime.SetError("value can not be empty", icon);
user.zero_val = "exits";
}
};
return vh;
}
public override void
OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
recyclerview_viewholder vh = holder as recyclerview_viewholder;
vh.rownbr.Text = summary_Requests.Rows[position]["rowNumber"].ToString();
vh.laborname.Text = summary_Requests.Rows[position]["laborerName"].ToString();
List<decimal> days_data = new List<decimal>();
days_data.Add((decimal)0.5);
days_data.Add((decimal)1);
var adapter = new ArrayAdapter(this.context.Context, Android.Resource.Layout.SimpleSpinnerItem, days_data);
adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
vh.days.Tag = position;
vh.days.Adapter = adapter;
vh.days.SetSelection(1);
vh.overtime.Text = summary_Requests.Rows[position]["overtimeHours"].ToString();
if (selected_pos == position)
vh.ItemView.SetBackgroundColor(Color.ParseColor("#4fa5d5"));
else
vh.ItemView.SetBackgroundColor(Color.LightGray);
vh.ItemView.Click += (sender, e) =>
{
int pos = vh.LayoutPosition;
user.del_pos = position;
selected_pos = position;
NotifyDataSetChanged();
//fill global variables that need to be passed to detail fragment
};
//delete.Click += delegate
//{
// vh.days.Enabled = false;
//};
}
public DataTable get_dt_final()
{
DataTable final_dt = summary_Requests.Copy();
return final_dt;
}
public override long GetItemId(int position)
{
return position;
}
public void deleteItem(int index)
{
summary_Requests.Rows.RemoveAt(index);
NotifyItemRemoved(index);
}
public override int ItemCount
{
get { return summary_Requests.Rows.Count; }
}
// Raise an event when the item-click takes place:
void OnClick(int position)
{
if (ItemClick != null)
ItemClick(this, position);
// user.req_pos = position;
}
}
}
}
I read the article that you provide, you need to do two things when you change spinner value, firstly, you need to change vegeList's itemPosition quantity by SpinnerItemSelectionChangedEvent, then you need to update TotalAmount in OnBindViewHolder
private void SpinnerItemSelectionChangedEvent(object sender, AdapterView.ItemSelectedEventArgs e)
{
Spinner spinner = (Spinner)sender;
var itemPosition = Convert.ToInt32(spinner.Tag);
//Update the view by Total Amount, after spinner value is been selected.
var currentquantity = vegeList[itemPosition].Quantity;
var selectedQuantity = Convert.ToInt32(spinner.GetItemAtPosition(e.Position).ToString());
if (currentquantity != selectedQuantity)
{
vegeList[itemPosition].Quantity = selectedQuantity;
Madapter.NotifyItemChanged(itemPosition);
}
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
var item = Items[position];
var vh = holder as VegeViewHolder;
var spinnerPos = 0;
var adapter = new ArrayAdapter<String>(Context, Android.Resource.Layout.SimpleSpinnerItem, _quantity);
adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
vh.Name.Text = item.Name;
vh.Price.Text = string.Format("Price: ${0}", item.Price);
vh.ItemView.Tag = position;
if (item.Quantity > 0)
{
spinnerPos = adapter.GetPosition(item.Quantity.ToString());
vh.TotalAmount.Text = string.Format("${0}", item.Price * item.Quantity);
}
else
{
vh.TotalAmount.Text = "";
}
vh.Quantity.Tag = position; //keep reference to list view row position
vh.Quantity.Adapter = adapter;
vh.Quantity.SetSelection(spinnerPos);
vh.Image.SetImageResource(item.ImageId);
}

RecyclerView Item Swipe to Dismiss gets stuck sometimes

I am working on RecyclerView swipe to show an action button behind list items and my RecyclerView is in a fragment with Bottom Navigation and everything is going well but sometimes swipe stops and gets stuck so I can't completely swipe the item. I need your help with this. My codes:
The code in main activity:
ItemTouchHelper itemTouchhelper = new ItemTouchHelper(swipeController);
itemTouchhelper.attachToRecyclerView(movelistview);
movelistview.addItemDecoration(new RecyclerView.ItemDecoration() {
#Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
swipeController.onDraw(c,"action");
}
});
The code in the Swipe Controller class:
public class SwipeController extends ItemTouchHelper.Callback {
private static final float buttonWidth = 200;
private boolean swipeBack = false;
private ButtonsState buttonShowedState = ButtonsState.GONE;
private RectF buttonInstance = null;
private RecyclerView.ViewHolder currentItemViewHolder = null;
private SwipeControllerActions buttonsActions = null;
public SwipeController(SwipeControllerActions buttonsActions) {
this.buttonsActions = buttonsActions;
}
#Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
return makeMovementFlags(0, LEFT);
}
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
}
#Override
public int convertToAbsoluteDirection(int flags, int layoutDirection) {
if (swipeBack) {
swipeBack = buttonShowedState != ButtonsState.GONE;
return 0;
}
return super.convertToAbsoluteDirection(flags, layoutDirection);
}
#Override
public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
if (actionState == ACTION_STATE_SWIPE) {
if (buttonShowedState != ButtonsState.GONE) {
// if (buttonShowedState == ButtonsState.LEFT_VISIBLE) dX = Math.max(dX, buttonWidth);
if (buttonShowedState == ButtonsState.RIGHT_VISIBLE)
dX = Math.min(dX, -buttonWidth);
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
} else {
setTouchListener(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
}
if (buttonShowedState == ButtonsState.GONE) {
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
currentItemViewHolder = viewHolder;
}
private void setTouchListener(final Canvas c, final RecyclerView recyclerView, final RecyclerView.ViewHolder viewHolder, final float dX, final float dY, final int actionState, final boolean isCurrentlyActive) {
recyclerView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
swipeBack = event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_UP;
if (swipeBack) {
if (dX < -buttonWidth) buttonShowedState = ButtonsState.RIGHT_VISIBLE;
//else if (dX > buttonWidth) buttonShowedState = ButtonsState.LEFT_VISIBLE;
if (buttonShowedState != ButtonsState.GONE) {
setTouchDownListener(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
setItemsClickable(recyclerView, false);
}
}
return false;
}
});
}
private void setTouchDownListener(final Canvas c, final RecyclerView recyclerView, final RecyclerView.ViewHolder viewHolder, final float dX, final float dY, final int actionState, final boolean isCurrentlyActive) {
recyclerView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
setTouchUpListener(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
return false;
}
});
}
private void setTouchUpListener(final Canvas c, final RecyclerView recyclerView, final RecyclerView.ViewHolder viewHolder, final float dX, final float dY, final int actionState, final boolean isCurrentlyActive) {
recyclerView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
SwipeController.super.onChildDraw(c, recyclerView, viewHolder, 0F, dY, actionState, isCurrentlyActive);
recyclerView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
setItemsClickable(recyclerView, true);
swipeBack = false;
if (buttonsActions != null && buttonInstance != null && buttonInstance.contains(event.getX(), event.getY())) {
/*if (buttonShowedState == ButtonsState.LEFT_VISIBLE) {
buttonsActions.onLeftClicked(viewHolder.getAdapterPosition());
}else*/
if (buttonShowedState == ButtonsState.RIGHT_VISIBLE) {
buttonsActions.onRightClicked(viewHolder.getAdapterPosition());
}
}
buttonShowedState = ButtonsState.GONE;
currentItemViewHolder = null;
}
return false;
}
});
}
private void setItemsClickable(RecyclerView recyclerView, boolean isClickable) {
for (int i = 0; i < recyclerView.getChildCount(); ++i) {
recyclerView.getChildAt(i).setClickable(isClickable);
}
}
private void drawButtons(Canvas c, RecyclerView.ViewHolder viewHolder, String text) {
float buttonWidthWithoutPadding = buttonWidth - 0;
float corners = 0;
View itemView = viewHolder.itemView;
Paint p = new Paint();
int position = viewHolder.getAdapterPosition();
String button_text = "Report";
if (position >= 0) {
if (MainApplication.moves_list.get(position).getMove_userId().equals(MainApplication.user_id)) {
button_text = "Delete";
} else {
button_text = "Report";
}
}
RectF rightButton = new RectF(itemView.getRight() - buttonWidthWithoutPadding, itemView.getTop() + 0, itemView.getRight(), itemView.getBottom() - 0);
p.setColor(Color.RED);
c.drawRoundRect(rightButton, corners, corners, p);
drawText(button_text, c, rightButton, p);
buttonInstance = null;
if (buttonShowedState == ButtonsState.RIGHT_VISIBLE) {
buttonInstance = rightButton;
}
}
private void drawText(String text, Canvas c, RectF button, Paint p) {
float textSize = 40;
p.setColor(Color.WHITE);
p.setAntiAlias(true);
p.setTextSize(textSize);
float textWidth = p.measureText(text);
c.drawText(text, button.centerX() - (textWidth / 2), button.centerY() + (textSize / 2), p);
}
public void onDraw(Canvas c, String text) {
if (currentItemViewHolder != null) {
drawButtons(c, currentItemViewHolder, text);
}
}
}
I have had the same problem. swipe button stuck in UI, Behind recyclerview. So here is the easy and best solution ever i found.
create new Function in SwipeViewController as below
public void setSwipeBack()
{
swipeBack = false;
buttonShowedState = ButtonsStates.GONE;
}
and use this function in your fragment where your are filling data in the same recycler view.
as below
setSwipeBack();
I had the same problem, but the solution turned out to be easy.
This will happen when parent container will intercept your touch event. Any ViewGroup that overrides ViewGroup.onInterceptTouchEvent(MotionEvent) can do that (RecyclerView or ScrollView for instance).
And this will result in returning ACTION_CANCEL from your motionEvent when the Y value slightly changes, and sending touch events to parent view.
Proper way to deal with this is to call ViewParent.requestDisallowInterceptTouchEvent(boolean) method on your parent view once you think you need to keep the motion event.
Here's a quick example (attemptClaimDrag() method is taken from android source code):
/**
* Tries to claim the user's drag motion, and requests disallowing any
* ancestors from stealing events in the drag.
*/
private void attemptClaimDrag() {
// parent = yourView.getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
}
And in your onTouchEvent() or onTouch():
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (iWantToKeepThisEventForMyself(event)) {
attemptClaimDrag();
}
//your logic here
} else {
//your logic here
}
}

RecyclerView with in recyclerView with start ActivityOnresult

I have a recycler view(A) containing another recyclerview(B). When I click on the plus icon in recyclerview(A) item, it opens up a new activity with a recyclerview(C). Long pressing and selecting few items and clicking on done. This needs to update a recyclerview(B) on recyclerview (A) item on which I clicked the plus icon.
But instead, all the items of recyclerview(A) which contains recyclerview(B) is being updated.
private void displayUpcomingEvents(View view) {
upcomingEventsArrayList = new ArrayList<>();
upcomingEvents = new UpcomingEvents("Meet and greet", "Coffee Connect | ", "Phython", "21 - ", "Jun - ", "22", "Jun", "21 Jun 10 AM", "Washinton");
upcomingEventsArrayList.add(upcomingEvents);
upcomingEvents = new UpcomingEvents("Meet and greet", "Coffee Connect | ", "Phython", "21 - ", "Jun - ", "22", "Jun", "21 Jun 10 AM", "Washinton");
upcomingEventsArrayList.add(upcomingEvents);
upcomingEvents = new UpcomingEvents("Meet and greet", "Coffee Connect | ", "Phython", "21 - ", "Jun - ", "22", "Jun", "21 Jun 10 AM", "Washinton");
upcomingEventsArrayList.add(upcomingEvents);
upcomingEventsAdapter = new RecyclerAdapterUpcomingEvents(getContext(), upcomingEventsArrayList);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_upcoming_event);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getAppContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(upcomingEventsAdapter);
}
class RecyclerAdapterUpcomingEvents extends RecyclerView.Adapter<RecyclerAdapterUpcomingEvents.MyViewHolder> {
private List<UpcomingEvents> upcomingEventsList;
private Context context;
private LayoutInflater inflater;
RecyclerAdapterUpcomingEvents(Context context, List<UpcomingEvents> upcomingEventsList) {
this.context = context;
this.upcomingEventsList = upcomingEventsList;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rootView = inflater.inflate(R.layout.card_view_upcoming_event, parent, false);
return new RecyclerAdapterUpcomingEvents.MyViewHolder(rootView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
UpcomingEvents upcomingEvents = upcomingEventsList.get(position);
holder.eventUpcomingName.setText(upcomingEvents.getEventUpcomingName());
holder.eventUpcomingType.setText(upcomingEvents.getEventUpcomingType());
holder.eventUpcomingDate.setText(upcomingEvents.getEventUpcomingDateStart() + upcomingEvents.getEventUpcomingDateEnd());
holder.eventUpcomingMonth.setText(upcomingEvents.getEventUpcomingMonthEnd() + upcomingEvents.getEventUpcomingMonthEnd());
holder.eventUpcomingAlarmNotify.setText(upcomingEvents.getEventUpcomingAlarmNotify());
holder.eventUpcomingPlace.setText(upcomingEvents.getEventUpcomingPlace());
holder.eventUpcomingAddPeople.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Activity origin = (Activity) context;
origin.startActivityForResult(new Intent(getAppContext(), ContactsActivity.class), CONTACT_CODE);
}
});
holder.contactRecyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
contactAdapter = new ContactAdapter(getAppContext(), R.layout.card__contact_image, contactsList);`enter code here`
holder.contactRecyclerView.setAdapter(contactAdapter);
}
#Override
public int getItemCount() {
return upcomingEventsList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
private TextView eventUpcomingName, eventUpcomingType, eventUpcomingDate, eventUpcomingMonth, eventUpcomingAlarmNotify, eventUpcomingPlace, eventUpcomingYes, eventUpcomingInterested, eventUpcomingNo;
private ImageView eventUpcomingAddPeople, eventUpcomingmore;
private RecyclerView contactRecyclerView;
MyViewHolder(View itemView) {
super(itemView);
eventUpcomingName = (TextView) itemView.findViewById(R.id.event_name);
eventUpcomingType = (TextView) itemView.findViewById(R.id.event_type);
eventUpcomingDate = (TextView) itemView.findViewById(R.id.event_date);
eventUpcomingMonth = (TextView) itemView.findViewById(R.id.event_month);
eventUpcomingAlarmNotify = (TextView) itemView.findViewById(R.id.event_time_notify);
eventUpcomingPlace = (TextView) itemView.findViewById(R.id.event_place);
eventUpcomingYes = (TextView) itemView.findViewById(R.id.event_yes);
eventUpcomingInterested = (TextView) itemView.findViewById(R.id.event_interested);
eventUpcomingNo = (TextView) itemView.findViewById(R.id.event_no);
eventUpcomingmore = (ImageView) itemView.findViewById(R.id.event_more);
eventUpcomingAddPeople = (ImageView) itemView.findViewById(R.id.hex_one_event);
contactRecyclerView = (RecyclerView) itemView.findViewById(R.id.upcome_events_recycler);
}
}
}
#Override
public void onReceived(int requestCode, int resultCode, Intent data) {
if (requestCode == CONTACT_CODE && resultCode == RESULT_OK && data != null) {
List<Contact> contactsLists = (ArrayList<Contact>) data.getSerializableExtra("contacts");
contactsList.clear();
contactsList.addAll(contactsLists);
contactAdapter.setContactList(contactsLists);
upcomingEventsAdapter = new RecyclerAdapterUpcomingEvents(getContext(), upcomingEventsArrayList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getAppContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(upcomingEventsAdapter);
}
}
CardView
<android.support.v7.widget.RecyclerView
android:id="#+id/upcome_events_recycler"
android:layout_width="match_parent"
android:layout_height="52dp"
android:layout_below="#id/event_place"
android:layout_marginBottom="8dp"
android:layout_marginEnd="52dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp">
</android.support.v7.widget.RecyclerView>
<ImageView
android:id="#+id/hex_one_event"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_alignParentEnd="true"
android:layout_below="#id/event_place"
android:layout_margin="8dp"
android:src="#drawable/hex_src_plus" />
First change your code by this below :
holder.eventUpcomingAddPeople.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Activity origin = (Activity) context;
Intent i = new Intent(getAppContext(), ContactsActivity.class);
i.putExtra("selectedPosition", position);
origin.startActivityForResult(i, CONTACT_CODE);
}
});
#Override
public void onReceived(int requestCode, int resultCode, Intent data) {
if (requestCode == CONTACT_CODE && resultCode == RESULT_OK && data != null) {
int result = data.getIntExtra("selectedPosition","put a default value in case of null");
List<Contact> contactsLists = (ArrayList<Contact>) data.getSerializableExtra("contacts");
contactsList.clear();
contactsList.addAll(contactsLists);
contactAdapter.setContactList(contactsLists);
upcomingEventsAdapter.notifyItemChanged(result);
}
}
on the second activity you should have something like that when you click on done :
int param = getIntent().getIntExtra("selectedPosition");
Intent resultIntent = new Intent();
resultIntent.putExtra("contacts", Your selected contacts);
resultIntent.putExtra("selectedPosition", param);
setResult(RESULT_OK, resultIntent);
finish();
Hope it's clear and helpful :)

how to add text and textsize as selected size from spinner on canvas android?

i set text and textsize from edittextbox i get perfect size as i selected but whenever i set different textsize for another text it takes same textsize for both text as second textsize...i want text as selected textsize form spinner...help...
Thank u in advance
here is my code of alertdialogbox and spinner `
LayoutInflater linf = LayoutInflater.from(c_new);
final View inflator = linf.inflate(R.layout.dialog, null);
AlertDialog.Builder alert = new AlertDialog.Builder(c_new);
alert.setTitle("EditText");
alert.setView(inflator);
final EditText editText = (EditText) inflator.findViewById(R.id.editTextResult);
alert.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
srt=editText.getText().toString();
c.setEdittext(srt);
click_values c1 = new click_values();
c1.setImage(3);
dialog.cancel();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.show();
final Spinner spinner = (Spinner)inflator.findViewById(R.id.mySpinner);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item,textSize);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
c.setTextsize(Float.parseFloat(item));
spinner.setPrompt("Select Text Size");
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected Text Size: " + item, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
spinner.setPrompt("Title");
}
});
here is the code for set and get edittext and textsize`
static String Edittext;
public static String getEdittext() {
return Edittext;
}
public static String setEdittext(String edittext) {
click_values.Edittext = edittext;
Edittext = edittext;
return edittext;
}
static float textsize;
public static float getTextsize() {
return textsize;
}
public static void setTextsize(float textsize) {
click_values.textsize = textsize;
}
here i how i store text and textsize `
ArrayList<EdtText> editTexts = new ArrayList<EdtText>();
ArrayList<Integer> textsize = new ArrayList<Integer>();
if (text_c == 0 && c.getImage() == 4) {
mPaint.setTextSize(c.getTextsize());
mPaint.setStyle(Style.FILL);
canvas.drawText(c.getEdittext(), startX, startY, mPaint);
c.setImage(0);
} else if (c.getImage() == 4) {
editTexts.add(new EdtText(c.getEdittext(), startX, startY));
mPaint.setTextSize(c.getTextsize());
mPaint.setStyle(Style.FILL);
canvas.drawText(c.getEdittext(), startX, startY, mPaint);
c.setImage(0);
text_c = 0;
}
for (EdtText l : editTexts) {
canvas.drawText(l.EdtText1, l.startX, l.stopY, mPaint);
}
}

To display an album art from media store in android

I'm not able to display album art from media store while listing albums,I'm getting
error
Bad request for field slot 0,-1. numRows = 32, numColumns = 7
01-02 02:48:16.789: D/AndroidRuntime(4963): Shutting down VM
01-02 02:48:16.789: W/dalvikvm(4963): threadid=1: thread exiting with uncaught exception (group=0x4001e578)
01-02 02:48:16.804: E/AndroidRuntime(4963): FATAL EXCEPTION: main
01-02 02:48:16.804: E/AndroidRuntime(4963): java.lang.IllegalStateException: get field slot from row 0 col -1 failed
Can anyone kindly help with this issue,Thanks in advance
public class AlbumbsListActivity extends Activity {
private ListAdapter albumListAdapter;
private HashMap<Integer, Integer> albumInfo;
private HashMap<Integer, Integer> albumListInfo;
private HashMap<Integer, String> albumListTitleInfo;
private String audioMediaId;
private static final String TAG = "AlbumsListActivity";
Boolean showAlbumList = false;
Boolean AlbumListTitle = false;
ImageView album_art ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.albums_list_layout);
Cursor cursor;
ContentResolver cr = getApplicationContext().getContentResolver();
if (getIntent().hasExtra(Util.ALBUM_ID)) {
int albumId = getIntent().getIntExtra(Util.ALBUM_ID,
Util.MINUS_ONE);
String[] projection = new String[] { Albums._ID, Albums.ALBUM, Albums.ARTIST, Albums.ALBUM_ART, Albums.NUMBER_OF_SONGS };
String selection = null;
String[] selectionArgs = null;
String sortOrder = Media.ALBUM + " ASC";
cursor = cr.query(Albums.EXTERNAL_CONTENT_URI, projection, selection, selectionArgs, sortOrder);
/* final String[] ccols = new String[] {
//MediaStore.Audio.Albums.,
MediaStore.Audio.Albums._ID,
MediaStore.Audio.Albums.ALBUM,
MediaStore.Audio.Albums.ARTIST,
MediaStore.Audio.Albums.ALBUM_ART,
MediaStore.Audio.Albums.NUMBER_OF_SONGS
};
cursor = cr.query(MediaStore.Audio.Albums.getContentUri(
"external"), ccols, null, null,
MediaStore.Audio.Albums.DEFAULT_SORT_ORDER);*/
showAlbumList = true;
}
else
{
String order = MediaStore.Audio.Albums.ALBUM + " ASC";
String where = MediaStore.Audio.Albums.ALBUM;
cursor = managedQuery(Media.EXTERNAL_CONTENT_URI,
DbUtil.projection, null, null, order);
showAlbumList = false;
}
albumInfo = new HashMap<Integer, Integer>();
albumListInfo = new HashMap<Integer, Integer>();
ListView listView = (ListView) findViewById(R.id.mylist_album);
listView.setFastScrollEnabled(true);
listView.setOnItemLongClickListener(new ItemLongClickListener());
listView.setAdapter(new AlbumCursorAdapter(this, cursor,
DbUtil.displayFields, DbUtil.displayViews,showAlbumList));
final Uri uri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
final Cursor albumListCursor = cr.query(uri, DbUtil.Albumprojection,
null, null, null);
}
private class AlbumCursorAdapter extends SimpleCursorAdapter implements SectionIndexer{
private final Context context;
private final Cursor cursorValues;
private Time musicTime;
private Boolean isAlbumList;
private MusicAlphabetIndexer mIndexer;
private int mTitleIdx;
public AlbumCursorAdapter(Context context, Cursor cursor, String[] from,
int[] to,Boolean isAlbumList) {
super(context, 0, cursor, from, to);
this.context = context;
this.cursorValues = cursor;
//musicTime = new Time();
this.isAlbumList = isAlbumList;
}
String albumName="";
String artistName = "";
String numberofsongs = "";
long albumid;
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater
.inflate(R.layout.row_album_layout, parent, false);
}
this.cursorValues.moveToPosition(position);
String title = "";
String artistName = "";
String albumName = "";
int count;
long albumid = 0;
String songDuration = "";
if (isAlbumList) {
albumInfo.put(
position,
Integer.parseInt(this.cursorValues.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Albums._ID))));
artistName = this.cursorValues
.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Albums.ARTIST));
albumName = this.cursorValues
.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Albums.ALBUM));
albumid=Integer.parseInt(this.cursorValues.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ID)));
} else {
albumInfo.put(position, Integer.parseInt(this.cursorValues
.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Media._ID))));
artistName = this.cursorValues.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Media.ARTIST));
albumName = this.cursorValues.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Media.ALBUM));
albumid=Integer.parseInt(this.cursorValues.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)));
}
//code for Alphabetical Indexer
mTitleIdx = cursorValues.getColumnIndex(MediaStore.Audio.Media.ALBUM);
mIndexer = new MusicAlphabetIndexer(cursorValues, mTitleIdx,
getResources().getString(R.string.fast_scroll_alphabet));
//end
TextView metaone = (TextView) rowView.findViewById(R.id.album_name);
TextView metatwo = (TextView) rowView.findViewById(R.id.artist_name);
ImageView metafour = (ImageView) rowView.findViewById(R.id.album_art);
TextView metathree = (TextView) rowView
.findViewById(R.id.songs_count);
metaone.setText(albumName);
metatwo.setText(artistName);
(metafour)getAlbumArt(albumid);
System.out.println("albumid----------"+albumid);
metaThree.setText(DbUtil.makeTimeString(context, secs));
getAlbumArt(albumid);
}
TextView metaone = (TextView) rowView.findViewById(R.id.album_name);
TextView metatwo = (TextView) rowView.findViewById(R.id.artist_name);
album_art = (ImageView) rowView.findViewById(R.id.album_art);
//TextView metathree = (TextView) rowView.findViewById(R.id.songs_count);
metaone.setText(albumName);
metatwo.setText(artistName);
return rowView;
}
}
String albumArtUri = "";
private void getAlbumArt(long albumid) {
Uri uri=ContentUris.withAppendedId(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, albumid);
System.out.println("hhhhhhhhhhh" + uri);
Cursor cursor = getContentResolver().query(
ContentUris.withAppendedId(
MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, albumid),
new String[] { MediaStore.Audio.AlbumColumns.ALBUM_ART },
null,
null,
null);
if (cursor.moveToFirst()) {
albumArtUri = cursor.getString(0);
}
System.out.println("kkkkkkkkkkkkkkkkkkk :" + albumArtUri);
cursor.close();
if(albumArtUri != null){
Options opts = new Options();
opts.inJustDecodeBounds = true;
Bitmap albumCoverBitmap = BitmapFactory.decodeFile(albumArtUri, opts);
opts.inJustDecodeBounds = false;
albumCoverBitmap = BitmapFactory.decodeFile(albumArtUri, opts);
if(albumCoverBitmap != null)
album_art.setImageBitmap(albumCoverBitmap);
}else {
// TODO:
Options opts = new Options();
Bitmap albumCoverBitmap = BitmapFactory.decodeResource(getApplicationContext().getResources(),
R.drawable.albumart_mp_unknown_list, opts);
if(albumCoverBitmap != null)
album_art.setImageBitmap(albumCoverBitmap);
}
}
}
}