if statement doesn't check the values of the edittexts reached by scrolling the recyclerview - android-recyclerview

i have a recyclerview the has an edittext in each row. the user can change the value of the edittext as he wishes but it should not be left empty for the values will be saved in a database. for this i'm trying to check if the edittext is empty. if any row has an empty edittext, the user is given a message when he wants to save that there is an empty value. this is the code that i wrote:
public class recyclerview_viewholder : RecyclerView.ViewHolder
{
public TextView rownbr, itemname;
public EditText qty;
public TextView unit;
public LinearLayout linearLayout;
public recyclerview_viewholder(View itemView, Action<int> listener)
: base(itemView)
{
rownbr = itemView.FindViewById<TextView>(Resource.Id.rownbr);
itemname = itemView.FindViewById<TextView>(Resource.Id.laborname);
unit = itemView.FindViewById<TextView>(Resource.Id.days);
qty = 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;
DataTable summary_Requests = new DataTable();
//Context context;
public readonly new_request_items context;
int selected_pos = -1;
private SwipeToDeleteCallback swipeToDeleteCallback;
List<list_item> item_details = new List<list_item>();
public recyclerviewAdapter(new_request_items context, DataTable sum_req, List<list_item> item_details)
{
this.context = context;
summary_Requests = sum_req;
this.item_details = item_details;
}
public recyclerviewAdapter(DataTable sum_req, SwipeToDeleteCallback swipeToDeleteCallback)
{
this.swipeToDeleteCallback = swipeToDeleteCallback;
summary_Requests = sum_req;
}
public override RecyclerView.ViewHolder
OnCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.From(parent.Context).
Inflate(Resource.Layout.recycler_view_request_new_data, parent, false);
recyclerview_viewholder vh = new recyclerview_viewholder(itemView, OnClick);
vh.qty.TextChanged += (sender, e) =>
{
if (vh.qty.Text != "")
try
{
int position = vh.LayoutPosition;
summary_Requests.Rows[position]["itemQty"] = Convert.ToDecimal(vh.qty.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.qty.SetError("qty can be decimal", icon);
user.zero_val = "exits";
}
else if (vh.qty.Text == "")
{
var icon = AppCompatResources.GetDrawable(context.Context, Resource.Drawable.error_ic);
icon.SetBounds(0, 0, 50, 50);
vh.qty.SetError("value can not be empty", icon);
user.zero_val = "exits";
}
};
vh.ItemView.LongClick += (sender, e) =>
{
int position = vh.AdapterPosition;
string itemcode = summary_Requests.Rows[position]["itemcode"].ToString();
list_item result = item_details.Find(list_item => list_item.item_code == itemcode);
Bundle bundle = new Bundle();
bundle.PutString("result", JsonConvert.SerializeObject(result));
items_info iteminf = new items_info();
iteminf.Arguments = bundle;
iteminf.Cancelable = true;
var SupportFragmentManager = this.context.FragmentManager;
iteminf.Show(SupportFragmentManager, "dialog");
selected_pos = position;
NotifyDataSetChanged();
//fill global variables that need to be passed to detail fragment
};
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.itemname.Text = summary_Requests.Rows[position]["name"].ToString();
vh.unit.Text = summary_Requests.Rows[position]["itemsunitcode"].ToString();
vh.qty.Text= summary_Requests.Rows[position]["itemQty"].ToString();
if (selected_pos == position)
vh.ItemView.SetBackgroundColor(Color.ParseColor("#4fa5d5"));
else
vh.ItemView.SetBackgroundColor(Color.LightGray);
}
public void RemoveItem(int position)
{
if (laborers_dt_total.Rows.Count != 0)
{
if (position < laborers_dt_total.Rows.Count && position > -1)
{
laborers_dt_total.Rows.RemoveAt(position);
}
else
{
Toast.MakeText(context.Context, "select an item to delete", ToastLength.Long).Show();
}
}
else if (laborers_dt_total.Rows.Count == 0)
{
Toast.MakeText(context.Context, "no items to delete", ToastLength.Long).Show();
}
for (int i = 0; i < laborers_dt_total.Rows.Count; i++)
{
laborers_dt_total.Rows[i]["rowNumber"] = (i + 1).ToString();
NotifyDataSetChanged();
}
}
public DataTable get_dt_final()
{
DataTable final_dt = summary_Requests.Copy();
return final_dt;
}
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;
}
}
now it works well when there are only few rows in the recyclerview, but when there are many in which i have to scroll through it, if i keep an edittext empty in a row reached by scrolling, the user.zero_val doesn't take the value of exits to tell me that an edittext is empty. what should i do in this case? where do i check for empty edittext? thanks in advance.
this is a simple code i wrote with hopes it would illustrate my problem:
this is the axml of the recyclerview:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="match_parent"
android:layout_height="255sp"
android:id="#+id/recyclerView1" />
<Button
android:text="Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/button1" />
</LinearLayout>
this is the layout of each row of the recyclerview:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/light_grey"
android:padding="1dp"
android:layout_marginTop="0.5dp"
android:weightSum="8"
android:gravity="center"
android:id="#+id/linearLayout"
>
<TextView
android:text=""
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="2"
android:id="#+id/rownbr"
android:background="#drawable/back"
android:paddingLeft="1dp"
android:paddingRight="1dp"
android:textSize="12dp"
android:gravity="center"
android:textColor="#000000"
/>
<TextView
android:text=""
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="4"
android:id="#+id/laborname"
android:paddingLeft="1dp"
android:paddingRight="1dp"
android:textSize="12dp"
android:gravity="center"
android:textColor="#000000"
android:background="#drawable/back"
android:layout_marginLeft="2dp"/>
<TextView
android:text=""
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:id="#+id/days"
android:paddingLeft="1dp"
android:paddingRight="1dp"
android:textSize="12dp"
android:textColor="#000000"
android:layout_marginLeft="2dp"
android:gravity="center"
android:background="#drawable/back"/>
<EditText
android:text=""
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:id="#+id/overtime"
android:paddingLeft="1dp"
android:paddingRight="1dp"
android:textSize="12dp"
android:textColor="#000000"
android:layout_marginLeft="2dp"
android:gravity="center"
android:background="#drawable/back"/>
</LinearLayout>
this is the back.xml drawable:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<solid android:color="#android:color/white" />
<stroke android:width="1dip" android:color="#4fa5d5"/>
</shape>
this is the activity where the recyclerview is populated and managed:
public class MainActivity : AppCompatActivity
{
RecyclerView mRecyclerView;
DataTable dt = new DataTable();
RecyclerView.LayoutManager mLayoutManager;
recyclerviewAdapter RecyclerviewAdapter;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
dt.Columns.Add("rowNumber");
dt.Columns.Add("name");
dt.Columns.Add("itemsunitcode");
dt.Columns.Add("itemQty");
dt.Rows.Add("1", "rana hd", "pcs", "1");
dt.Rows.Add("2", "rana hd1", "pcs", "1");
dt.Rows.Add("3", "rana hd2", "pcs", "1");
dt.Rows.Add("4", "rana hd3", "pcs", "1");
dt.Rows.Add("5", "rana hd4", "pcs", "1");
dt.Rows.Add("6", "rana hd5", "pcs", "1");
dt.Rows.Add("7", "rana hd6", "pcs", "1");
dt.Rows.Add("8", "rana hd7", "pcs", "1");
dt.Rows.Add("9", "rana hd8", "pcs", "1");
dt.Rows.Add("10", "rana hd9", "pcs", "1");
mRecyclerView = FindViewById<RecyclerView>(Resource.Id.recyclerView1);
Button btn= FindViewById<Button>(Resource.Id.button1);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.HasFixedSize = true;
mRecyclerView.SetLayoutManager(mLayoutManager);
RecyclerviewAdapter = new recyclerviewAdapter(this, dt);
mRecyclerView.SetAdapter(RecyclerviewAdapter);
btn.Click += delegate
{
if (user.zero_val == "exits")
Toast.MakeText(this, "exists", ToastLength.Long).Show();
if (user.zero_val == "Not_exist")
Toast.MakeText(this, "Not_exist", ToastLength.Long).Show();
};
}
public class recyclerview_viewholder : RecyclerView.ViewHolder
{
public TextView rownbr, itemname;
public EditText qty;
public TextView unit;
public LinearLayout linearLayout;
public recyclerview_viewholder(View itemView, Action<int> listener)
: base(itemView)
{
rownbr = itemView.FindViewById<TextView>(Resource.Id.rownbr);
itemname = itemView.FindViewById<TextView>(Resource.Id.laborname);
unit = itemView.FindViewById<TextView>(Resource.Id.days);
qty = 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;
DataTable summary_Requests = new DataTable();
//Context context;
public readonly MainActivity context;
int selected_pos = -1;
public recyclerviewAdapter(MainActivity context, DataTable sum_req)
{
this.context = context;
summary_Requests = sum_req;
}
public override RecyclerView.ViewHolder
OnCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.From(parent.Context).
Inflate(Resource.Layout.recyclerview_data, parent, false);
recyclerview_viewholder vh = new recyclerview_viewholder(itemView, OnClick);
vh.qty.TextChanged += (sender, e) =>
{
if (vh.qty.Text != "")
try
{
int position = vh.LayoutPosition;
summary_Requests.Rows[position]["itemQty"] = Convert.ToDecimal(vh.qty.Text);
user.zero_val = "Not_exist";
}
catch (System.FormatException exp)
{
var icon = AppCompatResources.GetDrawable(context, Resource.Drawable.error_ic);
icon.SetBounds(0, 0, 50, 50);
vh.qty.SetError("qty can be decimal", icon);
user.zero_val = "exits";
}
else if (vh.qty.Text == "")
{
var icon = AppCompatResources.GetDrawable(context, Resource.Drawable.error_ic);
icon.SetBounds(0, 0, 50, 50);
vh.qty.SetError("value can not be empty", icon);
user.zero_val = "exits";
}
};
vh.ItemView.LongClick += (sender, e) =>
{
int position = vh.AdapterPosition;
selected_pos = position;
NotifyDataSetChanged();
};
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.itemname.Text = summary_Requests.Rows[position]["name"].ToString();
vh.unit.Text = summary_Requests.Rows[position]["itemsunitcode"].ToString();
vh.qty.Text = summary_Requests.Rows[position]["itemQty"].ToString();
if (selected_pos == position)
vh.ItemView.SetBackgroundColor(Color.ParseColor("#4fa5d5"));
else
vh.ItemView.SetBackgroundColor(Color.LightGray);
}
public DataTable get_dt_final()
{
DataTable final_dt = summary_Requests.Copy();
return final_dt;
}
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;
}
}
}
}
this is the user class:
public static class user
{
public static string zero_val = "";
}

If I undstand your meanings correctly, I don't think it's correct to use variable zero_val in class user to indicate whether or not null values exist.For example ,if you have enter a empty value for the first EditText, then the value of zero_val will been changed to Not_exist, then if we enter another empty value for the second EditText, then the value of zero_val will also been changed to Not_exist,after that, if we change the second EditText to a correct value, then the value of zero_val will been changed to exits.But now, actually the first EditText still be empty.
I think you can verify the values the table DataTable when clicking button.
You can refer to the following code:
btn.Click += delegate
{
bool hasEmpty = false ;
foreach (DataRow row in dt.Rows)
{
string itemQty = row["itemQty"].ToString();
string rowNumber = row["rowNumber"].ToString();
System.Diagnostics.Debug.WriteLine("rowNumber =" + rowNumber + "< --- > itemQty = " + itemQty);
if (string.IsNullOrEmpty(itemQty)) {
hasEmpty = true;
}
}
//if (user.zero_val.Equals("exits"))
// Toast.MakeText(this, "exists", ToastLength.Long).Show();
//if (user.zero_val.Equals("Not_exist"))
// Toast.MakeText(this, "Not_exist", ToastLength.Long).Show();
if (!hasEmpty)
Toast.MakeText(this, "exists", ToastLength.Long).Show();
else
Toast.MakeText(this, "Not_exist", ToastLength.Long).Show();
};
In addition, modify the TextChanged function in RecyclerviewAdapter:
vh.qty.TextChanged += (sender, e) =>
{
if (!vh.qty.Text.Equals(""))
try
{
int position = vh.LayoutPosition;
summary_Requests.Rows[position]["itemQty"] = Convert.ToDecimal(vh.qty.Text);
}
catch (System.FormatException exp)
{
var icon = AppCompatResources.GetDrawable(context, Resource.Drawable.error);
icon.SetBounds(0, 0, 50, 50);
vh.qty.SetError("qty can be decimal", icon);
//store a empty value for this textview
int position = vh.LayoutPosition;
summary_Requests.Rows[position]["itemQty"] = "";
}
else if (vh.qty.Text.Equals(""))
{
var icon = AppCompatResources.GetDrawable(context, Resource.Drawable.error);
int position = vh.LayoutPosition;
//store a empty value for this textview
summary_Requests.Rows[position]["itemQty"] = "";
icon.SetBounds(0, 0, 50, 50);
vh.qty.SetError("value can not be empty", icon);
}
};

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 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 :)

JSON response Using Volley in a recycler view in Android app

I am trying to print a json response response in a recyclerview. my Recyclerview is like a expanded listView. And my json resone is like this:
{"Table1":
[
{"filedate":"Oct 26, 2016"},
{"filedate":"Oct 18, 2016"}
],
"Table2":
[{
"filedate":"Oct 18, 2016",
"file1":"12.txt"
},
{
"filedate":"Oct 26, 2016",
"file1":"acerinvoice.pdf"
}
]}
and I trying to print this json resonse using this code:
private void prepareListData() {
// Volley's json array request object
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
//I think problrm is here
#Override
public void onResponse(String response) {
try {
**JSONObject object = new JSONObject(response);
JSONArray jsonarray = object.getJSONArray("Table1");
JSONArray jsonarray1 = object.getJSONArray("Table2");
for (int i = 0; i < jsonarray.length(); i++) {
try {
JSONObject obj = jsonarray.getJSONObject(i);
String str = obj.optString("filedate").trim();
int lth = jsonarray1.length();
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.HEADER, str));
for (int j = 0; j < jsonarray1.length(); j++) {
try {
JSONObject obj1 = jsonarray1.getJSONObject(j);
String str1 = obj1.optString("filedate").trim();
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, str1));
Toast.makeText(getApplicationContext(), str1, Toast.LENGTH_LONG).show();**
//if condition
} catch (JSONException e) {
// Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
// adding movie to movies array
} catch (JSONException e) {
Log.e("gdshfsjkg", "JSON Parsing error: " + e.getMessage());
}
}
Log.d("test", String.valueOf(data));
Toast.makeText(getApplicationContext(), (CharSequence) data, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
recyclerview.setAdapter(new ExpandableListAdapter(data));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(CLIENT, "4");
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(stringRequest);
}
ExpandableListAdapter
public class ExpandableListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int HEADER = 0;
public static final int CHILD = 1;
private List<Item> data;
public ExpandableListAdapter(List<Item> data) {
this.data = data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int type) {
View view = null;
Context context = parent.getContext();
float dp = context.getResources().getDisplayMetrics().density;
int subItemPaddingLeft = (int) (18 * dp);
int subItemPaddingTopAndBottom = (int) (5 * dp);
switch (type) {
case HEADER:
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_header, parent, false);
ListHeaderViewHolder header = new ListHeaderViewHolder(view);
return header;
case CHILD:
TextView itemTextView = new TextView(context);
itemTextView.setPadding(subItemPaddingLeft, subItemPaddingTopAndBottom, 0, subItemPaddingTopAndBottom);
itemTextView.setTextColor(0x88000000);
itemTextView.setLayoutParams(
new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
return new RecyclerView.ViewHolder(itemTextView) {
};
}
return null;
}
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final Item item = data.get(position);
switch (item.type) {
case HEADER:
final ListHeaderViewHolder itemController = (ListHeaderViewHolder) holder;
itemController.refferalItem = item;
itemController.header_title.setText(item.text);
if (item.invisibleChildren == null) {
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_minus);
} else {
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_plus);
}
itemController.btn_expand_toggle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (item.invisibleChildren == null) {
item.invisibleChildren = new ArrayList<Item>();
int count = 0;
int pos = data.indexOf(itemController.refferalItem);
while (data.size() > pos + 1 && data.get(pos + 1).type == CHILD) {
item.invisibleChildren.add(data.remove(pos + 1));
count++;
}
notifyItemRangeRemoved(pos + 1, count);
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_plus);
} else {
int pos = data.indexOf(itemController.refferalItem);
int index = pos + 1;
for (Item i : item.invisibleChildren) {
data.add(index, i);
index++;
}
notifyItemRangeInserted(pos + 1, index - pos - 1);
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_minus);
item.invisibleChildren = null;
}
}
});
break;
case CHILD:
TextView itemTextView = (TextView) holder.itemView;
itemTextView.setText(data.get(position).text);
break;
}
}
#Override
public int getItemViewType(int position) {
return data.get(position).type;
}
#Override
public int getItemCount() {
return data.size();
}
private static class ListHeaderViewHolder extends RecyclerView.ViewHolder {
public TextView header_title;
public ImageView btn_expand_toggle;
public Item refferalItem;
public ListHeaderViewHolder(View itemView) {
super(itemView);
header_title = (TextView) itemView.findViewById(R.id.header_title);
btn_expand_toggle = (ImageView) itemView.findViewById(R.id.btn_expand_toggle);
}
}
public static class Item {
public int type;
public String text;
public List<Item> invisibleChildren;
public Item() {
}
public Item(int type, String text) {
this.type = type;
this.text = text;
}
}
}
But this code print nothing in my recycler UI.It show only a empty layout.I have also tried to print the response in my log and it prints whole response together.I want to print table1 contents in headers and table2 contents in as child(items) with their respective headers.how to do this?If any other information needed please ask..
You should probably check your response first of everything. As per your requirements you should use HashMap and ArrayList. Follow these following steps:
1.Take a ArrayLsit and store child data of 1st heading and so on with index starting from 0.
2.Store headers in HashMap as key.
ex: HashMap<String,ArrayList<Data>> hm;
hm.put("your first heading string","related arraylist");
Then use ExpandableListView to arrange parent and child items.
please check your json response this is invalid json response first try to validate your json formate after try to decode and add in recycler view.
Check Your Response into Logcat also the Exception. I've tested the Response you've supplied that contains some unnecessary "," that may cause the Exception.
I have solve my problem to just change above code like this..
private void prepareListData() {
// Volley's json array request object
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject object = null;
try {
object = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray jsonarray = null;
JSONArray jsonarray1 = null;
try {
jsonarray = object.getJSONArray("Table1");
jsonarray1 = object.getJSONArray("Table1");
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < jsonarray.length(); i++) {
try {
JSONObject obj = jsonarray.getJSONObject(i);
//
String str = obj.optString("filedate").trim();
Log.d("test", str);
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.HEADER, str));
// Toast.makeText(getApplicationContext(), lth, Toast.LENGTH_LONG).show();
for (int j = 0; j < jsonarray1.length(); j++) {
try {
JSONObject obj1 = jsonarray1.getJSONObject(j);
String str1 = obj1.optString("filedate").trim();
String str3 = obj1.optString("category").trim();
String str2 = obj1.optString("file1").trim();
String str4 = obj1.optString("4").trim();
Toast.makeText(getApplicationContext(), "server data respone", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "test"+str1, Toast.LENGTH_LONG).show();
if (str == str1) {
// data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, str1));
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, str3));
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, str2));
}
Toast.makeText(getApplicationContext(), str1, Toast.LENGTH_LONG).show();
//if condition
} catch (JSONException e) {
// Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
// adding movie to movies array
} catch (JSONException e) {
Log.e("gdshfsjkg", "JSON Parsing error: " + e.getMessage());
}
}
Log.d("test", String.valueOf(data));
// notifying list adapter about data changes
// so that it renders the list view with updated data
// adapterheader.notifyDataSetChanged();
recyclerview.setAdapter(new ExpandableListAdapter(data));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// VolleyLog.d(TAG, "Error: " + error.getMessage());
// hidePDialog();
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(CLIENT, "4");
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(stringRequest);
}

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

Animation of textview in android

i want to animate textview in such a way that collide with display horizontally and vertically mean while that change random color of text and that runs infinte.is there any way??
i tried like
Animation a = AnimationUtils.loadAnimation(this, R.anim.anim);
a.setFillAfter(true);
a.reset();
tv.startAnimation(a);
i got solution....
MY Solution
textview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/layout">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Helo suni" />
</LinearLayout>
just call repeat function in on create ..
private void repeat() {
// TODO Auto-generated method stub
if (curAnimation == 1) {
animation1 = new TranslateAnimation(width / 2, width, 0, height / 2);
animation1.setDuration(800);
} else if (curAnimation == 2) {
animation1 = new TranslateAnimation(width, width / 2, height / 2, height);
animation1.setDuration(800);
}
else if (curAnimation == 3) {
animation1 = new TranslateAnimation(width / 2, 0, height, height / 2);
animation1.setDuration(800);
}
else if (curAnimation == 4) {
animation1 = new TranslateAnimation(0,width/2,height/2,0);
animation1.setDuration(800);
}
animation1.setFillAfter(true);
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256),
rnd.nextInt(256));
tv.setTextColor(color);
tv.startAnimation(animation1);
animation1.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub
if (curAnimation == 4)
curAnimation = 1;
else
curAnimation++;
repeat();
}
});
}