CardView not rendered or data is not showing up in Recyclerview - android

May sound like a duplicate issue but have checked the issues posted which is either related to the getItemCount() not set or layout height/width issues.
I'm using a CardView as RecyclerView Item . The adapter fetches 60 records (checked the count )but the CardView is not even shown neither the data .
Using ConstraintLayout in which I'm still a newbie, the design view it shows perfectly. The data is being populated from external APIs and using retrofit library which is working fine.
Activity xml.
<android.support.constraint.ConstraintLayout 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:scrollbars="vertical"
tools:context="com.techn.rails.Activity.TrainStatus">
/>
<android.support.v7.widget.CardView
android:id="#+id/search_cardView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:cardElevation="5dp">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp">
<android.support.v7.widget.AppCompatTextView
android:id="#+id/trainno_search_tv"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Train Number"
app:layout_constraintEnd_toStartOf="#+id/trainno_search_et"
app:layout_constraintHorizontal_chainStyle="spread_inside"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintHorizontal_weight="1"
/>
<android.support.v7.widget.AppCompatEditText
android:id="#+id/trainno_search_et"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintStart_toEndOf="#id/trainno_search_tv"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBaseline_toBaselineOf="#+id/trainno_search_tv"
android:inputType="number"
android:maxLength="6"
android:hint="#string/train_number"
app:layout_constraintHorizontal_weight="1.5"
/>
<android.support.v7.widget.AppCompatEditText
android:id="#+id/doj_et"
android:layout_width="0dp"
app:layout_constraintEnd_toEndOf="#id/trainno_search_tv"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#+id/trainno_search_tv"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginTop="12dp"
/>
<android.support.v7.widget.AppCompatButton
android:id="#+id/doj_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintLeft_toRightOf="#+id/doj_et"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/trainno_search_et"
app:layout_constraintBaseline_toBaselineOf="#+id/doj_et"
android:layout_marginTop="12dp"
android:text="#string/select_date"
/>
<android.support.v7.widget.AppCompatButton
android:id="#+id/submit"
android:layout_width="100dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#+id/doj_btn"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:text="#string/submit_btn"
/>
</android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.RecyclerView
android:id="#+id/train_list"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/result_cardview"
app:layout_constraintBottom_toBottomOf="parent"
android:scrollbars="vertical"
android:padding="10dp"
android:layout_margin="10dp"></android.support.v7.widget.RecyclerView>
</android.support.constraint.ConstraintLayout>
Cardview xml
<android.support.constraint.ConstraintLayout
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.support.v7.widget.CardView
android:id="#+id/train_status_card_view"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_gravity="center"
android:layout_margin="5dp"
android:elevation="5dp"
app:cardCornerRadius="5dp"
android:background="?android:attr/selectableItemBackground">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.AppCompatTextView
android:id="#+id/train_stn_code_lbl"
android:layout_height="wrap_content"
android:layout_width="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
/>
<android.support.v7.widget.AppCompatTextView
android:id="#+id/train_stn_code"
android:layout_height="wrap_content"
android:layout_width="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toRightOf="#id/train_stn_code_lbl"
app:layout_constraintRight_toRightOf="parent" />
<android.support.v7.widget.AppCompatTextView
android:id="#+id/train_sch_arr_lbl"
android:layout_height="wrap_content"
android:layout_width="0dp"
app:layout_constraintTop_toBottomOf="#id/train_stn_code_lbl"
app:layout_constraintLeft_toLeftOf="parent"
/>
<android.support.v7.widget.AppCompatTextView
android:id="#+id/train_sch_arr"
android:layout_height="wrap_content"
android:layout_width="0dp"
app:layout_constraintTop_toBottomOf="#id/train_stn_code"
app:layout_constraintLeft_toRightOf="#id/train_sch_arr_lbl"
app:layout_constraintRight_toRightOf="parent" />
<android.support.v7.widget.AppCompatTextView
android:id="#+id/train_act_dep_lbl"
android:layout_height="wrap_content"
android:layout_width="0dp"
app:layout_constraintTop_toBottomOf="#id/train_sch_arr_lbl"
app:layout_constraintLeft_toLeftOf="parent"
/>
<android.support.v7.widget.AppCompatTextView
android:id="#+id/train_act_dep"
android:layout_height="wrap_content"
android:layout_width="0dp"
app:layout_constraintTop_toBottomOf="#id/train_sch_arr_lbl"
app:layout_constraintLeft_toRightOf="#id/train_act_dep_lbl"
app:layout_constraintRight_toRightOf="parent" />
</android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
</android.support.constraint.ConstraintLayout>
Activity
public class TrainStatus extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {
#BindView(R.id.doj_btn)
AppCompatButton mDojBtn;
#BindView(R.id.trainno_search_et)
AppCompatEditText mTrainNumber;
#BindView(R.id.submit)
AppCompatButton mSubmit;
#BindView(R.id.train_list)
RecyclerView recyclerView;
private Calendar calendar;
private DatePickerDialog datePickerDialog;
int Year, Month, Day ;
String dateSelected, dateToDisplay;
private TrainStatusRoute mAdapter;
private List<Route> mRoutes;
private static final String TAG = TrainStatus.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_train_status);
ButterKnife.bind(this);
mRoutes = new ArrayList<>();
mAdapter = new TrainStatusRoute(this,mRoutes);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(mAdapter);
calendar = Calendar.getInstance();
Year = calendar.get(Calendar.YEAR) ;
Month = calendar.get(Calendar.MONTH);
Day = calendar.get(Calendar.DAY_OF_MONTH);
mDojBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
datePickerDialog = DatePickerDialog.newInstance(TrainStatus.this, Year, Month, Day);
datePickerDialog.setThemeDark(false);
datePickerDialog.showYearPickerFirst(false);
}
});
mSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
requestAPIQuery(mTrainNumber.getText().toString(),dateSelected);
}
});
}
#Override
public void onDateSet(DatePickerDialog view, int Year, int Month, int Day) {
dateSelected = String.valueOf(Year)+String.valueOf(Month + 1)+String.valueOf(Day);
}
private void requestAPIQuery (String trainNumber, String doj){
IApi apiService = APIClient.getClient().create(IApi.class);
Call<TrainStatus> call = apiService.getTrainStatus(trainNumber,doj,API_KEY);
call.enqueue(new Callback<TrainStatus>() {
#Override
public void onResponse(Call<TrainStatus> call, Response<TrainStatus> response) {
List<Route> trainStatuses = response.body().getRoute();
mAdapter.notifyDataSetChanged();
Log.d(TAG,"Number of trains"+trainStatuses.size());//getting count 60 here
}
#Override
public void onFailure(Call<com.technovibe.railstat.Model.TrainStatus> call, Throwable t) {
Log.e(TAG, t.toString());
}
});
}
}
Adapter code
public class TrainStatusRoute extends RecyclerView.Adapter<TrainStatusRoute.RouteViewHolder> {
private Context mContext;
private List<Route> mRoutes;
public static class RouteViewHolder extends RecyclerView.ViewHolder{
#BindView(R.id.train_act_arr)
TextView mActArr;
#BindView(R.id.train_act_dep)
TextView mActDep;
#BindView(R.id.train_sch_arr)
TextView mSchArr;
#BindView(R.id.train_sch_dep)
TextView mSchDep;
public RouteViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
public TrainStatusRoute(Context context, List<Route> routeList) {
this.mContext = context;
this.mRoutes = routeList;
}
#Override
public TrainStatusRoute.RouteViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.train_status_card, parent, false);
return new RouteViewHolder(itemView);
}
#Override
public void onBindViewHolder(TrainStatusRoute.RouteViewHolder holder, int position) {
Route route = mRoutes.get(position);
holder.mActArr.setText(route.getActarr());
holder.mActDep.setText(route.getActdep());
holder.mSchDep.setText(route.getSchdep());
holder.mSchArr.setText(route.getScharr());
}
#Override
public int getItemCount() {
return mRoutes.size();
}
}
Please bear with me posting lengthy code.
Appreciate any help , thanks in advance.

I guess the problem could be in the card view's width and heights:
<android.support.v7.widget.CardView
android:id="#+id/search_cardView"
android:layout_width="0dp"
android:layout_height="wrap_content"
Try changing the width and height values to let's say width match_parent and height to 60 dp and see if the items will appear.

public void onResponse(Call<TrainStatus> call, Response<TrainStatus> response) {
List<Route> trainStatuses = response.body().getRoute();
//Add this line here
mAdapter.setRoutes(trainStatuses);
mAdapter.notifyDataSetChanged();
Log.d(TAG,"Number of trains"+trainStatuses.size());//getting count 60 here
}
And define a setter for your list in your adapter
public void setRoutes(List<Route> routes){
mRoutes = routes;
}

Related

RecyclerView that using GridLayoutManager with background makes different heights visible

I've made an adapter with a layout like the one I share below. it went well but, the appearance of each item became untidy.
Here is my code :
public class TableRecyclerAdapter extends RecyclerView.Adapter<TableRecyclerAdapter.ViewHolder> {
private ArrayList<TableModel> data;
private Context context;
private Fragment fragment;
private Dialog dialog;
public TableRecyclerAdapter(Context context, ArrayList<TableModel> data, Fragment fragment, Dialog dialog) {
this.context = context;
this.data = data;
this.fragment = fragment;
this.dialog = dialog;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v = inflater.inflate(R.layout.item_table, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.tvTable.setText(data.get(position).getName());
holder.tvState.setText(data.get(position).getStateString());
holder.bg.setBackgroundColor(Color.parseColor(data.get(position).getWarna()));
holder.tvHtml.setText(Html.fromHtml(data.get(position).getShortInfoHtml()));
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
public int getItemCount() {
return data.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private ImageView paid;
private TextView tvTable, tvHtml, tvState;
private ConstraintLayout bg;
public ViewHolder(View itemView) {
super(itemView);
tvTable = itemView.findViewById(R.id.tvTable);
tvHtml = itemView.findViewById(R.id.tvHtml);
bg = itemView.findViewById(R.id.bg);
tvState = itemView.findViewById(R.id.tvState);
paid = itemView.findViewById(R.id.ivPaid);
}
}
}
This is for layout item
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
app:cardCornerRadius="10dp"
app:cardElevation="3dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/bg"
android:layout_width="match_parent"
android:background="#drawable/border_button_green"
android:layout_height="wrap_content">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:layout_marginStart="12dp"
android:background="#drawable/border_transparent_table"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/tvState"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="4dp"
android:text="This text"
android:textColor="#color/color_primary"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
<TextView
android:id="#+id/tvTable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="25dp"
android:paddingStart="12dp"
android:paddingEnd="12dp"
android:text="7"
android:textColor="#color/color_primary"
android:textSize="30sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/tvHtml"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:layout_marginEnd="12dp"
android:paddingBottom="12dp"
android:text="Example Text"
android:textColor="#color/color_primary"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/tvTable" />
<ImageView
android:id="#+id/ivPaid"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="4dp"
android:src="#drawable/paid"
android:visibility="gone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
It makes my recyclerview have different heights depending on the text.
I want the items to be the same height per row (maximum height in the row)
Sorry for my english. I hope someone can help me. Thank you

Andriod Studio ListView doesn't update itself

I have ListView and my own adapter. ListView item consists of TextView, icon image and image "trash can"(simply "trash"). The problem is when i click on any item it should be deleted but in fact the last item of ListView disappears. I checked ArrayList and the item I clicked on is deleted from there.
Also when i try to add new item the program just restore previous items and if all initial items are displayed and i try to add new the program crashes. Although in ArrayList items are added correctly.
Activity code
public class MyItemsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_items);
myItemsList = findViewById(R.id.ListOfMyItems);
myItemsAdapter.arrayList.add(new MyItems("Keys", R.drawable.plus));
myItemsAdapter.arrayList.add(new MyItems("Wallet", R.drawable.plus));
myItemsAdapter.arrayList.add(new MyItems("Physics", R.drawable.plus));
myItemsAdapter.arrayList.add(new MyItems("umovnyy vasyl", R.drawable.plus));
myItemsAdapter.arrayList.add(new MyItems("Smartphone)", R.drawable.plus));
for (int i = 0; i<100; i++){
arrayList.add(new MyItems("Max)", R.drawable.plus));
}
myItemsList.addFooterView(new ImageView(this));
myItemsList.addHeaderView(new ImageView(this));
myItemsList.setAdapter(myItemsAdapter);
for (int i = 0; i<100; i++){
myItemsAdapter.arrayList.remove((5));
}
arrayList.add(new MyItems("Maxx)", R.drawable.plus));
myItemsAdapter.notifyDataSetChanged();
myItemsAdapter.notifyDataSetInvalidated();
myItemsList.setOnItemClickListener((parent, view, position, id) -> {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_SHORT)
.show();
myItemsAdapter.arrayList.remove((position-1));
myItemsAdapter.notifyDataSetChanged();
myItemsList.invalidateViews();
myItemsAdapter.notifyDataSetInvalidated();
});
}
ListView myItemsList;
ArrayList<MyItems> arrayList = new ArrayList<>();
MyItemsAdapter myItemsAdapter = new MyItemsAdapter(MyItemsActivity.this, arrayList);
public void addNewItem(View view) {
AlertDialog.Builder dialog = new AlertDialog.Builder(MyItemsActivity.this);
dialog.setView(R.layout.add_new_item);
AlertDialog alertDialog = dialog.create();
ListView a = alertDialog.getListView();
alertDialog.show();
myItemsList.invalidateViews();
}
public void addNewItemButtonClicked(View view){
LayoutInflater inflater = getLayoutInflater();
View v = inflater.inflate(R.layout.add_new_item, null);
EditText nameOfItem = v.findViewById(R.id.nameOfItem);
arrayList.add(new MyItems(nameOfItem.getText().toString(), R.drawable.forwardbutton));
myItemsAdapter.notifyDataSetChanged();
myItemsAdapter.notifyDataSetInvalidated();
}
public void notificationClicked(View view){
Toast.makeText(getApplicationContext(),
"Notification clicked", Toast.LENGTH_SHORT)
.show();
}
public void openMenu(View view) {
Intent intent = new Intent(getBaseContext(), MenuActivity.class);
startActivity(intent);
}
}
Adapter
class MyItemsAdapter extends BaseAdapter {
ArrayList<MyItems> arrayList;
Context context;
public MyItemsAdapter(Context context, ArrayList<MyItems> 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) {
observer.onChanged();
super.registerDataSetObserver(observer);
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
super.unregisterDataSetObserver(observer);
observer.onInvalidated();
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public MyItems getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final MyItems myItems = arrayList.get(position);
if(convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
convertView = layoutInflater.inflate(R.layout.example_of_list_of_items, parent, false);
TextView nameOfItem = convertView.findViewById(R.id.exampleTextView);
ImageView itemCircle = convertView.findViewById(R.id.exampleImageViewIcon);
ImageView trash = convertView.findViewById(R.id.exampleImageViewTrash);
nameOfItem.setText(myItems.itemName);
itemCircle.setImageResource(myItems.itemImage);
trash.setImageResource(R.drawable.trash);
trash.setOnClickListener(v -> {
Toast.makeText(context, "lol "+position, Toast.LENGTH_SHORT).show();
arrayList.remove(position);
notifyDataSetChanged();
notifyDataSetInvalidated();
});
}
return convertView;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return arrayList.size();
}
#Override
public boolean isEmpty() {
return false;
}
}
MyItems code
class MyItems {
String itemName;
int itemImage;
public MyItems(String itemName, int image) {
this.itemName = itemName;
this.itemImage = image;
}
}
Example of item
<?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:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/exampleTextView"
android:layout_width="170dp"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="85dp"
android:fadingEdge="horizontal|vertical"
android:layoutDirection="inherit"
android:lineSpacingExtra="14sp"
android:text="TextView"
android:textAlignment="textStart"
android:textColor="#000000"
android:textSize="20sp"
app:autoSizeMaxTextSize="20sp"
app:autoSizeMinTextSize="8sp"
app:layout_constraintEnd_toStartOf="#+id/exampleImageViewTrash"
app:layout_constraintStart_toEndOf="#+id/exampleImageViewLeft"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/exampleImageViewLeft"
android:layout_width="25dp"
android:layout_height="23dp"
android:layout_marginStart="32dp"
android:layout_marginTop="24dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#mipmap/ic_launcher_round" />
<ImageView
android:id="#+id/exampleImageViewTrash"
android:layout_width="49dp"
android:layout_height="47dp"
android:layout_marginTop="12dp"
android:layout_marginEnd="20dp"
android:cropToPadding="true"
android:fitsSystemWindows="true"
android:focusableInTouchMode="false"
android:focusable="false"
android:clickable="false"
android:scaleType="centerInside"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/trash" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintGuide_begin="70dp"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
Code of main screen
<?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:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="99dp">
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintGuide_begin="127dp"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/myItemsTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/my_items"
android:textColor="#000000"
android:textSize="36sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/menuImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:clickable="true"
android:focusable="true"
android:onClick="openMenu"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/menu" />
<ImageView
android:id="#+id/notificationImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:clickable="true"
android:focusable="true"
android:onClick="notificationClicked"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/notification" />
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/ListOfMyItems"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_marginStart="1dp"
android:layout_marginTop="30dp"
android:layout_marginEnd="1dp"
android:layout_marginBottom="100dp"
android:alwaysDrawnWithCache="true"
android:animateLayoutChanges="true"
android:choiceMode="singleChoice"
android:clickable="false"
android:clipToPadding="false"
android:descendantFocusability="beforeDescendants"
android:dividerHeight="1dp"
android:footerDividersEnabled="true"
android:headerDividersEnabled="true"
android:isScrollContainer="true"
android:layoutDirection="ltr"
android:scrollbars="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
tools:listfooter="#android:layout/simple_list_item_1">
</ListView>
<LinearLayout
android:layout_width="409dp"
android:layout_height="70dp"
android:layout_marginStart="1dp"
android:layout_marginTop="1dp"
android:layout_marginEnd="1dp"
android:focusable="auto"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/ListOfMyItems">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusable="true">
<TextView
android:id="#+id/addNewItemTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="-1dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="70dp"
android:clickable="true"
android:focusable="true"
android:onClick="addNewItem"
android:text="#string/add_new_item"
android:textColor="#000000"
android:textSize="30sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/plusImageView"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/plusImageView"
android:layout_width="67dp"
android:layout_height="74dp"
android:layout_marginStart="56dp"
android:clickable="false"
android:focusable="true"
android:onClick="addNewItem"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/plus" />
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
Code for AlertDialog adding new item
<?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="300dp"
android:orientation="vertical">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="300dp"
android:background="#FFFFFF">
<EditText
android:id="#+id/nameOfItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:ems="10"
android:hint="Enter name"
android:inputType="textPersonName"
android:singleLine="true"
android:textColor="#000000"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:layout_marginTop="9dp"
android:background="#android:drawable/btn_default_small"
android:onClick="addNewItemButtonClicked"
android:text="Button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/nameOfItem" />
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
Looks like your data is not properly updated inside the Adapter's getView method.
You should try to update the item inside the Adapter when contentView is not null.
For performance reason, there is a pattern called ViewHolder used inside the adapter. Refer to Android listview using ViewHolder for more info. Just create Holder when contentView is null and set the data when it isn't. Hope it helps.
P.S. ListView is considered deprecated. Use RecyclerView instead. It has already built-in ViewHolder pattern and is more flexible

Why UI not displaying properly?

I am making an android cv app but I want to implement the UI shown in the screenshot.
screenshot of ui I want
below current UI from real device
current ui
The XML layout where I have implemented my UI, which consists of an ImageView and some TextViews which shows subjects. I have implemented all the tasks but UI is not showing how I want it to show.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorBlust"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:orientation="horizontal">
<ImageView
android:id="#+id/educationImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:src="#drawable/education_information"
tools:ignore="ContentDescription" />
<TextView
android:id="#+id/education_info"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:text="#string/education_information"
android:textColor="#color/colorWhite"
android:textSize="20sp" />
</LinearLayout>
<TextView
android:id="#+id/duration"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginStart="12dp"
android:layout_marginLeft="12dp"
android:text="#string/text_duration"
android:textColor="#color/colorWhite"
android:textSize="16sp" />
<TextView
android:id="#+id/institution"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginStart="12dp"
android:layout_marginLeft="12dp"
android:text="#string/text_institution"
android:textColor="#color/colorWhite"
android:textSize="16sp" />
<TextView
android:id="#+id/degree"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginStart="12dp"
android:layout_marginLeft="12dp"
android:text="#string/text_degree"
android:textColor="#color/colorWhite"
android:textSize="16sp" />
<Space
android:layout_width="50dp"
android:layout_height="50dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/subjectImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginStart="20dp"
android:layout_marginLeft="20dp"
android:src="#drawable/university_subjects"
tools:ignore="ContentDescription" />
<TextView
android:id="#+id/subjects"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginStart="100dp"
android:layout_marginLeft="100dp"
android:text="#string/university_subjects"
android:textColor="#color/colorWhite"
android:textSize="20sp" />
<include
layout="#layout/subject_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/subjects"
android:layout_marginTop="60dp" />
</RelativeLayout>
</LinearLayout>
</LinearLayout>
I have created another adapter and created dummy data in subjectivity
below adapter class
public class SubjectAdapter extends RecyclerView.Adapter<SubjectAdapter.ViewHolder> {
private SubjectActivity subjectActivity;
private int [] subjectImage;
String[] subjectText;
List<FakeData> fakeData;
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView subjects;
public ImageView subjectImage;
public ViewHolder(View view) {
super(view);
subjectImage = (ImageView) view.findViewById(R.id.subjectImage);
subjects = (TextView) view.findViewById(R.id.subjects);
}
}
public SubjectAdapter(SubjectActivity subjectActivity, int []subjectImage, String [] subjectText, List<FakeData> fakeData){
this.subjectActivity = subjectActivity;
this.subjectImage = subjectImage;
this.subjectText = subjectText;
this.fakeData = fakeData;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.subject_list, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
FakeData fake = fakeData.get(position);
Picasso.get().load(fake.getImage()).
into(holder.subjectImage);
holder.subjects.setText(fake.getSubjects());
}
// TODO Auto-generated constructor stub
#Override
public int getItemCount() {
return fakeData.size() ;
}
}
below subject XML where I have hosted RecyclerView
<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.support.v7.widget.RecyclerView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
</android.support.v7.widget.RecyclerView>
below subject_list.xml where I have host items
<?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="match_parent"
android:background="#color/colorBlust"
android:orientation="horizontal" >
<ImageView
android:id="#+id/icon"
android:layout_width="60dp"
android:layout_marginLeft="10dp"
android:layout_height="60dp"
android:padding="5dp"
android:src="#drawable/computer_science"
android:layout_marginStart="10dp" />
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/computers_science"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:padding="2dp"
android:textColor="#color/colorWhite" />
</LinearLayout>
I have created fake data in order to host other images and texts
below fakeModel class
public class FakeData {
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getSubjects() {
return subjects;
}
public void setSubjects(String subjects) {
this.subjects = subjects;
}
String image;
String subjects;
}
below adapter class where I have extended with RecyclerView
public class SubjectAdapter extends RecyclerView.Adapter {
private SubjectActivity subjectActivity;
private int [] subjectImage;
String[] subjectText;
List<FakeData> fakeData;
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView subjects;
public ImageView subjectImage;
public ViewHolder(View view) {
super(view);
subjectImage = (ImageView) view.findViewById(R.id.subjectImage);
subjects = (TextView) view.findViewById(R.id.subjects);
}
}
public SubjectAdapter(SubjectActivity subjectActivity, int []subjectImage, String [] subjectText, List<FakeData> fakeData){
this.subjectActivity = subjectActivity;
this.subjectImage = subjectImage;
this.subjectText = subjectText;
this.fakeData = fakeData;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.subject_list, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
FakeData fake = fakeData.get(position);
Picasso.get().load(fake.getImage()).
into(holder.subjectImage);
holder.subjects.setText(fake.getSubjects());
}
// TODO Auto-generated constructor stub
#Override
public int getItemCount() {
return fakeData.size() ;
}
}
below My Subject class where I have implemented fake images and data
public class SubjectActivity extends Activity {
List<FakeData> fakeData;
int [] subjectImage = {R.drawable.computer_science,
R.drawable.data_structure,
};
ListView list;
String[] subjectText = {
"Computer Science",
"Data Structure",
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.subject);
RecyclerView recyclerView= (RecyclerView) findViewById(R.id.list);
SubjectAdapter adapter = new SubjectAdapter(SubjectActivity.this, subjectImage,
subjectText, fakeData);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(adapter);
}
}
This looks like you only have used Android Studio's drag and drop feature to position the UI elements. The problem is, Android Studio shows those UI elements in a generic device, which wont match all devices. When I was starting off with Android, this document helped me a lot to understand how elements in the UI must be placed.
https://developer.android.com/studio/write/layout-editor
You XML is malformed. Your LinearLayout orientation is wrong:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
It should be vertical.
Then validate its content. You have multiple RelativeLayout with orientation attribute.
It should be LinearLayout instead. RelativeLayouts don’t have orientation.
Besides those errors, your layout is very complex and have a deep hierarchy. This will lead to performance issues. My suggestion to you is to learn how to use ConstraintLayout.
The learning curve is a bit high, but it will be worth it!

StaggeredGridLayoutManager changing item size on scroll

I am searching for a long time on net. But no use. Please help or try to give some ideas how to solve this problem.
1. Bug Description
image link:https://i.stack.imgur.com/ixvdB.jpg
"left":Run the apk
"Right":When I swipe down, the size of the items is changing.
2. Code
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
List<Member> memberList = new ArrayList<>();
memberList.add(new Member(1, R.drawable.baishatunbeach1, "白沙屯海灘1"));
//add Members
recyclerView.setAdapter(new MemberAdapter(this, memberList));
}
private class MemberAdapter extends RecyclerView.Adapter<MemberAdapter.ViewHolder> {
private Context context;
private List<Member> memberList;
MemberAdapter(Context context, List<Member> memberList) {
this.context = context;
this.memberList = memberList;
}
#Override
public MemberAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.recyclerview_cardview_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(MemberAdapter.ViewHolder holder, int position) {
final Member member = memberList.get(position);
holder.imageId.setImageResource(member.getImage());
holder.textId.setText(String.valueOf(member.getId()));
holder.textName.setText(member.getName());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ImageView imageView = new ImageView(context);
imageView.setImageResource(member.getImage());
Toast toast = new Toast(context);
toast.setView(imageView);
toast.setDuration(Toast.LENGTH_SHORT);
toast.show();
}
});
}
#Override
public int getItemCount() {
return memberList.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
ImageView imageId;
TextView textId, textName;
ViewHolder(View itemView) {
super(itemView);
imageId = (ImageView) itemView.findViewById(R.id.imageId);
textId = (TextView) itemView.findViewById(R.id.textId);
textName = (TextView) itemView.findViewById(R.id.textName);
}
}
}
}
activity_main.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
recyclerview_cardview_item.xml
<android.support.v7.widget.CardView
android:id="#+id/cardview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="6dp"
android:padding="6dp"
app:cardBackgroundColor="#ffdddddd"
app:cardCornerRadius="28dp"
app:cardElevation="6dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/imageId"
android:layout_width="120dp"
android:layout_height="160dp"
android:layout_marginStart="16dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/textId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:layout_marginStart="20dp" />
<TextView
android:id="#+id/textName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:layout_marginStart="24dp" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
You need to change the height of cardview and linearlayout to wrap_content
<android.support.v7.widget.CardView
android:id="#+id/cardview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="6dp"
android:padding="6dp"
app:cardBackgroundColor="#ffdddddd"
app:cardCornerRadius="28dp"
app:cardElevation="6dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

RecyclerView is loading Images but TextView on scroll

I want to display my Pizza & Drink Objects from the Webserver, but my RecyclerView only loads the images directly and the TextViews on Scroll.
I am calling notifyDataSetChanged() for each adapter and even notify the adapters for each of their items with an iteration. I am using Glide to Transform my Images.
Why do my TextViews not load?
MainActivity.java
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
PizzaDataAdapter pizzaDataAdapter;
DrinkDataAdapter drinkDataAdapter;
CartDataAdapter cartDataAdapter;
ImageView emptyListImageView;
TextView emptyListTextView;
Toolbar mActionBarToolbar;
ConstraintLayout cartIntLayout;
RecyclerView product_recyclerview;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_food:
mActionBarToolbar.setTitle("Pizzas");
FrameLayout pizzas_layout = findViewById(R.id.pizzas_layout);
FrameLayout drinks_layout = findViewById(R.id.drinks_layout);
ConstraintLayout cart_layout = findViewById(R.id.cart_layout);
drinks_layout.setVisibility(GONE);
cart_layout.setVisibility(GONE);
pizzas_layout.setVisibility(View.VISIBLE);
return true;
case R.id.navigation_drinks:
mActionBarToolbar.setTitle("Drinks");
drinks_layout = findViewById(R.id.drinks_layout);
pizzas_layout = findViewById(R.id.pizzas_layout);
cart_layout = findViewById(R.id.cart_layout);
pizzas_layout.setVisibility(GONE);
cart_layout.setVisibility(GONE);
drinks_layout.setVisibility(View.VISIBLE);
return true;
case R.id.navigation_cart:
mActionBarToolbar.setTitle("Cart");
pizzas_layout = findViewById(R.id.pizzas_layout);
drinks_layout = findViewById(R.id.drinks_layout);
cart_layout = findViewById(R.id.cart_layout);
initCartViews();
pizzas_layout.setVisibility(GONE);
drinks_layout.setVisibility(GONE);
cart_layout.setVisibility(View.VISIBLE);
return true;
}
return false;
}
};
public static void start(Context context) {
Intent starter = new Intent(context, MainActivity.class);
context.startActivity(starter);
}
#Override
protected void onCreate(Bundle savedInstanceState) throws NullPointerException {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cartIntLayout = findViewById(R.id.cart_int_layout);
cartIntLayout.bringToFront();
mActionBarToolbar = findViewById(R.id.my_toolbar);
mActionBarToolbar.setTitle("Pizzas");
mActionBarToolbar.setTitleTextColor(getResources().getColor(R.color.white, this.getTheme()));
setSupportActionBar(mActionBarToolbar);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
PizzaLoadingTask.TaskListener pizzaListener = new PizzaLoadingTask.TaskListener() {
#Override
public void onComplete(List<Pizza> pizzas) {
if (pizzas.isEmpty()) {
initViewsWithEmptyList();
}
initPizzaViews(pizzas);
}
};
new PizzaLoadingTask(pizzaListener, APIClient.getInstance()).execute();
DrinkLoadingTask.TaskListener drinkListener = new DrinkLoadingTask.TaskListener() {
#Override
public void onComplete(List<Drink> drinks) {
if (drinks.isEmpty()) {
initViewsWithEmptyList();
}
initDrinkViews(drinks);
}
};
new DrinkLoadingTask(drinkListener, APIClient.getInstance()).execute();
}
private void initPizzaViews(List<Pizza> pizzas) {
pizzaDataAdapter = new PizzaDataAdapter(pizzas);
recyclerView = findViewById(R.id.card_recycler_view_pizzas);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new DividerItemDecoration(getBaseContext(),
DividerItemDecoration.VERTICAL));
pizzaDataAdapter.notifyDataSetChanged();
recyclerView.setAdapter(pizzaDataAdapter);
}
private void initDrinkViews(List<Drink> drinks) {
recyclerView = findViewById(R.id.card_recycler_view_drinks);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new DividerItemDecoration(getBaseContext(),
DividerItemDecoration.VERTICAL));
drinkDataAdapter = new DrinkDataAdapter(drinks);
drinkDataAdapter.notifyDataSetChanged();
recyclerView.setAdapter(drinkDataAdapter);
}
private void initCartViews() {
product_recyclerview = findViewById(R.id.cart_products_recyclerview);
product_recyclerview.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
product_recyclerview.setLayoutManager(layoutManager);
cartDataAdapter = new CartDataAdapter(pizzaDataAdapter.getCartPizzas(), drinkDataAdapter.getCartDrinks());
product_recyclerview.setAdapter(cartDataAdapter);
}
private void initViewsWithEmptyList() {
recyclerView = findViewById(R.id.card_recycler_view_drinks);
recyclerView.setVisibility(GONE);
emptyListImageView = findViewById(R.id.pizza_image_empty_list);
emptyListTextView = findViewById(R.id.pizza_empty_textview);
emptyListImageView.setVisibility(View.VISIBLE);
emptyListTextView.setVisibility(View.VISIBLE);
}
#Override
public void onBackPressed() {
super.onBackPressed();
SharedPreferences preferences = getSharedPreferences("loginRecognizer", MODE_PRIVATE);
if (preferences.contains("loggedIn")) {
Intent i = new Intent(this, LoginActivity.class); // Your list's Intent
i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NO_HISTORY); // Adds the FLAG_ACTIVITY_NO_HISTORY flag
startActivity(i);
}
}
}
PizzaDataAdapter.java (DrinkDataAdapter same but just with Drink-Objects)
public class PizzaDataAdapter extends RecyclerView.Adapter<PizzaDataAdapter.ViewHolder> {
private List<Pizza> pizzas;
//TODO implement cartDrinks LinkedList
private List<Pizza> cartPizzas = new LinkedList<>();
PizzaDataAdapter(List<Pizza> pizzas) {
this.pizzas = pizzas;
}
private static BigDecimal round(float d) {
BigDecimal bd = new BigDecimal(Float.toString(d));
bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
return bd;
}
#Override
public PizzaDataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.pizza_card_row, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(PizzaDataAdapter.ViewHolder viewHolder, int position) {
final Pizza pizza = pizzas.get(position);
// viewHolder.setIsRecyclable(false);
//viewHolder.pizza_image.setText(pizzas.get(i).getId().toString());
viewHolder.pizza_name.setText(pizza.getName());
BigDecimal result = round(pizza.getPrice());
String price = "Price: " + result.toString();
viewHolder.pizza_price.setText(price);
GlideApp.with(viewHolder.pizza_image.getContext())
.load(pizzas.get(position).getImagepath())
.apply(RequestOptions.circleCropTransform())
.into(viewHolder.pizza_image);
viewHolder.pizza_layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(viewHolder.pizza_layout.getContext(), PizzaDetailActivity.class);
intent.putExtra("Name", pizzas.get(position).getName());
intent.putExtra("Price", pizzas.get(position).getPrice());
intent.putExtra("Ingredients", pizzas.get(position).getIngredients());
viewHolder.pizza_layout.getContext().startActivity(intent);
}
});
viewHolder.plus_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cartPizzas.add(pizzas.get(position));
}
});
}
#Override
public int getItemCount() {
return pizzas.size();
}
public List<Pizza> getCartPizzas() {
return cartPizzas;
}
class ViewHolder extends RecyclerView.ViewHolder {
private ImageView pizza_image;
private TextView pizza_name, pizza_price;
private ImageButton plus_button;
private ConstraintLayout pizza_layout;
ViewHolder(View view) {
super(view);
pizza_image = view.findViewById(R.id.pizza_image);
pizza_name = view.findViewById(R.id.pizza_name);
pizza_price = view.findViewById(R.id.pizza_price);
plus_button = view.findViewById(R.id.pizza_plus_button);
pizza_layout = view.findViewById(R.id.pizza_card_row_layout);
}
}
}
PizzaLoadingTask.java
public class PizzaLoadingTask extends AsyncTask<Void, Void, List<Pizza>> {
private APIClient apiClient;
private TaskListener mListener;
public PizzaLoadingTask(TaskListener listener, APIClient apiClient){
this.mListener=listener;
this.apiClient = apiClient;
}
#Override
protected List<Pizza> doInBackground(Void... voids) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(APIInterface.baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIInterface request = retrofit.create(APIInterface.class);
Call<List<Pizza>> call = request.getPizzas();
try {
Response<List<Pizza>> jsonResponse = call.execute();
return jsonResponse.body();
// return Collections.emptyList();
} catch (IOException | NullPointerException e) {
e.printStackTrace();
return Collections.emptyList();
}
}
#Override
protected void onPostExecute(List<Pizza> pizzas) {
mListener.onComplete(pizzas);
}
public interface TaskListener {
void onComplete(List<Pizza> pizzas);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".screens.MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.constraint.ConstraintLayout
android:id="#+id/navigation_layout"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/navigation"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/my_toolbar"
app:layout_constraintVertical_bias="0.0">
<include
android:id="#+id/pizzas_layout"
layout="#layout/pizza_products"
android:visibility="visible" />
<include
android:id="#+id/drinks_layout"
layout="#layout/drink_products"
android:visibility="invisible" />
<include
android:id="#id/cart_layout"
layout="#layout/product_cart"
android:visibility="invisible" />
</android.support.constraint.ConstraintLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="0dp"
android:layout_marginStart="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/navigation">
</android.support.design.widget.BottomNavigationView>
<android.support.constraint.ConstraintLayout
android:id="#+id/cart_int_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="57dp"
android:layout_marginTop="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="#id/navigation">
<TextView
android:id="#+id/cart_int_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:textColor="#000000"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
</android.support.constraint.ConstraintLayout>
pizza_products.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pizza_products_layout"
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.apprentice.ti8m.myfirstrestclient.screens.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/card_recycler_view_pizzas"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp"
tools:listitem="#layout/pizza_card_row">
</android.support.v7.widget.RecyclerView>
<android.support.constraint.ConstraintLayout
android:id="#+id/pizza_image_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center">
<ImageView
android:id="#+id/pizza_image_empty_list"
android:layout_width="256dp"
android:layout_height="256dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:visibility="gone"
app:layout_constraintBottom_toTopOf="#+id/pizza_empty_textview"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.176"
app:layout_constraintVertical_chainStyle="spread"
app:srcCompat="#drawable/ic_pizza_empty_list"
tools:visibility="visible"
android:contentDescription="#string/image_to_show_up_if_pizza_list_is_empty" />
<TextView
android:id="#+id/pizza_empty_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pizza_list_empty"
android:visibility="gone"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/pizza_image_empty_list"
app:layout_constraintVertical_bias="0.567"
tools:visibility="visible" />
</android.support.constraint.ConstraintLayout>
</FrameLayout>
pizza_card_row.xml
<android.support.constraint.ConstraintLayout
android:id="#+id/pizza_card_row_layout"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="72dp">
<ImageView
android:id="#+id/pizza_image"
android:layout_width="40dp"
android:layout_height="40dp"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:layout_marginStart="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
tools:ignore="ContentDescription" />
<TextView
android:id="#+id/pizza_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="0dp"
android:fontFamily="sans-serif"
android:textSize="16sp"
android:textColor="#color/colorPizzaName"
app:layout_constraintHorizontal_bias="0.1"
app:layout_constraintLeft_toRightOf="#+id/pizza_image"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="#+id/pizza_image" />
<TextView
android:id="#+id/pizza_price"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="-1dp"
app:layout_constraintBottom_toBottomOf="#+id/pizza_image"
app:layout_constraintLeft_toRightOf="#+id/pizza_image"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:fontFamily="sans-serif"
android:textSize="14sp"
app:layout_constraintRight_toRightOf="parent" />
<ImageButton
android:id="#+id/pizza_plus_button"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="72dp"
android:layout_height="0dp"
android:layout_gravity="center"
android:src="#drawable/ic_add_black_24dp"
android:gravity="center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:contentDescription="#string/plus_button_for_each_recyclerview_card" />
</android.support.constraint.ConstraintLayout>
try remove this unnecessary code:
for (int i = 0; i< pizzas.size(); i++){
pizzaDataAdapter.notifyItemInserted(i);
}
since recyclerview adapter set after data complete/loaded in adapter

Categories

Resources