I want data from my JSON to be displayed in another Activity inside a ListView with 3 columns. I made a Layout for my ListView but that's all
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:descendantFocusability="afterDescendants"
android:orientation="vertical"
android:paddingBottom="15dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="15dp">
<TextView
android:id="#+id/txtViewNumarCumparator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="NumarCumparator" />
<TextView
android:id="#+id/listaProduse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/txtViewNumarCumparator"
android:layout_marginTop="10dp"
android:text="NumarProduse" />
<TextView
android:id="#+id/sumaProduse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:text="SumaProdsue" />
I have a JSONObject which retrieves data like this :
{"dataCurenta":"11-08-2017",
"produseSelectate":3,
"pretTotal":605
}
Here is the code :
JSONObject json = new JSONObject();
try {
json.put("dataCurenta", getDate(calendarData.getTimeInMillis()));
} catch (JSONException e) {
e.printStackTrace();
}
try {
json.put("produseSelectate", listaProdusePreview.getAdapter().getCount());
} catch (JSONException e) {
e.printStackTrace();
}
try {
json.put("pretTotal", totalPrice);
} catch (JSONException e) {
e.printStackTrace();
}
try {
json.put("numarVanzare", numarVanzare);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("LISTA", json.toString());
Adapter :
public class CardArrayAdapter extends ArrayAdapter<Card> {
private static final String TAG = "CardArrayAdapter";
private List<Card> cardList = new ArrayList<Card>();
static class CardViewHolder {
TextView line1;
TextView line2;
TextView line3;
}
public CardArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public void add(Card object) {
cardList.add(object);
super.add(object);
}
#Override
public int getCount() {
return this.cardList.size();
}
#Override
public Card getItem(int index) {
return this.cardList.get(index);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CardViewHolder viewHolder;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.list_item_card, parent, false);
viewHolder = new CardViewHolder();
viewHolder.line1 = (TextView) row.findViewById(R.id.txtViewNumarCumparator);
viewHolder.line2 = (TextView) row.findViewById(R.id.listaProduse);
viewHolder.line3 = (TextView) row.findViewById(R.id.sumaProduse);
row.setTag(viewHolder);
} else {
viewHolder = (CardViewHolder)row.getTag();
}
Card card = getItem(position);
viewHolder.line1.setText(card.getNumarCumparator());
viewHolder.line2.setText(card.getListaProduse());
viewHolder.line3.setText(card.getSumaProduse());
return row;
}
public Bitmap decodeToBitmap(byte[] decodedByte) {
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
} }
Object class :
public class Card {
private Integer numarCumparator;
private String listaProduse;
private Integer sumaProduse;
public Card(Integer numarCumparator, String listaProduse, Integer sumaProduse) {
this.numarCumparator = numarCumparator;
this.listaProduse = listaProduse;
this.sumaProduse = sumaProduse;
}
public Integer getNumarCumparator() {
return numarCumparator;
}
public void setNumarCumparator(Integer numarCumparator) {
this.numarCumparator = numarCumparator;
}
public String getListaProduse() {
return listaProduse;
}
public void setListaProduse(String listaProduse) {
this.listaProduse = listaProduse;
}
public Integer getSumaProduse() {
return sumaProduse;
}
public void setSumaProduse(Integer sumaProduse) {
this.sumaProduse = sumaProduse;
}}
Hope the question is clear, I really need to get out from this problem.
Related
I want to ask you, how to change programmatically the background color of LinearLayout in CardView when the text in TextView equals specify word or is empty. For example field1 getting string "red", the background of LinearLayout gets red. I'm fetching the data from JSON php file.
MainActivity.class
public class MainActivity extends AppCompatActivity {
private String jsonURL = "http://example.com/test.php";
private final int jsoncode = 1;
private RecyclerView recyclerView;
ArrayList<Model> ModelArrayList;
private Adapter adapter;
private static ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler);
fetchJSON();
}
#SuppressLint("StaticFieldLeak")
private void fetchJSON(){
new AsyncTask<Void, Void, String>(){
protected String doInBackground(Void[] params) {
String response="";
HashMap<String, String> map=new HashMap<>();
try {
HttpRequest req = new HttpRequest(jsonURL);
response = req.prepare(HttpRequest.Method.POST).withData(map).sendAndReadString();
} catch (Exception e) {
response=e.getMessage();
}
return response;
}
protected void onPostExecute(String result) {
//do something with response
onTaskCompleted(result,jsoncode);
}
}.execute();
}
public void onTaskCompleted(String response, int serviceCode) {
Log.d("responsejson", response.toString());
switch (serviceCode) {
case jsoncode:
if (isSuccess(response)) {
removeSimpleProgressDialog(); //will remove progress dialog
ModelArrayList = getInfo(response);
adapter = new Adapter(this,ModelArrayList);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
}else {
Toast.makeText(MainActivity.this, getErrorCode(response), Toast.LENGTH_SHORT).show();
}
}
}
public ArrayList<Model> getInfo(String response) {
ArrayList<Model> ModelArrayList = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("status").equals("true")) {
JSONArray dataArray = jsonObject.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
Model fieldsModel = new Model();
JSONObject dataobj = dataArray.getJSONObject(i);
fieldsModel.setField1(dataobj.getString("field1"));
fieldsModel.setField2(dataobj.getString("field2"));
ModelArrayList.add(fieldsModel);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return ModelArrayList;
}
public boolean isSuccess(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.optString("status").equals("true")) {
return true;
} else {
return false;
}
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
public String getErrorCode(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
return jsonObject.getString("message");
} catch (JSONException e) {
e.printStackTrace();
}
return "No data";
}
}
Adapter.class
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {
private LayoutInflater inflater;
private ArrayList<Model> ModelArrayList;
public Adapter(Context ctx, ArrayList<Model> rogerModelArrayList){
inflater = LayoutInflater.from(ctx);
this.ModelArrayList = rogerModelArrayList;
}
#Override
public Adapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.rv_item, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(Adapter.MyViewHolder holder, int position) {
holder.field1.setText(ModelArrayList.get(position).getField1());
holder.field2.setText(ModelArrayList.get(position).getField2());
}
#Override
public int getItemCount() {
return ModelArrayList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView field1,field2;
public MyViewHolder(View itemView) {
super(itemView);
field1 = (TextView) itemView.findViewById(R.id.field1);
field2 = (TextView) itemView.findViewById(R.id.field2);
}
}
}
Model.class
public class Model {
private String field1, field2;
public String getField1() {
return field1;
}
public void setField1(String field1) {
this.field1 = field1;
}
public String getField2() {
return field2;
}
public void setField2(String field2) {
this.field2 = field2;
}
}
activity_main.xml
<?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:background="#cd15e6"
tools:context=".MainActivity">
** <android.support.v7.widget.RecyclerView
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginTop="15dp"/> **
</LinearLayout>
rv_item.xml
Here is the LinearLayout which i want to change the color LL_background
<?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"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
app:cardCornerRadius="5dp">
<LinearLayout
android:id="#+id/LL_background"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:orientation="vertical">
<TextView
android:id="#+id/field1"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_marginTop="5dp"
android:layout_weight="1"
android:text="ddd"
android:textColor="#000"
android:textStyle="bold" />
<TextView
android:id="#+id/field2"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:text="ddd"
android:textColor="#000"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Please check my project and share your ideas. Thanks a lot 😊
First of all add layout reference to ViewHolder
class MyViewHolder extends RecyclerView.ViewHolder{
TextView field1,field2;
LinearLayout layout;
public MyViewHolder(View itemView) {
super(itemView);
field1 = (TextView) itemView.findViewById(R.id.field1);
field2 = (TextView) itemView.findViewById(R.id.field2);
layout = itemView.findViewById(R.id.LL_background);
}
}
Then check Field1 and set color
#Override
public void onBindViewHolder(Adapter.MyViewHolder holder, int position) {
holder.field1.setText(ModelArrayList.get(position).getField1());
holder.field2.setText(ModelArrayList.get(position).getField2());
if(ModelArrayList.get(position).getField1().equalIgnoreCase("red")
holder.layout.setBackgroundColor(Color.RED)
}
red is not recognizable in android. Either you have to handle it manually like above or you can send the corresponding #code of color from server and handle it like below:
holder.layout.setBackgroundColor(Color.parseColor("#ff0000"));
You can change layout instead color. Create different layouts that has different background color or different design. Then do this.
#Override
public Adapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.rv_item, parent, false);
if(ModelArrayList.get(position).getField1().equalIgnoreCase("red")
view = inflater.inflate(R.layout.anotherLayout, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
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!
I'm building an application , i have created a listview where i can retreive data from mysql database. IT's working very good.
But the problem is that i want to load the data of each item in another activity with details from the database .
Can anyone help me please ?? i'm really stuck , i don't how to do it.
This is my java code :
public class GererUtilisateur extends AppCompatActivity
{
private ArrayList<ClassListItem> itemArrayListU;
private MyAppAdapterU myAppAdapterU;
private ListView listViewU;
private boolean succes = false;
private static final String DB_URL="jdbc:mysql://192.168.1.2/test3_10032018";
private static final String USER="";
private static final String PASS="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gerer_utilisateur);
listViewU=(ListView) findViewById(R.id.listuser);
itemArrayListU = new ArrayList<ClassListItem>();
SynDataU orderData = new SynDataU();
orderData.execute();
}
private class SynDataU extends AsyncTask<String,String,String> {
String msg="";
ProgressDialog progressDialog;
#Override
protected String doInBackground(String... strings) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(DB_URL, USER, PASS);
if (connection == null) {
succes = false;
} else {
String query = "SELECT id_utilisateur , nom , prenom , fonction FROM utilisateur";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) {
while (rs.next()) {
try {
itemArrayListU.add(new ClassListItem(rs.getInt("id_utilisateur"), rs.getString("nom"), rs.getString("prenom") , rs.getString("fonction")));
} catch (Exception ex) {
ex.printStackTrace();
}
}
succes = true;
}
}
}catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
succes = false;
}
return msg;
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(GererUtilisateur.this,"Synchronising","ListView Loading !!!",true);
}
#Override
protected void onPostExecute(String s) {
progressDialog.dismiss();
if (succes = false){
}else{
try{
myAppAdapterU = new MyAppAdapterU(itemArrayListU,GererUtilisateur.this);
listViewU.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listViewU.setAdapter(myAppAdapterU);
}catch (Exception ex){
}
}
}
}
public class MyAppAdapterU extends BaseAdapter {
public class ViewHolder{
TextView id;
TextView prenom;
TextView nom;
TextView fonction;
}
public List<ClassListItem> decisionList;
public Context context;
ArrayList<ClassListItem> arrayList;
private MyAppAdapterU(List<ClassListItem> apps,Context context){
this.decisionList= apps;
this.context=context;
arrayList= new ArrayList<ClassListItem>();
arrayList.addAll(decisionList);
}
#Override
public int getCount() {
return decisionList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
ViewHolder viewHolder = null;
if(rowView==null){
LayoutInflater inflater = getLayoutInflater();
rowView= inflater.inflate(R.layout.list_content,parent,false);
viewHolder= new ViewHolder();
viewHolder.id=rowView.findViewById(R.id.tv_id);
viewHolder.nom=rowView.findViewById(R.id.tv_nom);
viewHolder.prenom=rowView.findViewById(R.id.tv_prenom);
viewHolder.fonction=rowView.findViewById(R.id.tv_fonc);
rowView.setTag(viewHolder);
}else
{
viewHolder=(ViewHolder) convertView.getTag();
}
viewHolder.id.setText(decisionList.get(position).getId()+"");
viewHolder.nom.setText(decisionList.get(position).getNom()+"");
viewHolder.prenom.setText(decisionList.get(position).getPrenom()+"");
viewHolder.fonction.setText(decisionList.get(position).getFonction()+"");
return rowView;
}
}
public void ajout(View view){
Intent i = new Intent(getApplicationContext(),AjouterUtil.class);
startActivity(i);
}
And this is my xml file
<?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="com.example.mootaz.mobilevoting.GererUtilisateur"
android:background="#drawable/bg">
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="fill_parent"
android:layout_height="400dp"
android:layout_alignParentStart="true"
android:layout_below="#+id/btn_ajout"
android:layout_marginTop="25dp"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"
card_view:cardCornerRadius="10dp"
card_view:cardBackgroundColor="#color/BlueGrayLight"
>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listuser"/>
</android.support.v7.widget.CardView>
<android.support.v7.widget.AppCompatButton
android:id="#+id/btn_ajout"
style="#style/RaisedButtonA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="22dp"
android:layout_marginTop="98dp"
android:onClick="ajout"
android:text="Ajouter Utilisateur" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="41dp"
android:fontFamily="cursive"
android:text="Gerer les utilisateurs"
android:textColor="#color/primary"
android:textSize="28dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"/>
</RelativeLayout>
In your FirstActivity add this.
listViewU.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Movie movie = movieList.get(position);
// retrieve from movie whatever you want
movie.getName();
Toast.makeText(getApplicationContext(),"Name: "+movie.getName(),Toast.LENGTH_LONG).show();
// creaet intent and add data to it.
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra("name",movie.getName());
startActivity(intent);
}
});
In your second activity get data like this.
// get info from intent
Bundle bundle = getIntent().getExtras();
String name = bundle.getString("name");
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
i need create a custom adapter for a listview but i can't understand how could do it. Actually it works my work but using simply a listview with all objects inside the default android layout for the lists. I need "separate" the objects creating the custom adapter. This is the actual code:
private static class SoluzioniLoader extends AsyncTaskLoader<List<Soluzione>> {
private FermataComune partenza;
private FermataComune arrivo;
private String data;
public SoluzioniLoader(Context context, FermataComune partenza, FermataComune arrivo, String data) {
super(context);
this.partenza = partenza;
this.arrivo = arrivo;
this.data = data;
}
#Override
public List<Soluzione> loadInBackground() {
try {
List<Soluzione> soluzioni = Client.cercaCorseAndata(partenza, arrivo, data);
return soluzioni;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
private LoaderCallbacks<List<Soluzione>> mLoaderCallbacks = new LoaderCallbacks<List<Soluzione>>() {
private ProgressDialog pd;
#Override
public Loader<List<Soluzione>> onCreateLoader(int id, Bundle args) {
pd = new ProgressDialog(SoluzioniActivity.this);
pd.setTitle("Caricamento Soluzioni Trovate");
pd.setMessage("Attendi...");
pd.setIndeterminate(false);
pd.show();
return new SoluzioniLoader(SoluzioniActivity.this, partenza, arrivo, data);
}
#Override
public void onLoadFinished(Loader<List<Soluzione>> loader, List<Soluzione> data) {
try {
pd.dismiss();
} catch(Exception e){
}
if (data == null) {
// ERRORE
} else {
mListView.setAdapter(new ArrayAdapter<Soluzione>(SoluzioniActivity.this, android.r.layout.simple_list_item_1, data));
}
I've already created a layout for the row
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:id="#+id/fromhour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
/>
<TextView
android:id="#+id/from"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
/>
<TextView
android:id="#+id/tohour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
/>
<TextView
android:id="#+id/to"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
/>
</LinearLayout>
Any help how could i create and integrate a custom adapter here? Thanks
Try below code:
//Declare your custom adapter:
private EfficientAdapter adapter;
In onCreate() initialize it:
adapter = new EfficientAdapter(this);
Then set your list adapter,
your_listview.setAdapter(adapter);
//Your adapter code:
private class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Context context;
private Bitmap imageBitmap = null;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context = context;
}
#Override
public int getCount() {
return YOUR_ARRAY.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.featured_item, null);
holder = new ViewHolder();
holder.txtTitle = (TextView) convertView.findViewById(R.id.txtTitle);
holder.txtAuthorName = (TextView) convertView.findViewById(R.id.txtAuthorName);
holder.txtDescription = (TextView) convertView.findViewById(R.id.txtDescription);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtTitle.setText(data.get(position).get("article_title"));
holder.txtAuthorName.setText(data.get(position).get("author_name"));
holder.txtDescription.setText(data.get(position).get("article_text"));
return convertView;
}
class ViewHolder {
//YOUR ATTRUBUTES TO DISPLAY IN LIST DECLARE HERE
TextView txtTitle;
TextView txtAuthorName;
TextView txtDescription;
}
}