ExpandableListView: Get input values from childs - java

I'm parsing a JSON into a ExpandableListView, on each child the user can select the amount of each child he wants to have due +/- Buttons. The +/- Buttons are connected to a TextView where the total amount of each child gets displayed and the total cost will be displayed at the end of the line.
At the Bottom of the parent there should be a TextView with the summary of all the values calculated in every child of the ExpListView (Summary)
And the OK Button at the Bottom should send the amount of each child to the server (the amount is connected to a ID).
I'm having problems with reading out the amount of each child when I'm clicking on the "OK" Button - how can I build the bridge to the values of my Childs?
I also encounter problems reading out the cost of each childto calculate the total cost at the bottom. The onClickListener in the Child should somehow refresh the TextView at the bottom, but as far as I know, that's not going to be easy, right?
Has anyone an idea how to access the values?
This is the ChildView of my ListAdapter where the magic happens:
public class ExpandableListAdapterDrinks extends BaseExpandableListAdapter {
private Context context;
private List<String> listDataHeader,listDataHeaderPrice;
private HashMap<String,List<String>> listHashMap;
private List<Drink> drinksList;
class ViewHolder {
TextView childText,counterText, childUnitPrice, childFinalPrice;
Button btn_plus,btn_minus;
}
class DrinksListChildItem{
String name;
int quantity;
DrinksListChildItem(String name, int quantity){
this.name = name;
this.quantity = quantity;
}
}
class Pos{
int group;
int child;
Pos(int group, int child){
this.group = group;
this.child = child;
}
}
public ExpandableListAdapterDrinks(Context context, List<Drink> drinksList) {
this.context = context;
this.drinksList= drinksList;
}
#Override
public int getGroupCount() {
return drinksList.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return drinksList.get(groupPosition).getContent().size();
}
#Override
public Object getGroup(int groupPosition) {
return drinksList.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return drinksList.get(groupPosition).getContent();
listHashMap.get(listDataHeader.get(groupPosition)).get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(final int groupPosition, boolean isExpanded, View view, ViewGroup parent) {
String headerTitle = (String) drinksList.get(groupPosition).getTitle();
/** HEADER TEXT HERE */
if(view==null) {
LayoutInflater inflater = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.vip_package_listgroup,null);
}
final LinearLayout bgcolor = view.findViewById(R.id.lblListHeaderLayout);
TextView lblListHeader = (TextView)view.findViewById(R.id.lblListHeader);
TextView lblListHeaderPrice = (TextView)view.findViewById(R.id.lblListHeader_Price);
Button lblListHeaderButton = view.findViewById(R.id.lblListHeaderButton);
lblListHeaderPrice.setVisibility(View.GONE);
lblListHeaderButton.setVisibility(View.GONE);
if(!drinksList.get(groupPosition).getBg().get(0).isEmpty() || !drinksList.get(groupPosition).getBg().get(1).isEmpty() ) {
List<String> colorGradientTopBottom = drinksList.get(groupPosition).getBg();
int[] colors = {Color.parseColor(colorGradientTopBottom.get(0)),Color.parseColor(colorGradientTopBottom.get(1))};
GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors);
gd.setCornerRadius(0f);
bgcolor.setBackground(gd);
} else {
bgcolor.setBackgroundColor(ContextCompat.getColor(context, R.color.cardview_bg));
}
lblListHeader.setText(headerTitle);
return view;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View view, ViewGroup parent) {
/** Drinks List */
final ViewHolder viewHolder;
final List<String> childDrink = drinksList.get(groupPosition).getContent();
final List<Integer> childPrice = drinksList.get(groupPosition).getPricelist();
//final String childText = childDrink.get(childPosition);
if(view == null) {
LayoutInflater inflater = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.vip_drinks_listitem,null);
final TextView txtListChild = view.findViewById(R.id.lblListItemDrinks);
final TextView txtListDrinksUnitPrice = view.findViewById(R.id.lblListItemDrinksUnitPrice);
final TextView txtDrinksAmount = view.findViewById(R.id.vip_drinks_amount);
final TextView txtListDrinkPriceFinal = view.findViewById(R.id.lblListItemDrinksFinalPrice);
Button btn_plus = view.findViewById(R.id.vip_drinks_btn_plus);
Button btn_minus = view.findViewById(R.id.vip_drinks_btn_minus);
viewHolder = new ViewHolder();
viewHolder.childText = txtListChild;
viewHolder.childUnitPrice = txtListDrinksUnitPrice;
viewHolder.counterText = txtDrinksAmount;
viewHolder.childFinalPrice = txtListDrinkPriceFinal;
viewHolder.btn_plus = btn_plus;
viewHolder.btn_minus = btn_minus;
viewHolder.childText.setText(childDrink.get(childPosition));
viewHolder.counterText.setText("0");
viewHolder.childFinalPrice.setText("0");
final float headerPrice = childPrice.get(childPosition);
final int headerPriceInt = (int) headerPrice;
viewHolder.childUnitPrice.setText(String.format("%.02f",headerPrice).replace(".",",") +"€");
DrinksListChildItem child = childDrink.get(childPosition);
viewHolder.btn_plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int t = Integer.parseInt(viewHolder.counterText.getText().toString());
ChildItem selectedItem = viewHolder.counterText.getText().toString();
selectedItem.quantity = selectedItem.quantity+1;
notifyDataSetChanged();
viewHolder.counterText.setText(String.valueOf(t + 1));
viewHolder.childFinalPrice.setText(String.valueOf((t+1)* headerPriceInt) + "€");
}
});
viewHolder.btn_minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Pos pos = (Pos) v.getTag();
int t = Integer.parseInt(viewHolder.counterText.getText().toString());
DrinksListChildItem selectedItem = (DrinksListChildItem) getChild(pos.group,pos.child);
selectedItem.quantity = selectedItem.quantity-1;
notifyDataSetChanged();
viewHolder.counterText.setText(String.valueOf(t - 1));
viewHolder.counterText.setText(String.valueOf((t-1)* headerPriceInt) + "€");
}
});
} else {
viewHolder = (ViewHolder) view.getTag();
}
return view;
I'm having massive problems glueing your code to my Code (expand problem with a TextView): I don't understand exactly how to connect the ChildItem child = childDrink.get(childPosition); to my drinksList to make the setOnCLickListener increase the selectedItem.quantity. The Code works somehow, but it messes up the order of my childs and it also selects the quantity in the other childs
Drinks (Pojo)
public class Drink {
#SerializedName("title")
#Expose
private String title;
#SerializedName("bg")
#Expose
private List<String> bg = null;
#SerializedName("content")
#Expose
private List<String> content = null;
#SerializedName("pricelist")
#Expose
private List<Integer> pricelist = null;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<String> getBg() {
return bg;
}
public void setBg(List<String> bg) {
this.bg = bg;
}
public List<String> getContent() {
return content;
}
public void setContent(List<String> content) {
this.content = content;
}
public List<Integer> getPricelist() {
return pricelist;
}
public void setPricelist(List<Integer> pricelist) {
this.pricelist = pricelist;
}
}
VipDrinks(Pojo):
public class VipDrinks {
#SerializedName("drinks")
#Expose
private List<Drink> drinks = null;
public List<Drink> getDrinks() {
return drinks;
}
public void setDrinks(List<Drink> drinks) {
this.drinks = drinks;
}
}
JSON has the following structure:
{
"drinks":[ {
"title":,
"bg":[],
"content":[],
"pricelist":[],
},
{...}
]
}
Here is the Activity with the Parsing Request:
public class drinks_selection extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drinks_selection);
final ExpandableListView listView = findViewById(R.id.vip_drinks_listview);
/** PARSING JSON FROM SERVER */
final JsonObjectRequest galleryUrls = new JsonObjectRequest(Request.Method.GET, PARSE_URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray packageArray = response.getJSONArray("drinks");
Log.e("response", String.valueOf(response));
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
List<Drink> vipDrinks = Arrays.asList(gson.fromJson(String.valueOf(packageArray),Drink[].class));
List<Drink> arrayList = new ArrayList<>(vipDrinks);
ExpandableListAdapterDrinks listAdapter = new ExpandableListAdapterDrinks(getApplicationContext(),arrayList);
listView.setAdapter( listAdapter);
listView.expandGroup(0);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ERROR", String.valueOf(error));
}
});
RequestQueue rQ = Volley.newRequestQueue(this);
rQ.add(galleryUrls);
}
}
VIP Package List Group.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="#+id/lblListHeaderLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="#dimen/default_padding"
android:background="#drawable/bg_vip_booking"
android:orientation="horizontal"
>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:paddingStart="?android:attr/expandableListPreferredItemPaddingLeft"
android:paddingEnd="#dimen/feed_item_padding_left_right"
android:layout_weight="0.9"
>
<TextView
android:id="#+id/lblListHeader"
android:textSize="#dimen/text_title_list_header"
android:textColor="#color/Textwhite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/mont_bold"
/>
<TextView
android:id="#+id/lblListHeader_Price"
android:textSize="#dimen/text_title_list_header"
android:textColor="#color/Textwhite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:fontFamily="#font/mont_bold"
/>
</RelativeLayout>
<Button
android:id="#+id/lblListHeaderButton"
android:layout_width="60dp"
android:layout_height="30dp"
android:background="#drawable/bg_btn_ripple_dark"
android:text="#string/btn_ok"
android:textColor="#color/Textwhite"
android:fontFamily="#font/mont_bold"
android:focusable="false"
/>
</LinearLayout>
VIP Drinks ListItem.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dip"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_centerInParent="true"
>
<TextView
android:id="#+id/lblListItemDrinks"
android:paddingTop="#dimen/padding_small"
android:paddingBottom="#dimen/padding_small"
android:textSize="#dimen/text_normal"
android:paddingLeft="#dimen/default_padding"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:fontFamily="#font/mont_medium"
android:textColor="#color/Textwhite"
app:layout_constraintStart_toStartOf="parent"
/>
<RelativeLayout
android:id="#+id/vip_drinks_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#id/lblListItemDrinks"
android:paddingStart="#dimen/default_padding"
android:layout_centerInParent="true"
android:paddingEnd="#dimen/default_padding"
app:layout_constraintEnd_toEndOf="parent"
>
<TextView
android:id="#+id/lblListItemDrinksUnitPrice"
android:textSize="#dimen/text_normal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/mont_light"
android:textColor="#color/Textwhite"
android:paddingEnd="#dimen/padding_small"
/>
<Button
android:id="#+id/vip_drinks_btn_minus"
android:layout_toEndOf="#id/lblListItemDrinksUnitPrice"
android:layout_width="30dp"
android:layout_height="20dp"
android:text="-"
android:background="#drawable/bg_btn_ripple_dark"
android:textColor="#color/white"
android:textSize="14sp"
android:layout_marginEnd="#dimen/padding_small"
/>
<TextView
android:id="#+id/vip_drinks_amount"
android:layout_toEndOf="#+id/vip_drinks_btn_minus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/white"
android:fontFamily="#font/mont_light"
android:textSize="#dimen/text_normal"
android:layout_marginEnd="#dimen/padding_small"
/>
<Button
android:id="#+id/vip_drinks_btn_plus"
android:layout_toEndOf="#+id/vip_drinks_amount"
android:layout_width="30dp"
android:layout_height="20dp"
android:text="+"
android:background="#drawable/bg_btn_ripple_dark"
android:textColor="#color/white"
android:textSize="14sp"
android:layout_marginEnd="#dimen/padding_small"
/>
<TextView
android:id="#+id/lblListItemDrinksFinalPrice"
android:layout_toEndOf="#id/vip_drinks_btn_plus"
android:textSize="#dimen/text_normal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/mont_light"
android:textColor="#color/Textwhite"
/>
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

Add a new class SelectedDrink like this:
public class SelectedDrink {
String content;
int qty;
}
Then try this adapter code:
public class ExpandableListAdapterDrinks extends BaseExpandableListAdapter {
private Context context;
private List<Drink> drinksList;
private Button btReset, btOk;
private List<Integer> groupSum;
private List<List<Integer>> qty;
private int totalSum = 0;
class ViewHolder {
TextView childText,counterText, childUnitPrice, childFinalPrice;
Button btn_plus,btn_minus;
}
class Pos{
int group;
int child;
Pos(int group, int child){
this.group = group;
this.child = child;
}
}
public ExpandableListAdapterDrinks(Context context, List<Drink> drinksList,
Button btReset, Button btOk) {
this.context = context;
this.drinksList= drinksList;
this.btReset = btReset;
this.btOk = btOk;
groupSum = new ArrayList<>();
qty = new ArrayList<>();
for(int i=0; i<drinksList.size(); i++) {
groupSum.add(0);
List<Integer> orderedQty = new ArrayList<>();
for(int j=0; j<drinksList.get(i).getContent().size(); j++) orderedQty.add(0);
qty.add(orderedQty);
}
}
private void resetGroupSum(int groupPosition) {
totalSum -= groupSum.get(groupPosition);
groupSum.set(groupPosition, 0);
resetGroupChildrenQty(groupPosition);
}
private void resetGroupChildrenQty(int groupPosition) {
for(int i=0; i<qty.get(groupPosition).size(); i++) qty.get(groupPosition).set(i, 0);
}
#Override
public int getGroupCount() {
return drinksList.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return drinksList.get(groupPosition).getContent().size();
}
#Override
public Drink getGroup(int groupPosition) {
return drinksList.get(groupPosition);
}
#Override
public String getChild(int groupPosition, int childPosition) {
return drinksList.get(groupPosition).getContent().get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View view, ViewGroup parent) {
String headerTitle = drinksList.get(groupPosition).getTitle();
/** HEADER TEXT HERE */
if(view==null) {
LayoutInflater inflater = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.vip_package_listgroup,null);
}
LinearLayout bgcolor = view.findViewById(R.id.lblListHeaderLayout);
TextView lblListHeader = (TextView)view.findViewById(R.id.lblListHeader);
TextView lblListHeaderPrice = (TextView)view.findViewById(R.id.lblListHeader_Price);
Button lblListHeaderButton = view.findViewById(R.id.lblListHeaderButton);
if(groupSum.get(groupPosition) > 0){
lblListHeaderPrice.setVisibility(View.VISIBLE);
lblListHeaderPrice.setText(String.format("%.02f", (float)groupSum.get(groupPosition)).replace(".", ",") + "€");
}else{
lblListHeaderPrice.setVisibility(View.GONE);
lblListHeaderButton.setVisibility(View.GONE);
}
if(!drinksList.get(groupPosition).getBg().get(0).isEmpty() || !drinksList.get(groupPosition).getBg().get(1).isEmpty() ) {
List<String> colorGradientTopBottom = drinksList.get(groupPosition).getBg();
int[] colors = {Color.parseColor(colorGradientTopBottom.get(0)),Color.parseColor(colorGradientTopBottom.get(1))};
GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors);
gd.setCornerRadius(0f);
bgcolor.setBackground(gd);
} else {
//bgcolor.setBackgroundColor(ContextCompat.getColor(context, R.color.cardview_bg));
}
lblListHeader.setText(headerTitle);
return view;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View view, ViewGroup parent) {
/** Drinks List */
ViewHolder viewHolder;
String childDrink = getChild(groupPosition, childPosition);
int childPrice = getGroup(groupPosition).getPricelist().get(childPosition);
if (view == null) {
LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.vip_drinks_listitem, null);
viewHolder = new ViewHolder();
viewHolder.childText = view.findViewById(R.id.lblListItemDrinks);
viewHolder.childUnitPrice = view.findViewById(R.id.lblListItemDrinksUnitPrice);
viewHolder.counterText = view.findViewById(R.id.vip_drinks_amount);
viewHolder.childFinalPrice = view.findViewById(R.id.lblListItemDrinksFinalPrice);
viewHolder.btn_plus = view.findViewById(R.id.vip_drinks_btn_plus);
viewHolder.btn_minus = view.findViewById(R.id.vip_drinks_btn_minus);
viewHolder.btn_plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Pos pos = (Pos) v.getTag();
int orderedQty = qty.get(pos.group).get(pos.child);
orderedQty++;
qty.get((pos.group)).set(pos.child, orderedQty);
groupSum.set(pos.group, groupSum.get(pos.group) + getGroup(pos.group).getPricelist().get(pos.child));
notifyDataSetChanged();
totalSum += getGroup(pos.group).getPricelist().get(pos.child);
btOk.setText(String.format("%.02f", (float)totalSum).replace(".", ",") + "€");
btReset.setEnabled(true);
}
});
viewHolder.btn_minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Pos pos = (Pos) v.getTag();
int orderedQty = qty.get(pos.group).get(pos.child);
if (orderedQty > 0) {
orderedQty--;
qty.get((pos.group)).set(pos.child, orderedQty);
groupSum.set(pos.group, groupSum.get(pos.group) - getGroup(pos.group).getPricelist().get(pos.child));
notifyDataSetChanged();
totalSum -= getGroup(pos.group).getPricelist().get(pos.child);
if (totalSum == 0) resetTotalSum();
else btOk.setText(String.format("%.02f", (float)totalSum).replace(".", ",") + "€");
}
}
});
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.childText.setText(childDrink);
viewHolder.childUnitPrice.setText(String.format("%.02f", (float)childPrice).replace(".", ",") + "€");
int orderedQty = qty.get(groupPosition).get(childPosition);
viewHolder.counterText.setText(String.valueOf(orderedQty));
viewHolder.childFinalPrice.setText(String.format("%.02f", (float)orderedQty*childPrice).replace(".", ",") + "€");
viewHolder.btn_minus.setTag(new Pos(groupPosition, childPosition));
viewHolder.btn_plus.setTag(new Pos(groupPosition, childPosition));
view.setTag(viewHolder);
return view;
}
#Override
public boolean isChildSelectable(int i, int i1) {
return false;
}
public void resetTotalSum() {
for(int i=0; i<drinksList.size(); i++) {
resetGroupSum(i);
}
notifyDataSetChanged();
btReset.setEnabled(false);
btOk.setText(String.valueOf(0));
}
public ArrayList<SelectedDrink> getOrderList() {
ArrayList<SelectedDrink> orderList = new ArrayList<>();
for(int i=0; i<drinksList.size(); i++) {
for(int j=0; j<drinksList.get(i).getContent().size(); j++) {
if(qty.get(i).get(j) > 0) {
SelectedDrink selectedDrink = new SelectedDrink();
selectedDrink.content = getGroup(i).getContent().get(j);
selectedDrink.qty = qty.get(i).get(j);
orderList.add(selectedDrink);
}
}
}
return orderList;
}
}
I test the above with this activity:
public class MainActivity extends AppCompatActivity {
final private static int NUM_OF_GROUP = 5;
List<Drink> drinksList;
ExpandableListView listView;
ExpandableListAdapterDrinks expandableListAdapterDrinks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btRest = findViewById(R.id.btReset);
Button btOk = findViewById(R.id.btOK);
listView = findViewById(R.id.elvDrinks);
initDataList();
expandableListAdapterDrinks =
new ExpandableListAdapterDrinks(getApplicationContext(), drinksList, btRest, btOk);
listView.setAdapter(expandableListAdapterDrinks);
listView.expandGroup(0);
btRest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
expandableListAdapterDrinks.resetTotalSum();
for(int i=0; i<drinksList.size(); i++) listView.collapseGroup(i);
listView.expandGroup(0);
}
});
btOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String msg = "Nothing Selected";
Button button = (Button)view;
if(!button.getText().equals("0")) {
msg = "Upload!\n";
ArrayList<SelectedDrink> selectedDrinks = expandableListAdapterDrinks.getOrderList();
for(SelectedDrink selectedDrink: selectedDrinks) {
msg += selectedDrink.content + " " + selectedDrink.qty + "\n";
}
msg += "Total: " + button.getText();
}
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
}
private void initDataList(){
drinksList = new ArrayList<>();
List<String> content;
List<Integer> pricelist;
List<String> bg;
for(int i=1; i<=NUM_OF_GROUP; i++) {
content = new ArrayList<>();
pricelist = new ArrayList<>();
bg = new ArrayList<>();
for(int j = 1; j<(NUM_OF_GROUP + new Random().nextInt(5)); j++){
content.add("Drink " + i + "-" + j);
pricelist.add(new Random().nextInt(1000));
bg.add("#008577");
bg.add("#D81B60");
}
Drink drink = new Drink();
drink.setTitle("Group " + i);
drink.setContent(content);
drink.setPricelist(pricelist);
drink.setBg(bg);
drinksList.add(drink);
}
}
}
and this layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/llBtns"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<Button
android:id="#+id/btReset"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:enabled="false"
android:text="Reset" />
<Button
android:id="#+id/btOK"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="0" />
</LinearLayout>
<ExpandableListView
android:id="#+id/elvDrinks"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/llBtns">
</ExpandableListView>
</RelativeLayout>
Also, your Drink class, vip_package_listgroup.xml and vip_drinks_listitem.xml are also needed. Hope that helps!

Related

How can I delete the data I clicked in String[] Android

I am getting data in String[] from another class with intent. I show the data I received in listview. When I click the deleteshop button on the custom adapter, I want the data I clicked to be deleted from the String array. How can I do that?
My code;
final ListView list = findViewById(R.id.list);
final ArrayList<SubjectData> arrayList = new ArrayList<SubjectData>();
final String[] cartList = getIntent().getStringArrayExtra("saleData");
arrayList.add(new SubjectData("", ""));
final int cartListLength = cartList.length;
int counter = 0;
String lastItem = "";
for (String e : cartList) {
counter += 1;
if (e == "" || e == null) {
lastItem = cartList[counter-3];
break;
}
String productPhoto = "";
switch (e) {
case "1 PC GREEN COLA x 10.00 TL":
productPhoto = "cc";
break;
default:
productPhoto = "";
break; }
arrayList.add(new SubjectData(e, productPhoto));;
}
arrayList.remove(arrayList.size()-1);
arrayList.remove(arrayList.size()-1);
final CustomAdapter customAdapter = new CustomAdapter(this, arrayList);
list.setAdapter(customAdapter);
nextButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
final int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
nextButton.setImageResource(R.drawable.next_down);
break;
case MotionEvent.ACTION_UP:
nextButton.setImageResource(R.drawable.next_up);
Intent myIntent = new Intent(getApplicationContext(), PrinterManagerActivity.class);
myIntent.putExtra("saleData", cartList);
startActivityForResult(myIntent, 0);
//
break;
}
return true;
}
});
SubjectData model class:
String SubjectName;
String Image;
public SubjectData(String subjectName, String image) {
this.SubjectName = subjectName;
this.Image = image;
}
Customadapter;
class CustomAdapter implements ListAdapter {
ArrayList<SubjectData> arrayList;
Context context;
public CustomAdapter(Context context, ArrayList<SubjectData> arrayList) {
this.arrayList=arrayList;
this.context=context;
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
return true;
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final SubjectData subjectData=arrayList.get(position);
if(convertView==null){
LayoutInflater layoutInflater = LayoutInflater.from(context);
convertView=layoutInflater.inflate(R.layout.list_row, null);
TextView tittle=convertView.findViewById(R.id.title);
ImageView imag=convertView.findViewById(R.id.list_image);
ImageView
deleteshop=convertView.findViewById(R.id.deleteshop);
deleteshop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (context instanceof SaleSummary) {
((SaleSummary)context).deleteItem(position);
int selectedFromList = (int) list.getItemAtPosition(position);
String gettextdata = tittle.getText().toString();
Toast.makeText(context, gettextdata""+"the product has been deleted
", Toast.LENGTH_LONG).show();
}
}
});
tittle.setText(subjectData.SubjectName);
Resources resources = context.getResources();
final int resourceId = resources.getIdentifier(subjectData.Image, "drawable",
context.getPackageName());
imag.setImageResource(resourceId);
}
return convertView;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return arrayList.size();
}
#Override
public boolean isEmpty() {
return false;
}
listview design;
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dip">
<LinearLayout
android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip"
android:padding="3dip">
<ImageView
android:id="#+id/list_image"
android:layout_width="50dip"
android:layout_height="50dip" />
</LinearLayout>
<TextView
android:id="#+id/title"
android:layout_width="250dp"
android:layout_height="match_parent"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:gravity="center"
android:textColor="#040404"
android:textSize="15dip"
android:textStyle="bold"
android:typeface="sans" />
<ImageView
android:layout_gravity="center"
android:id="#+id/deleteshop"
android:src="#drawable/negative"
android:layout_width="25dp"
android:layout_height="25dp" ></ImageView>
</LinearLayout>
This is basically removing data from an Array which is normal programming / data structure task.
You can run a for loop on cartList and when you encounter the item you wish to delete you can simply overwrite that item with next item until you get to end of list then you mark the last item as null.
for(int i ==0; i < cartList.length(); i++){
if(cartList[i] == selectedItem){
for(int j = i j < cartList.length(); j++){
cartList[j] == cartList[j++];
}
// mark last item as null
cartList[cartList.length()-1] = null;
break;
}
}
All you need now is a listener between your activity and adapter that will trigger the logic whenever user clicks on delete item on any item.

how to callback from fragment to activity With bottom sheet

Hey I'm doing filtering data on my project using bottom Sheet with view-pager and two fragments i can pass data from activity to view-pager adapter and get in fragment through constructor but how can i get data from fragment to activity using bottom-sheet
this is how i send data from activity
adapter = new PagerAdapters(this.getSupportFragmentManager(),
tabLayout.getTabCount(),_id);
and receive data with constructor in fragment
public Filterfragment(String _id) {
this._id = _id;
}
And I'm using recyclerview to show data like this
So how can i send id of the item to activity so i can reload my recyclerview data when the apply button click.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/bottom_sheet"
android:background="#android:color/white"
app:behavior_peekHeight="0dp"
app:layout_behavior="android.support.design.widget.BottomSheetBehavior"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:tabGravity="fill"
app:tabMode="fixed"
app:tabPadding="0dp"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_below="#id/tabs"
android:layout_above="#id/applyBtn"
android:layout_height="match_parent"
/>
<Button
android:id="#+id/applyBtn"
android:layout_width="match_parent"
android:text="Apply"
android:layout_alignParentBottom="true"
android:layout_height="wrap_content" />
</RelativeLayout>
This is main recyclerview adapter
public class FilterAdapter extends RecyclerView.Adapter<FilterAdapter.FilterViewHolder> {
private static final String TAG = "FilterAdapter";
Context context;
List<TagTypeResult> tagTypeModels;
public static int current_pos = -1;
TagAdapter tagAdapter;
int rotationAngle = 0;
public FilterAdapter(Context context, List<TagTypeResult> tagTypeModels) {
this.context = context;
this.tagTypeModels = tagTypeModels;
}
#NonNull
#Override
public FilterViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.filter_row_item,parent,false);
return new FilterAdapter.FilterViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull FilterViewHolder filterViewHolder, int i) {
TagTypeResult tagTypeModel = tagTypeModels.get(i);
filterViewHolder.txt.setText(tagTypeModel.getName());
filterViewHolder.sub_list_recycler.setVisibility(View.GONE);
if (tagTypeModel.getTagsLists() != null) {
if (tagTypeModel.getTagsLists().size() <= 0) {
filterViewHolder.arrow.setVisibility(View.GONE);
filterViewHolder.arrow.setRotationX(180);
} else {
filterViewHolder.arrow.setVisibility(View.VISIBLE);
filterViewHolder.arrow.setRotationX(0);
}
}else {
filterViewHolder.arrow.setVisibility(View.GONE);
}
tagAdapter = new TagAdapter(context, tagTypeModel.getTagsLists(), new TagInterface() {
#Override
public void tagClick(View view, int pos, String tagID) {
Log.d(TAG, "tagClick: "+tagID);
}
});
filterViewHolder.sub_list_recycler.setAdapter(tagAdapter);
tagAdapter.notifyDataSetChanged();
if (current_pos == filterViewHolder.getAdapterPosition()){
if (filterViewHolder.sub_list_recycler.getVisibility() == View.GONE) {
filterViewHolder.sub_list_recycler.setVisibility(View.VISIBLE);
}else {
filterViewHolder.sub_list_recycler.setVisibility(View.GONE);
}
}else {
Log.i(TAG, "onBindViewHolder: sublist gone "+tagTypeModel.getName());
filterViewHolder.sub_list_recycler.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
return tagTypeModels.size();
}
class FilterViewHolder extends RecyclerView.ViewHolder {
TextView txt;
ImageView arrow;
RecyclerView sub_list_recycler;
RelativeLayout linearLayout;
FilterViewHolder(#NonNull View itemView) {
super(itemView);
txt = itemView.findViewById(R.id.txt);
arrow = itemView.findViewById(R.id.arrow);
linearLayout = itemView.findViewById(R.id.main_cat_lay);
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG, "onClick: "+current_pos);
if (current_pos != getAdapterPosition()) {
current_pos = getAdapterPosition();
notifyDataSetChanged();
}
else{
current_pos = -1;
notifyDataSetChanged();
}
}
});
sub_list_recycler = itemView.findViewById(R.id.sub_list_recycler);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(context) {
#Override
public boolean canScrollVertically() {
return false;
}
};
sub_list_recycler.setLayoutManager(mLayoutManager);
sub_list_recycler.addItemDecoration(new SimpleDividerItemDecoration(context));
}
}
}
sub recyclerView adapter :
public class TagAdapter extends RecyclerView.Adapter<TagAdapter.TagViewHolder> {
private static final String TAG = "SublistAdapter";
Context context;
List<TagsList> tagsLists;
int pos = -1;
TagInterface tagInterface;
public TagAdapter(Context context, List<TagsList> tagsLists,TagInterface tagInterface) {
this.context = context;
this.tagsLists = tagsLists;
this.tagInterface = tagInterface;
}
#NonNull
#Override
public TagViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.tag_item,parent,false);
return new TagAdapter.TagViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull TagViewHolder tagViewHolder, int i) {
TagsList tagsList = tagsLists.get(i);
tagViewHolder.tagtxt.setText(tagsList.getName());
if (tagsList.isChecked()){
tagViewHolder.tagName.setChecked(true);
}else {
tagViewHolder.tagName.setChecked(false);
}
}
#Override
public int getItemCount() {
return tagsLists.size();
}
public class TagViewHolder extends RecyclerView.ViewHolder {
TextView tagtxt;
CheckBox tagName;
RelativeLayout childClik;
public TagViewHolder(#NonNull View itemView) {
super(itemView);
//pri_txt = itemView.findViewById(R.id.pri_txt);
tagName = itemView.findViewById(R.id.tagName);
tagtxt = itemView.findViewById(R.id.tagtxt);
childClik = itemView.findViewById(R.id.childClik);
tagName.setEnabled(false);
childClik.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isChecked = true;
if (isChecked)
{
tagsLists.get(getAdapterPosition()).setChecked(true);
tagName.setChecked(true);
tagInterface.tagClick(v,getAdapterPosition(),tagsLists.get(getAdapterPosition()).get_id());
Toast.makeText(context, "[pos]"+tagsLists.get(getAdapterPosition()).get_id(), Toast.LENGTH_SHORT).show();
}else
{
tagsLists.get(getAdapterPosition()).setChecked(false);
tagName.setChecked(false);
}
}
});
}
}
}

Need to create headers within Recyclerview

I create app for sports site and need to make calendar events. There is a detail which I can't understand: how to make headers within Recyclerview for display of tournaments name that not to specified near each game (example "Примера" on the screen).
Is there a library or anyways for my task? I don’t want create many static Recyclerview and find agile ways.
Of course, there are a lot of tournaments in the calendar, so the headers should be the same.
Main class of the calendar:
public class FootballResults extends Fragment implements
View.OnClickListener, DatePickerDialog.OnDateSetListener{
private LinearLayoutManager linLM;
private FootballResultsAdapter adapter;
private ArrayList<FootballResultsData> dl;
String today_day;
String today_month;
String today_year;
String mDay;
String mMonth;
String mYear;
Button arrow_left;
Button arrow_right;
Button datepicker;
Switch swLive;
int n = 0;
//int n_plus = 1;
#SuppressLint("SetTextI18n")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rv = inflater.inflate(R.layout.results_football, container, false);
RecyclerView footballresults_feed1 = (RecyclerView) rv.findViewById(R.id.rcMatch1);
dl = new ArrayList<>();
footballresults_feed1.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new FootballResultsAdapter(getActivity(), dl);
footballresults_feed1.setAdapter(adapter);
arrow_left = (Button)rv.findViewById(R.id.arrow_left);
arrow_right = (Button)rv.findViewById(R.id.arrow_right);
datepicker = (Button)rv.findViewById(R.id.btnDatepick);
swLive = (Switch)rv.findViewById(R.id.swLive);
arrow_left.setOnClickListener(this);
arrow_right.setOnClickListener(this);
datepicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
datepickermethod ();
}
});
swLive.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {swLive.setText("");}
else {swLive.setText("");}
}
});
currenttime();
datepicker.setText(Integer.parseInt(mDay)+" "+TimeFormat.monthDef(Integer.parseInt(mMonth))+" "+mYear);
ResultDisplay();
return rv;
}
private void ResultDisplay() {
#SuppressLint("StaticFieldLeak") AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
#Override
protected Void doInBackground(Integer... integers) {
ResultFeed ();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
adapter.notifyDataSetChanged();
}
};
task.execute();
}
void ResultFeed (){
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url(C.RESULT_API+mYear+"/"+mMonth+"/"+mDay+"?sport_id=1")
.build();
try {
okhttp3.Response response = client.newCall(request).execute();
JSONObject object = new JSONObject(response.body().string());
dl.clear();
JSONArray sports = object.getJSONArray("sports");
JSONObject tournament0 = sports.getJSONObject(0);
JSONArray tournament = tournament0.getJSONArray("tournaments");
for (int i=0; i<tournament.length(); i++){
JSONObject matches1 = tournament.getJSONObject(i);
Log.i (C.T, "Турнир: "+matches1.getString("tournament_name"));
JSONArray matches0 = matches1.getJSONArray("matches");
for (int j=0; j<matches0.length(); j++) {
JSONObject matches = matches0.getJSONObject(j);
String match_time = TimeFormat.TimeRadar(matches.getString("date_of_match")); //время начала матча
String match_res = matches.getString("ft_value");
String match_status = matches.getString("status");
if (match_res.equals("null")) {match_res = "-:-";}
if (match_status.equals("Не начался")) {match_status = "";}
if (match_status.equals("null")) {match_status = "";}
JSONObject team_home1 = matches.getJSONObject("team_home");
String team_home = team_home1.getString("short_name");
String team_home_logo = team_home1.getString("logo_small");
JSONObject team_away1 = matches.getJSONObject("team_away");
String team_away = team_away1.getString("short_name");
String team_away_logo = team_away1.getString("logo_small");
FootballResultsData data = new FootballResultsData(matches1.getString("tournament_name"),
match_time,
match_res,
team_home, team_away,
match_status,
team_home_logo,
team_away_logo);
dl.add(data);
}}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
#SuppressLint("SimpleDateFormat")
void currenttime () {
long date_today = System.currentTimeMillis();
today_day = new SimpleDateFormat("dd").format(date_today);
today_month = new SimpleDateFormat("MM").format(date_today);
today_year = new SimpleDateFormat("yyyy").format(date_today);
mDay = today_day; mMonth = today_month; mYear = today_year;
}
#SuppressLint("SimpleDateFormat")
void calendar (String dd, String mm, String yyyy, int day_n) {
String sourceDate = yyyy+"-"+mm+"-"+dd;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date myDate;
try {
myDate = format.parse(sourceDate);
myDate = DateUtil.addDays(myDate, day_n);
String mDate = new SimpleDateFormat("dd MM yyyy").format(new SimpleDateFormat("EEE MMM dd kk:mm:ss zzzz yyyy").parse(myDate.toString()));
mDay = new SimpleDateFormat("dd").format(new SimpleDateFormat("dd MM yyyy").parse(mDate));
mMonth = new SimpleDateFormat("MM").format(new SimpleDateFormat("dd MM yyyy").parse(mDate));
mYear = new SimpleDateFormat("yyyy").format(new SimpleDateFormat("dd MM yyyy").parse(mDate));
Log.i(C.T, mDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
#SuppressLint("SetTextI18n")
#Override
public void onClick(View v) {
//currenttime ();
switch (v.getId()) {
case R.id.arrow_left: {n=n-1; break;}
case R.id.arrow_right: {n=n+1; break;}
default: break;
}
calendar(today_day, today_month, today_year, n);
datepicker.setText(Integer.parseInt(mDay)+" "+TimeFormat.monthDef(Integer.parseInt(mMonth))+" "+mYear);
ResultDisplay();
}
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
}
void datepickermethod () {
DatePickerDialog datepick = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
datepicker.setText(dayOfMonth+" "+TimeFormat.monthDef(month+1)+" "+year);
mDay = String.valueOf(dayOfMonth); mMonth = String.valueOf(month+1); mYear = String.valueOf(year);
n=0;
today_day = String.valueOf(dayOfMonth); today_month = String.valueOf(month+1); today_year = String.valueOf(year);
ResultDisplay();
}
}, Integer.parseInt(today_year), Integer.parseInt(today_month)-1, Integer.parseInt(today_day));
datepick.show();
}
}
For setters and getters:
class FootballResultsData {
public FootballResultsData(String tournament_name, String match_time, String match_result, String team_home, String team_away, String match_status, String team_home_logo, String team_away_logo) {
this.setTournament_name(tournament_name);
this.setMatch_time(match_time);
this.setMatch_result(match_result);
this.setTeam_home(team_home);
this.setTeam_away(team_away);
this.setMatch_status(match_status);
this.setTeam_home_logo(team_home_logo);
this.setTeam_away_logo(team_away_logo);
}
private String tournament_name;
private String match_time;
private String match_result;
private String team_home;
private String team_away;
private String match_status;
private String team_home_logo;
private String team_away_logo;
public String getMatch_time() { return match_time; }
public void setMatch_time(String match_time) {
this.match_time = match_time;
}
public String getTeam_home() {
return team_home;
}
public void setTeam_home(String team_home) {
this.team_home = team_home;
}
public String getTeam_away() {
return team_away;
}
public void setTeam_away(String team_away) {
this.team_away = team_away;
}
public String getMatch_status() {
return match_status;
}
public void setMatch_status(String match_status) {
this.match_status = match_status;
}
public String getMatch_result() { return match_result; }
public void setMatch_result(String match_result) { this.match_result = match_result; }
public String getTeam_home_logo() {
return team_home_logo;
}
public void setTeam_home_logo(String team_home_logo) {
this.team_home_logo = team_home_logo;
}
public String getTeam_away_logo() {
return team_away_logo;
}
public void setTeam_away_logo(String team_away_logo) {
this.team_away_logo = team_away_logo;
}
public String getTournament_name() {
return tournament_name;
}
public void setTournament_name(String tournament_name) {
this.tournament_name = tournament_name;
}
}
Cardview for a display of match:
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tournament_result" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:background="#drawable/newsbody_file">
<TextView
android:id="#+id/linebelownews"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/colorNewsPressed" />
<TextView
android:id="#+id/match_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/linebelownews"
android:text="22:00" />
<TextView
android:id="#+id/match_status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:text="ост." />
<TextView
android:id="#+id/match_res"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/match_time"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:text="2:2"
android:textStyle="bold" />
<TextView
android:id="#+id/match_th"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/match_time"
android:layout_marginEnd="5dp"
android:layout_toStartOf="#+id/logo_th"
android:text="Динамо"
android:textAlignment="viewEnd"
android:textColor="#000000" />
<TextView
android:id="#+id/match_ta"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_toEndOf="#+id/logo_ta"
android:layout_below="#id/match_time"
android:textColor="#000000"
android:text="Шахтер" />
<ImageView
android:id="#+id/logo_th"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_toStartOf="#id/match_res"
android:layout_below="#+id/match_time"
android:contentDescription="logo_th"
app:srcCompat="#drawable/author_file" />
<ImageView
android:id="#+id/logo_ta"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_below="#id/match_time"
app:srcCompat="#drawable/author_file"
android:layout_toEndOf="#id/match_res"
android:layout_marginBottom="5dp"
android:contentDescription="logo_th" />
<TextView
android:id="#+id/tournament_n"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/match_status"
android:layout_centerHorizontal="true"
android:text="#string/name_tournament" />
</RelativeLayout>
</android.support.v7.widget.CardView>
And main layout with Recyclerview:
<RelativeLayout
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="wrap_content"
android:id="#+id/tournament_result">
<android.support.v7.widget.RecyclerView
android:id="#+id/rcMatch1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lCalendar">
<Button
android:id="#+id/arrow_left"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginTop="5dp"
android:layout_toStartOf="#+id/btnDatepick"
android:background="#drawable/ic_arrow_left" />
<Button
android:id="#+id/arrow_right"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_toEndOf="#+id/btnDatepick"
android:background="#drawable/ic_arrow_right" />
<Button
android:id="#+id/btnDatepick"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:paddingStart="8dp"
android:paddingEnd="8dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<Switch
android:id="#+id/swLive"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_marginStart="16dp" />
</RelativeLayout>
</RelativeLayout>
EDIT
Adapter:
class FootballResultsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private ArrayList<FootballResultsData> footballresults_data = new ArrayList<FootballResultsData>();
private static int View_Header = 0;
private static int View_Item = 1;
public FootballResultsAdapter(Context context, ArrayList<FootballResultsData> footballresults_data) {
this.context = context;
this.footballresults_data = footballresults_data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder holder = null;
if(viewType == View_Item) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_match, parent, false);
holder = new ViewHolder_item(view);
}
else if(viewType == View_Header) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_tournament, parent, false);
holder = new ViewHolder_header(view);
}
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
FootballResultsData NFD = footballresults_data.get(position);
if (holder instanceof ViewHolder_item) {
((ViewHolder_item) holder).match_time.setText(NFD.getMatch_time());
((ViewHolder_item) holder).match_result.setText(NFD.getMatch_result());
((ViewHolder_item) holder).team_home.setText(NFD.getTeam_home());
((ViewHolder_item) holder).team_away.setText(NFD.getTeam_away());
((ViewHolder_item) holder).match_status.setText(NFD.getMatch_status());
Glide.with(context).load(NFD.getTeam_home_logo()).into( ((ViewHolder_item) holder).team_home_logo);
Glide.with(context).load(NFD.getTeam_away_logo()).into( ((ViewHolder_item) holder).team_away_logo);
}
else if (holder instanceof ViewHolder_header) {
((ViewHolder_header) holder).tournament_name.setText(NFD.getTournament_name());
}
}
#Override
public int getItemViewType(int position) {
super.getItemViewType(position);
if(position == 0) {
return View_Header;
}else {
return View_Item;
}
}
#Override
public int getItemCount() {
return footballresults_data.size()+1;
}
public static class ViewHolder_item extends RecyclerView.ViewHolder {
public TextView match_time;
public TextView match_result;
public TextView team_home;
public TextView team_away;
public TextView match_status;
public ImageView team_home_logo;
public ImageView team_away_logo;
public ViewHolder_item(View itemView) {
super(itemView);
match_time = (TextView)itemView.findViewById(R.id.match_time);
match_result = (TextView)itemView.findViewById(R.id.match_res);
team_home = (TextView)itemView.findViewById(R.id.match_th);
team_away = (TextView)itemView.findViewById(R.id.match_ta);
match_status = (TextView)itemView.findViewById(R.id.match_status);
team_home_logo = (ImageView)itemView.findViewById(R.id.logo_th);
team_away_logo = (ImageView)itemView.findViewById(R.id.logo_ta);
}
}
public static class ViewHolder_header extends RecyclerView.ViewHolder {
public TextView tournament_name;
public ViewHolder_header(View itemView) {
super(itemView);
tournament_name = (TextView)itemView.findViewById(R.id.tournament_n);
}
}
}
Override getItemViewType (int position) return the appropriate type based on position and then inflate a different layout for header in onCreateViewHolder.
In Adapter
private static int View_Header =0;
private static int View_Item = 1;
Then
#Override
public int getItemViewType (int position) {
// position 0 return header type
if(position == 0) {
return View_Header;
}else {
return View_Item;
}
}
Then
// add 1 to the list
// total items is item in list + 1 for header
#Override
public int getItemCount() {
return footballresults_data.size()+1;
}
Then
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder holder = null;
if(viewType == View_Item) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_match, parent, false);
holder = new ViewHolder_Item(view);
}else if(viewType == View_Header) {
// inflate header layout
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.header_layout, parent, false);
holder = new ViewHolder_header(view);
}
return holder;
}
Then
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof ViewHolder) {
// bind row items items
}
// create a separate viewholder class for header
else if( holder instanceof ViewHolder_header){
// bind header item
}
If you are looking for header and sub items (grouping items under a header) have a look at https://stackoverflow.com/a/42976078/653856. But the logic remains the same

Getting error - android.widget.TextView.getText()' on a null object reference [duplicate]

This question already has answers here:
findViewByID returns null
(33 answers)
Closed 6 years ago.
Im trying to use intent to get information from the textview in my listview and display it on another activity. I have tried searching for answers but i cant seem to find the problem .
Menuactivity :
public class MenuActivity extends Activity {
private String server = "http://172.16.156.56";
private String sql_table = "orders";
private ListView list;
private TextView txtOrder, txtMember, txtPrice;
private Button btnAdd;
ArrayList<String> rows;
ListView listView1;
Button btnSubmit;
ArrayList<CustomItem> itemList, selectedList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
txtOrder = (TextView) findViewById(R.id.txt1);
txtMember = (TextView) findViewById(R.id.txt2);
txtPrice = (TextView) findViewById(R.id.txt3);
list=(ListView) findViewById(R.id.listView);
btnAdd = (Button)findViewById(R.id.button);
rows = new ArrayList<String>();
itemList=new ArrayList<CustomItem>();
itemList.add(new CustomItem("Fried Rice","description","1","Quantity"));
itemList.add(new CustomItem("Fried Noodle","description","2","Quantity"));
itemList.add(new CustomItem("Prawn noodle","description","3","Quantity"));
itemList.add(new CustomItem("Chicken Rice","description","4","Quantity"));
int[] prgmImages={R.drawable.friedrice,R.drawable.friednoodle,R.drawable.pnoodle,R.drawable.chickenrice};
listView1 = (ListView) findViewById(R.id.listView);
final CustomLVAdapter customLVAdapter = new CustomLVAdapter(this, itemList,prgmImages);
listView1.setAdapter(customLVAdapter);
btnSubmit = (Button) findViewById(R.id.button);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String strOrder = txtOrder.getText().toString();
String strMember = txtMember.getText().toString();
String strPrice = txtPrice.getText().toString();
StringBuffer responseText = new StringBuffer();
selectedList = new ArrayList<CustomItem>();
int total = 0;
for (int i = 0; i < itemList.size(); i++) {
CustomItem object = itemList.get(i);
if (object.isSelected()) {
responseText.append(object.getItem() + "," + object.getQty() + ",");//item
selectedList.add(object);
//calculate price
total = total + Integer.parseInt(object.getQty()) * Integer.parseInt(object.getPrice());
}
}
Add(responseText.toString(), "5565", String.valueOf(total));
Intent i = new Intent(getApplicationContext(), ReceiptActivity.class);
i.putExtra("Order",strOrder);
i.putExtra("Member",strMember);
i.putExtra("Price",strPrice);
startActivity(i);
Toast.makeText(getApplicationContext(), responseText + " $" + total,
Toast.LENGTH_SHORT).show();
SelectAll();
//store in database
//go to ReceiptActivity - membership, item, totalprice
}
});
}
public void Add(final String item, final String membership, final String price)
{
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
String url = server + "/insertorder.php";
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("item",item );
MyData.put("membership",membership );
MyData.put("price",price );
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
SelectAll();
}
public void SelectAll()
{
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
String url = server + "/fetchorder.php";
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
JSONArray jsonMainNode = jsonResponse.optJSONArray(sql_table);
rows.clear();
for(int i=0; i < jsonMainNode.length(); i++)
{
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String order = jsonChildNode.optString("item").toString();
String membership = jsonChildNode.optString("membership").toString();
String price = jsonChildNode.optString("price").toString();
rows.add(order + ", " + membership + ", " + price );
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MenuActivity.this,
android.R.layout.simple_list_item_1, rows);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
}
});
MyRequestQueue.add(MyStringRequest);
}
}
recieptactivity (the results should be displayed here)
public class ReceiptActivity extends Activity {
static public String txtOrder = "";
TextView foodorder;
ArrayList<CustomItem> itemList, selectedList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receipt);
Bundle extras = getIntent().getExtras();
String strOrder = extras.getString("Order");
String strMember = extras.getString("Member");
String strPrice = extras.getString("Price");
TextView foodorder = (TextView)findViewById(R.id.foodorder);
foodorder.setText("hey"+strOrder);
menu.xml :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MenuActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit Order"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
listview.xml :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView1"
android:id="#+id/txt1"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
style="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView2"
android:id="#+id/txt2"
android:textStyle="bold"
android:layout_below="#+id/txt1"
android:layout_alignStart="#+id/txt1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView3"
android:id="#+id/txt3"
android:textStyle="bold"
android:layout_below="#+id/txt2"
android:layout_alignStart="#+id/txt2" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ckBox"
android:checked="false"
android:layout_below="#+id/txt3"
android:layout_alignStart="#+id/txt3"
/>
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitXY"
android:gravity="left"
android:layout_alignBottom="#+id/ckBox"
android:layout_toStartOf="#+id/txt1"
android:layout_alignParentEnd="false"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true" />
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/numberPicker"
android:layout_toEndOf="#+id/txt2"
android:layout_marginStart="23dp"
android:layout_alignParentTop="true"
android:layout_alignBottom="#+id/ckBox" />
customadapter :
public class CustomLVAdapter extends BaseAdapter {
private Context context;
LayoutInflater inflater;
private ArrayList<CustomItem> objectList;
private int[] imageId;
public static ArrayList<CustomItem> arl_food=new ArrayList<>();
private class ViewHolder {
TextView txt1,txt2,txt3;
CheckBox ckBox;
ImageView image;
NumberPicker np;
}
public CustomLVAdapter(Context context, ArrayList<CustomItem> objectList,int[]prgmImages){
this.context = context;
this.inflater = LayoutInflater.from(context);
this.objectList = objectList;
this.imageId = prgmImages;
this.objectList=objectList;
arl_food.clear();
for(int i=0;i<this.objectList.size();i++)
{
arl_food.add(this.objectList.get(i));
}
}
public int getCount(){
return objectList.size();
}
public CustomItem getItem (int position) {
return objectList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.row_checkbox_textview, null);
holder.txt1 = (TextView) convertView.findViewById(R.id.txt1);
holder.txt2 = (TextView) convertView.findViewById(R.id.txt2);
holder.txt3 = (TextView) convertView.findViewById(R.id.txt3);
holder.image=(ImageView) convertView.findViewById(R.id.image);
holder.ckBox = (CheckBox) convertView.findViewById(R.id.ckBox);
holder.np = (NumberPicker) convertView.findViewById(R.id.numberPicker);
holder.np.setMinValue(0);
holder.np.setMaxValue(10);
convertView.setTag(holder);
holder.ckBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
CustomItem object = (CustomItem) cb.getTag();
Toast.makeText(context,
"You have selected: " + object.getItem() +
"Price: " + object.getPrice() +
"Qty: " + object.getQty(),
Toast.LENGTH_LONG).show();
object.setSelected(cb.isChecked());
arl_food.get(position).setSelected(cb.isChecked());
}
}
);
holder.np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
NumberPicker p = picker;
CustomItem object = (CustomItem) p.getTag();
object.setQty(String.valueOf(newVal));
arl_food.get(position).setQty(String.valueOf(newVal));
}
});
}
else {
holder = (ViewHolder) convertView.getTag();
}
CustomItem object = objectList.get(position);
holder.txt1.setText(object.getItem());
holder.txt2.setText(object.getDesc());
holder.txt3.setText(object.getPrice());
holder.np.setTag(object);
holder.image.setImageResource(imageId[position]);
holder.ckBox.setChecked(object.isSelected());
holder.ckBox.setTag(object);
return convertView;
}
}
customitem :
public class CustomItem {
private int id;
private String item;
private String price;
private String desc;
private String qty;
private Boolean selected = false;
public CustomItem(){
}
public CustomItem(String item,String desc, String price,String qty){
this.item=item;
this.desc=desc ;
this.price=price;
this.qty=qty;
}
public CustomItem(int id, String item,String desc, String price,String qty){
this.id=id;
this.item=item;
this.desc=desc;
this.price=price;
this.qty=qty;
}
public int getId(){
return id;
}
public void setId (int id) {
this.id=id;
}
public String getItem(){
return item;
}
public void setItem(String item){
this.item=item;
}
public String getDesc()
{
return desc;
}
public void setDesc(String desc) {
this.desc=desc;
}
public String getPrice()
{
return price;
}
public void setPrice(String price) {
this.price=price;
}
public String getQty()
{
return qty;
}
public void setQty(String qty) {
this.qty=qty;
}
public boolean isSelected(){
return selected;
}
public void setSelected(boolean selected){
this.selected=selected;
}
logcat :
06-30 15:25:59.969 7196-7196/com.example.android.cardemulation E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.cardemulation, PID: 7196
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference
at com.example.android.cardemulation.MenuActivity$1.onClick(MenuActivity.java:79)
at android.view.View.performClick(View.java:5226)
at android.view.View$PerformClick.run(View.java:21266)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5845)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
You can not use this in to your Activity.
txtOrder = (TextView) findViewById(R.id.txt1);
txtMember = (TextView) findViewById(R.id.txt2);
txtPrice = (TextView) findViewById(R.id.txt3);
You should use another approach to get selected item data.
You can get from itemList or selectedList and can process further.

How to run time update data from edit-text and spinner to database

I am try to update data from edit-text and spinner to my database . but I found problem when scrolling list-view and also update data. My data is fluctuation after scrolling , so enable to save updated data.
below is my demo code.. please tall me where I am wrong.
Activity code:(MainActivity.java)
public class MainActivity extends AppCompatActivity {
private ListView listview;
private MainActivity context;
private newCustomDBAdapter adpter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String main[] = {"A", "B", "C", "D", "E", "F", "G", "H","i", "j", "k", "l"};
String main1[] = {"Aa", "Bbb", "Cccc", "Ddddd", "Eeeeeee", "Fff", "G", "H","Eeeeeee", "Fff", "G", "H"};
String values[] = {"A1", "B2", "C3", "D4", "E4", "F6", "G7", "H8","E4", "F6", "G7", "H8"};
String values_temp[] = {"A1", "B2"};
String valuesSpin[][] = {main, main, main, main1, main1, main1, main1, main,values_temp,values_temp,values_temp,values_temp};
ArrayList<String> arraylist_item = new ArrayList<String>(Arrays.<String>asList(main));
ArrayList<String> arraylist_item_values = new ArrayList<String>(Arrays.<String>asList(values));
ArrayList<String> arraylist_item1 = new ArrayList<String>(Arrays.<String>asList(main1));
List<List<String>> listOfLists = new ArrayList<List<String>>();
listOfLists.add(arraylist_item1);
listview = (ListView) findViewById(R.id.listview);
context = this;
adpter= new newCustomDBAdapter(context, arraylist_item, arraylist_item_values, listOfLists,valuesSpin);
listview.setAdapter(adpter);
}
public void Save(View view)
{
String s=adpter.main_hash_map.toString();
Log.i("Valiue of has map- "," "+s);
}
}
Adapter Code:(newCustomDBAdapter.java)
public class newCustomDBAdapter extends BaseAdapter {
private final String[][] valuesSpin;
public boolean checkData;
public int counter = 0;
private String LVL;
private Context CONTEXT;
private List<String> ITEMS = new ArrayList<>();
public static HashMap<Integer, String> main_hash_map= new HashMap<>();
private List<List<String>> VALUES = new ArrayList<>();
private List<String> TYPES = new ArrayList<>();
private List<String> DATATITLE = new ArrayList<>();
private List<String> DATAVALUE = new ArrayList<>();
private String finalvalueInValue = "";
private boolean checkUserComesInv;
private String spinnerValue = "";
private String sizeValue = "";
private String final_value;
private HashMap<Integer, Integer> mapRowSpinnerPos = new HashMap<>();
public newCustomDBAdapter(Context context, List<String> items, List<String> type, List<List<String>> spinner_values, String[][] valuesSpin) {
this.ITEMS = items;
this.CONTEXT = context;
this.valuesSpin = valuesSpin;
this.TYPES = type;
checkData = true;
counter = 0;
}
#Override
public int getCount() {
if (ITEMS != null && ITEMS.size() != 0) {
return ITEMS.size();
}
return 0;
}
#Override
public Object getItem(int position) {
return ITEMS.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final ViewHolder holder;
String itemlevel = "";
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater newInflate = (LayoutInflater) CONTEXT.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = newInflate.inflate(R.layout.custom_new_db_adapter_layout, null);
holder.editMain = (EditText) convertView.findViewById(R.id.custum_main_edit);
holder.imgMain = (ImageView) convertView.findViewById(R.id.custum_main_img);
holder.spinMain = (Spinner) convertView.findViewById(R.id.custum_main_spinner);
holder.txtMain = (TextView) convertView.findViewById(R.id.custum_main_desc);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if ((ITEMS.get(position).equals("A") || ITEMS.get(position).equals("D") || ITEMS.get(position).equals("i") || ITEMS.get(position).equals("l"))) {
holder.editMain.setVisibility(View.GONE);
holder.editMain.setEnabled(false);
holder.spinMain.setVisibility(View.VISIBLE);
holder.spinMain.setEnabled(true);
} else if (ITEMS.get(position).equals("B")) {
holder.spinMain.setVisibility(View.VISIBLE);
holder.editMain.setEnabled(true);
holder.editMain.setVisibility(View.VISIBLE);
holder.spinMain.setEnabled(true);
} else {
holder.editMain.setVisibility(View.VISIBLE);
holder.editMain.setEnabled(true); holder.spinMain.setVisibility(View.GONE);
holder.spinMain.setEnabled(false);
}
holder.txtMain.setText(ITEMS.get(position));
holder.editMain.setText(TYPES.get(position));
holder.editMain.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
main_hash_map.put(position, arg0.toString());
Log.i("value edit- ",arg0.toString()+" position- "+position);
}
});
/* if (main_hash_map.containsKey(position)) {
holder.editMain.setText(main_hash_map.get(position));
}*/
holder.spinMain.setAdapter(new ArrayAdapter<>(CONTEXT, android.R.layout.simple_spinner_dropdown_item, valuesSpin[position]));
holder.spinMain.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int spinnerPosition, long id) {
mapRowSpinnerPos.put(position, spinnerPosition);
String textSpin = holder.spinMain.getSelectedItem().toString();
main_hash_map.put(position,textSpin
);
Log.i("value in spinner- ",textSpin+" position- "+position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
if (mapRowSpinnerPos.containsKey(position)) {
holder.spinMain.setSelection(mapRowSpinnerPos.get(position));
}
return convertView;
}
public class
ViewHolder {
private EditText editMain;
private ImageView imgMain;
private TextView txtMain;
private Spinner spinMain;
String typeValue = "";
}
}
custom_new_db_adapter_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_marginTop="5dp"
android:id="#+id/custum_main_lin_layout"
android:layout_width="match_parent"
android:background="#color/colorAccent"
android:layout_height="55dp">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.3"
android:id="#+id/custum_main_desc"
android:textSize="18sp"
android:layout_margin="5dp"
android:textColor="#fff"
android:text=" ggggg"
android:layout_gravity="center_vertical"/>
<EditText android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.4"
android:singleLine="true"
android:lines="1"
android:inputType="text"
android:id="#+id/custum_main_edit"
android:layout_gravity="center_vertical"
android:maxLines="1"
android:background="#fff"
android:textColor="#000"
android:layout_margin="5dp"/>
<Spinner android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.7"
android:layout_margin="5dp"
android:visibility="visible"
android:background="#drawable/btn_dropdown_selected"
android:id="#+id/custum_main_spinner"
android:layout_gravity="center_vertical"/>
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.1"
android:id="#+id/custum_main_img"
android:layout_gravity="center_vertical"
android:src="#drawable/icon_forward_10"/>
</LinearLayout>
</RelativeLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.newf.phoenixbd.demoaccornford.MainActivity">
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_above="#+id/button"></ListView>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="#+id/button"
android:onClick="Save"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Sorry for my English.
thanks in advance.
You can pass the updated value from the adapter to your activity using an interface. I solved my problem using this:
Class:
public class YourActivity extends ActionBarActivity implements GetClickedItem {
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Context mContext = this;
ListView Your_List = findViewById(R.id.listview);
Your_Adapter adptr = new Your_Adapter(mContext, (GetClickedItem) this);
Your_List.setAdapter(adptr);
}
#Override
public void getPostID(int position, String any_data) {
Toast(context, "position: " + position + " any_data: " + any_data).show();
}
}
and Adapter:
public class Your_Adapter extends BaseAdapter{
private Context mContext;
private GetClickedItem mGetClickedItem;
Holder holder;
// Constructor
public Your_Adapter(Context context, GetClickedItem itemclickreference) {
mContext = context;
this.mGetClickedItem = itemclickreference;
}
public int getCount() {
return your_data_size;
}
public Object getItem(int position) {
return your_data.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
holder = new Holder();
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.xml_layout, null);
holder.mButton = (Button) convertView.findViewById(R.id.button);
convertView.setTag(holder);
}else {
holder = (Holder) convertView.getTag();
}
holder.mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mGetClickedItem.getPostID(position, your_data.get(position));
}
});
return convertView;
}
public class Holder{
Button mButton;
}
public interface GetClickedItem{
public void getPostID(int position, String any_other_data);
}
}
You can access any data from the adapter, all you have to do is include the button in your adapter layout file.

Categories