Adapter of recycler view causes crash and forces stop - java

When I use a recycler view and adapter, the adapter doesn't let the app to install and it causes a crash. I commented out the adapter in my main activity and it started successfully but with adapter it doesn't work.
My adapter class is here:
public class AdapterFree extends RecyclerView.Adapter<AdapterFree.ViewHolder> {
Context context;
List<ModelFree> modelFrees;
public AdapterFree(Context context, List<ModelFree> modelFrees) {
this.context = context;
this.modelFrees = modelFrees;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_free, parent, false);
return new AdapterFree.ViewHolder(view);
//return new ViewHolder(view);
//return new AdapterFree(context, modelFrees).new ViewHolder(view);
/*ViewHolder vh = new ViewHolder(view);
return vh;*/
//here I tried a few codes but didn't help
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
ModelFree free = modelFrees.get(position);
DecimalFormat decimalFormat = new DecimalFormat("###,###");
String price = decimalFormat.format(Integer.valueOf(free.getPrice()));
holder.textPriceFree.setText(price + " " + "$");
holder.textVisitFree.setText(free.getVisit());
holder.textTitle.setText(free.getTitle());
holder.textFreePrice.setText(free.getFree());
//holder.imageFree.setImageResource(free.getImage());
holder.imageFree.setImageResource(Integer.parseInt(free.getImage()));
}
#Override
public int getItemCount() {
return modelFrees.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
LinearLayout linearLayout;
CardView cardViewFree;
ImageView imageFree;
TextView textTitle, textVisitFree, textPriceFree, textFreePrice;
Typeface typeface = Typeface.createFromAsset(itemView.getContext().getAssets(), "fonts/vaziri.ttf");
public ViewHolder(#NonNull View itemView) {
super(itemView);
linearLayout = itemView.findViewById(R.id.linearLayout);
cardViewFree = itemView.findViewById(R.id.cardViewFree);
imageFree = itemView.findViewById(R.id.imageFree);
textTitle = itemView.findViewById(R.id.textTitle);
textTitle.setTypeface(typeface);
textVisitFree = itemView.findViewById(R.id.textVisitFree);
textVisitFree.setTypeface(typeface);
textPriceFree = itemView.findViewById(R.id.textPriceFree);
textPriceFree.setTypeface(typeface);
textFreePrice = itemView.findViewById(R.id.textFreePrice);
textFreePrice.setTypeface(typeface);
}
}
}
my main activity :
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
ImageView image1;
CoordinatorLayout coordinator;
DrawerLayout drawerLayout;
NavigationView navigationView;
Toolbar mainToolbar;
RecyclerView recyclerFree, recyclerOnly, recyclerVisit, recyclerSales;
AdapterFree adapterFree;
List<ModelFree> modelFreeList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
coordinator = findViewById(R.id.coordinator);
drawerLayout = findViewById(R.id.drawerLayout);
navigationView = findViewById(R.id.navigationView);
mainToolbar = findViewById(R.id.main_toolbar);
image1 = findViewById(R.id.image1);
recyclerFree = findViewById(R.id.recyclerFree);
recyclerOnly = findViewById(R.id.recyclerOnly);
recyclerVisit = findViewById(R.id.recyclerVisit);
recyclerSales = findViewById(R.id.recyclerSales);
setSupportActionBar(mainToolbar);
ActionBarDrawerToggle toggle;
toggle = new ActionBarDrawerToggle(this, drawerLayout, mainToolbar, R.string.open, R.string.close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
Picasso.get().load(R.drawable.lexuse).into(image1);
setDataFree();
}
private void setDataFree() {
adapterFree = new AdapterFree(getApplicationContext(), modelFreeList);
recyclerFree.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false));
recyclerFree.setAdapter(adapterFree);
modelFreeList.add(new ModelFree(1, String.valueOf(R.drawable.lexus2), "lexus2", "10", "10000$", "5$"));
modelFreeList.add(new ModelFree(2, String.valueOf(R.drawable.lexus3), "lexus3", "20", "20000$", "6$"));
modelFreeList.add(new ModelFree(3, String.valueOf(R.drawable.lexus3), "lexus3", "30", "30000$", "7$"));
modelFreeList.add(new ModelFree(4, String.valueOf(R.drawable.lexus4), "lexus4", "40", "40000$", "8$"));
modelFreeList.add(new ModelFree(5, String.valueOf(R.drawable.lexus5), "lexus5", "50", "50000$", "9$"));
modelFreeList.add(new ModelFree(6, String.valueOf(R.drawable.lexusd), "lexus6", "60", "60000$", "5$"));
adapterFree.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.option_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int optionId = item.getItemId();
switch (optionId) {
case R.id.page2:
startActivity(new Intent(this, MainActivity2.class));
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
my model class :
public class ModelFree {
int id;
String image;
String title;
String visit;
String price;
String free;
public ModelFree(int id, String image, String title, String visit, String price, String free) {
this.id = id;
this.image = image;
this.title = title;
this.visit = visit;
this.price = price;
this.free = free;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getVisit() {
return visit;
}
public void setVisit(String visit) {
this.visit = visit;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getFree() {
return free;
}
public void setFree(String free) {
this.free = free;
}
}
xml layout that I write recycler view:
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/purple_200"
android:id="#+id/main_toolbar"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="#+id/image1"
android:scaleType="fitXY"/>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#e7e7e7">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="60dp"
app:cardCornerRadius="10dp"
app:cardElevation="1dp"
app:cardBackgroundColor="#color/teal_200"
android:layout_marginLeft="60dp"
android:layout_marginRight="60dp"
android:layout_marginTop="20dp"
android:layout_marginBottom="10dp"
android:id="#+id/cardCategory">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal"
android:layoutDirection="rtl">
<ImageView
android:layout_width="34dp"
android:layout_height="34dp"
android:src="#drawable/ic_baseline_format_list_bulleted_24"
app:tint="#color/cardview_light_background" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:textSize="18sp"
android:textColor="#color/white"
android:text="Category"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
<androidx.appcompat.widget.AppCompatTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="16sp"
android:gravity="left"
android:text="Special Discounts"
android:textColor="#color/black"
android:layout_marginLeft="15dp"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recyclerFree"
android:layoutDirection="ltr"
android:layout_marginTop="10dp"
android:layout_marginLeft="3dp"/>
<androidx.appcompat.widget.AppCompatTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="16sp"
android:gravity="left"
android:text="Just Here"
android:textColor="#color/black"
android:layout_marginLeft="15dp"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recyclerOnly"
android:layoutDirection="ltr"
android:layout_marginTop="10dp"
android:layout_marginLeft="3dp"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_marginTop="10dp"
android:scaleType="fitXY"
android:src="#drawable/lexusa"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="140dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="15dp"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:layout_margin="1dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="#drawable/lexusb"/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:layout_margin="1dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="#drawable/lexusc"/>
</LinearLayout>
</LinearLayout>
<androidx.appcompat.widget.AppCompatTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="16sp"
android:textColor="#color/black"
android:gravity="left"
android:text="Most visited"
android:layout_marginLeft="15dp"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layoutDirection="ltr"
android:layout_marginTop="10dp"
android:layout_marginLeft="3dp"
android:id="#+id/recyclerVisit"/>
<androidx.appcompat.widget.AppCompatTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="16sp"
android:textColor="#color/black"
android:gravity="left"
android:text="Most sales"
android:layout_marginLeft="15dp"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layoutDirection="ltr"
android:layout_marginTop="10dp"
android:layout_marginLeft="3dp"
android:id="#+id/recyclerSales"/>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
my xml layout for items:
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="170dp"
android:layout_height="260dp"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:clickable="true"
android:id="#+id/cardViewFree"
android:layout_margin="4dp"
android:orientation="vertical"
app:cardCornerRadius="2dp"
app:cardElevation="1dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/linearLayout"
android:visibility="visible"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="match_parent"
android:layout_height="170dp"
android:scaleType="centerInside"
android:id="#+id/imageFree"
android:src="#drawable/lexus2"/>
</RelativeLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="start"
android:id="#+id/textTitle"
android:layout_margin="3dp"
android:gravity="left"
android:text="lexus2"
android:textColor="#color/black"
android:textSize="12dp"
android:singleLine="true" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layoutDirection="ltr"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.4"
android:gravity="center_vertical"
android:layoutDirection="ltr"
android:orientation="horizontal"
android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12dp"
android:id="#+id/textVisitFree"
android:text="10"
android:textColor="#color/black"/>
<ImageView
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_marginRight="5dp"
android:src="#drawable/ic_baseline_visibility_24"
app:tint="#color/black" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.6"
android:gravity="center_vertical|right"
android:padding="5dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textPriceFree"
android:gravity="center_vertical|right"
android:text="123000$"
android:textColor="#color/black"
android:textSize="12sp"/>
</LinearLayout>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textFreePrice"
android:padding="1dp"
android:layout_marginRight="5dp"
android:gravity="right|center_vertical"/>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>

I found the problem and solved it.
the main problem was about MaterialCardView, so I changed my codes to this:
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="170dp"
android:layout_height="260dp"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
app:cardCornerRadius="2dp"
app:cardElevation="1dp"
android:clickable="true"
android:id="#+id/cardViewFree"
android:layout_margin="4dp"
android:orientation="vertical"
android:theme="#style/Theme.MaterialComponents.DayNight"
style="#style/Widget.MaterialComponents.CardView">
<LinearLayout
............
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
after that I changed the part of the codes of Model class to this:
public class ModelFree {
int id;
int image;
String title;
String visit;
int price;
String free;
so I write some of variables to "int"
of course I changed this method in MainActivity:
private void setDataFree() {
adapterFree = new AdapterFree(getApplicationContext(), modelFreeList);
recyclerFree.setLayoutManager(new
LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL,
false));
recyclerFree.setAdapter(adapterFree);
modelFreeList.add(new ModelFree(1, R.drawable.lexus2, "lexus2", "10",
100000, "5%"));
modelFreeList.add(new ModelFree(2, R.drawable.lexus3, "lexus3", "20", 20000,
"6$"));
modelFreeList.add(new ModelFree(3, R.drawable.lexus3, "lexus3", "30", 30000,
"7$"));
modelFreeList.add(new ModelFree(4, R.drawable.lexus4, "lexus4", "40", 40000,
"8$"));
modelFreeList.add(new ModelFree(5, R.drawable.lexus5, "lexus5", "50", 50000,
"9$"));
modelFreeList.add(new ModelFree(6, R.drawable.lexusd, "lexus6", "60", 60000,
"5$"));
adapterFree.notifyDataSetChanged();
}
finally I commented some lines in Adapter class because they caused error and I couldn't solve that:
public class MyViewHolder extends RecyclerView.ViewHolder {
LinearLayout linearLayout;
CardView cardViewFree;
ImageView imageFree;
TextView textTitle, textVisitFree, textPriceFree, textFreePrice;
//Typeface typeface =
Typeface.createFromAsset(itemView.getContext().getAssets(),
String.valueOf(R.font.times));
public MyViewHolder(#NonNull View itemView) {
super(itemView);
linearLayout = itemView.findViewById(R.id.linearLayout);
cardViewFree = itemView.findViewById(R.id.cardViewFree);
imageFree = itemView.findViewById(R.id.imageFree);
textTitle = itemView.findViewById(R.id.textTitle);
//textTitle.setTypeface(typeface);
textVisitFree = itemView.findViewById(R.id.textVisitFree);
//textVisitFree.setTypeface(typeface);
textPriceFree = itemView.findViewById(R.id.textPriceFree);
//textPriceFree.setTypeface(typeface);
textFreePrice = itemView.findViewById(R.id.textFreePrice);
//textFreePrice.setTypeface(typeface);
}
}

Related

inputData to send data to mainActivity error using Realm Database instant crash

I have a problem that when I press the Fab button the app instant close and I don't know how to fix it, my goal was when pressing the fab button and inserting the data it will send the data to the MainActivity.xml and make a list of item
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="10dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Income"
android:textSize="24dp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="0"
android:textSize="20dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="10dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Expenses"
android:textSize="24dp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="0"
android:textSize="20dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="10dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Balance"
android:textSize="24dp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="0"
android:textSize="20dp" />
</LinearLayout>
</LinearLayout>
<ListView
android:id="#+id/listView"
app:layout_anchor="#id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="80dp">
</ListView>
<com.google.android.material.bottomappbar.BottomAppBar
android:id="#+id/bottomAppBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:fabCradleMargin="10dp"
app:fabCradleVerticalOffset="10dp"
app:fabCradleRoundedCornerRadius="20dp"
android:layout_gravity="bottom">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/bottomNavigationView"
app:menu="#menu/bottom_nav_menu"
android:layout_marginEnd="10dp"/>
</com.google.android.material.bottomappbar.BottomAppBar>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fab"
android:src="#drawable/add_button"
app:layout_anchor="#id/bottomAppBar"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
activity_input_data.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"
tools:context=".InputDataActivity">
<LinearLayout
android:layout_marginTop="200dp"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:layout_marginBottom="200dp"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textAlignment="center"
android:textSize="50dp"
android:textStyle="bold"
android:text="Input Data"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/txtTitle"
android:hint="Title..."
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/txtAmount"
android:hint="Amount..."
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/txtDate"
android:hint="Date..."
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/addButton"
android:text="Add"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
list_item.xml
<?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="horizontal"
android:padding="20dp">
<ImageView
android:src="#drawable/profile_button"
android:layout_width="50dp"
android:layout_height="50dp"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/title"
android:layout_gravity="end"
android:textSize="16dp"
android:textStyle="bold"
android:text="Main Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/amount"
android:layout_gravity="end"
android:textSize="14dp"
android:textStyle="bold"
android:text="Rp. 20.000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/date"
android:layout_gravity="end"
android:textSize="12dp"
android:textStyle="bold"
android:text="23-06-2021"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/spinner"
android:layout_gravity="end"
android:textSize="14dp"
android:textStyle="bold"
android:text="Expense"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView listView;
MyHelper myHelper;
BottomNavigationView bottomNavigationView;
FloatingActionButton floatingActionButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNavigationView = findViewById(R.id.bottomNavigationView);
floatingActionButton = findViewById(R.id.fab);
//ListView Adapter
ListViewAdapter adapter = new ListViewAdapter(this, myHelper.justRefresh());
listView.setAdapter(adapter);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, InputDataActivity.class);
startActivity(intent);
}
});
//Bottom Nav
bottomNavigationView.setBackground(null);
bottomNavigationView.getMenu().getItem(2).setEnabled(false);
}
}
InputDataActivity.java
public class InputDataActivity extends AppCompatActivity {
EditText txtTitle, txtAmount,txtDate;
Button button;
Realm realm;
ListView listView;
MyHelper myHelper;
RealmChangeListener realmChangeListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_input_data);
realm = Realm.getDefaultInstance();
txtTitle = findViewById(R.id.txtTitle);
txtAmount = findViewById(R.id.txtAmount);
txtDate = findViewById(R.id.txtDate);
button = findViewById(R.id.addButton);
listView = findViewById(R.id.listView);
//MyHelper
myHelper = new MyHelper(realm);
myHelper.selectFromDB();
//ListView Adapter
ListViewAdapter adapter = new ListViewAdapter(this, myHelper.justRefresh());
listView.setAdapter(adapter);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveData();
}
});
Refresh();
}
private void saveData(){
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Number maxId = realm.where(User.class).max("title_id");
int newKey = (maxId == null) ? 1 : maxId.intValue()+1;
User user = realm.createObject(User.class, newKey);
user.setTitle_name(txtTitle.getText().toString());
user.setAmount(txtAmount.getText().toString());
user.setDate(txtDate.getText().toString());
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Toast.makeText(InputDataActivity.this, "Success", Toast.LENGTH_SHORT).show();
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
Toast.makeText(InputDataActivity.this, "Fail", Toast.LENGTH_SHORT).show();
}
});
}
private void Refresh(){
realmChangeListener = new RealmChangeListener() {
#Override
public void onChange(Object o) {
ListViewAdapter adapter = new ListViewAdapter(InputDataActivity.this, myHelper.justRefresh());
listView.setAdapter(adapter);
}
};
realm.addChangeListener(realmChangeListener);
}
#Override
protected void onDestroy() {
super.onDestroy();
realm.removeChangeListener(realmChangeListener);
realm.close();
}
}
MyHelper.java
public class MyHelper {
Realm realm;
RealmResults<User> users;
public MyHelper(Realm realm) {
this.realm = realm;
}
public void selectFromDB(){
users = realm.where(User.class).findAll();
}
public ArrayList<User> justRefresh(){
ArrayList<User> listItem = new ArrayList<>();
for(User user: users){
listItem.add(user);
}
return listItem;
}
}
User.java
public class User extends RealmObject {
#PrimaryKey
private int title_id;
private String title_name;
private String amount;
private String date;
private String spinner;
public int getTitle_id() {
return title_id;
}
public void setTitle_id(int title_id) {
this.title_id = title_id;
}
public String getTitle_name() {
return title_name;
}
public void setTitle_name(String title_name) {
this.title_name = title_name;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getSpinner() {
return spinner;
}
public void setSpinner(String spinner) {
this.spinner = spinner;
}
}
ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
Context context;
ArrayList<User> users;
public ListViewAdapter(Context context, ArrayList<User> users) {
this.context = context;
this.users = users;
}
#Override
public int getCount() {
return users.size();
}
#Override
public Object getItem(int position) {
return users.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater =(LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
view =inflater.inflate(R.layout.list_item, parent,false);
TextView title,amount,date,spinner;
title =view.findViewById(R.id.title);
amount = view.findViewById(R.id.amount);
date = view.findViewById(R.id.date);
spinner = view.findViewById(R.id.spinner);
User u = (User)this.getItem(position);
title.setText(u.getTitle_name());
amount.setText(u.getAmount());
date.setText(u.getDate());
spinner.setText(u.getSpinner());
int numPosition = u.getTitle_id();
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// for update
}
});
return view;
}
}
if someone can help, Thank you because I'm stuck here. my goal is to make Money Management

android- Show multiple images in one imageView?

I need to create a chat view like below image. if there are members more than 3, need to show number. But images need to retrieved from URL. i have done a research but can't find any example. here i have set one Image in a imageView.Can anyone help me?
ChatAdapter.xml
<?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"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/chat_list_border"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:id="#+id/view_background"
android:padding="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.AppCompatTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="end|center"
android:gravity="end|center"
android:text="#string/delete"
android:textColor="#color/white"
android:textSize="15sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/view_foreground"
android:padding="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10sp"
android:orientation="horizontal">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/chat_image"
android:layout_width="50sp"
android:layout_height="50sp"
android:layout_gravity="center"
android:layout_weight="0" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginEnd="5dp"
android:layout_weight="1"
android:orientation="vertical">
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/chat_name"
style="#style/defaultTextStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="#font/abhaya_libre_extra_bold"
android:textColor="#color/defaultTextColor"
android:textSize="16sp" />
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/chat_message"
style="#style/defaultTextStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textColor="#color/defaultTextColor"
android:fontFamily="#font/abhaya_libre_semi_bold"
android:textSize="14sp" />
</LinearLayout>
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/chat_date"
style="#style/defaultTextStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginStart="5dp"
android:layout_marginEnd="5dp"
android:layout_weight="0"
android:gravity="center"
android:text=""
android:textColor="#color/black"
android:textSize="14sp" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="0.5dp"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="5dp" />
</LinearLayout>
</FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
ChatAdapter.java
public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ViewHolder> {
Context context;
List<ChatList> chatLists;
public ChatAdapter(Context context, List<ChatList> chatLists) {
this.context = context;
this.chatLists = chatLists;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_adapter, null, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
ChatList item = chatLists.get(position);
holder.name.setText(item.getName());
holder.message.setText(item.getMessage());
holder.date.setText(item.getDate());
Glide.with(context)
.load(item.getImage())
.fitCenter()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.into(holder.image);
holder.itemView.setOnClickListener(view -> {
Intent intent = new Intent(context, ChatMessageActivity.class);
intent.putExtra("chatname", item.getName());
context.startActivity(intent);
});
}
public void removeItem(int position) {
chatLists.remove(position);
notifyItemRemoved(position);
}
public void restoreItem(ChatList item, int position) {
chatLists.add(position, item);
notifyItemInserted(position);
}
public List<ChatList> getData() {
return chatLists;
}
#Override
public int getItemCount() {
return chatLists.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircleImageView image;
AppCompatTextView name, message, date;
public LinearLayout forground, background;
public ViewHolder(#NonNull View itemView) {
super(itemView);
image = itemView.findViewById(R.id.chat_image);
name = itemView.findViewById(R.id.chat_name);
message = itemView.findViewById(R.id.chat_message);
date = itemView.findViewById(R.id.chat_date);
forground = itemView.findViewById(R.id.view_foreground);
background = itemView.findViewById(R.id.view_background);
}
}
}
ChatList.java
public class ChatList {
String name, message, date, image;
public ChatList(String name, String message, String date, String image) {
this.name = name;
this.message = message;
this.date = date;
this.image = image;
}
public String getName() {
return name;
}
public String getMessage() {
return message;
}
public String getDate() {
return date;
}
public String getImage() {
return image;
}
}
here is my chatListData
ChatList list = new ChatList("Ellen, Grandpa + 1", "Thanks for letting us know!", "Jan 04", "https://media.istockphoto.com/photos/senior-adult-male-laughing-portrait-he-is-90-years-old-picture-id155357459?k=6&m=155357459&s=612x612&w=0&h=E_uK43zNoAnt9ohSdYMbNgCyFJliuKIzTynduh7d-Ck=");
chatLists.add(list);
list = new ChatList("Ellen, Grandpa + 1", "Thanks for letting us know!", "Jan 04", "https://media.istockphoto.com/photos/senior-adult-male-laughing-portrait-he-is-90-years-old-picture-id155357459?k=6&m=155357459&s=612x612&w=0&h=E_uK43zNoAnt9ohSdYMbNgCyFJliuKIzTynduh7d-Ck=");
chatLists.add(list);
list = new ChatList("Ellen, Grandpa + 1", "Thanks for letting us know!", "Jan 04", "https://media.istockphoto.com/photos/senior-adult-male-laughing-portrait-he-is-90-years-old-picture-id155357459?k=6&m=155357459&s=612x612&w=0&h=E_uK43zNoAnt9ohSdYMbNgCyFJliuKIzTynduh7d-Ck=");
chatLists.add(list);

How show a Horizontal Recyclerview - have trouble showing horizontal items

I want to show horizontal items in recyclerview, but I've tried but no work it all, only show me horizontal items with enlarge widh.
In Android Studio show as I want
But in runtime in my movile, show me
The items is width wraped but the other items appear after scroll right separated of my previus item.
This is my code.
LIST_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="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="#+id/linearFondo"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:background="#drawable/item_list_sel"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView2"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_gravity="center"
app:srcCompat="#drawable/ruta"
tools:srcCompat="#drawable/ruta" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="5dp"
android:orientation="vertical">
<TextView
android:id="#+id/tnombre"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:inputType="textMultiLine"
android:lines="1"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:textSize="12sp"
android:textStyle="bold"></TextView>
<TextView
android:id="#+id/thorarios"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
android:textColor="#color/colorPrimary"
android:textSize="10sp"
android:visibility="gone"></TextView>
</LinearLayout>
</LinearLayout>
</LinearLayout>
And My Xml to show the recyclerview
<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"
tools:context="sitetech.NFCcheckPoint.ui.operador.CheckFragment">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#color/SuccessColor"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<TextView
android:id="#+id/tfecha"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="Fecha"
android:textSize="20sp" />
<Button
android:id="#+id/bpruebas"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pasar Tarjeta" />
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="Ruta para el registro" />
<com.omega_r.libs.omegarecyclerview.OmegaRecyclerView
android:id="#+id/rlista"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#888"
android:dividerHeight="0dp"
android:fadeScrollbars="true"
android:orientation="horizontal"
android:overScrollMode="never"
android:scrollbarAlwaysDrawHorizontalTrack="true"
android:scrollbarAlwaysDrawVerticalTrack="false"
android:scrollbars="horizontal"
app:itemSpace="0dp"
tools:listitem="#layout/ruta_sel_template">
</com.omega_r.libs.omegarecyclerview.OmegaRecyclerView>
</LinearLayout>
</LinearLayout>
And my Fragment code to load
dataAdapter = new rutaSelAdapter(lista, new onItemClick() {
#Override
public void onClickItemList(View v, int position) {
ToastHelper.info(lista.get(position).getNombre().toString());
}
});
rlista.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
rlista.setAdapter(dataAdapter);
And my dataAdapter class
public class rutaSelAdapter extends OmegaRecyclerView.Adapter<rutaSelAdapter.ViewHolder> {
public List<Ruta> lista;
private onItemClick onItemClick;
private Ruta selectedItem;
public rutaSelAdapter(List<Ruta> l, onItemClick onclick) {
lista = l;
this.onItemClick = onclick;
if (l.size() > 0)
setSelectedItem(l.get(0));
}
#Override
public int getItemCount() {
return lista.size();
}
#Override
public rutaSelAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new rutaSelAdapter.ViewHolder(parent);
}
#Override
public void onBindViewHolder(rutaSelAdapter.ViewHolder holder, int position) {
Ruta dato = lista.get(position);
holder.display(dato);
}
public void setSelectedItem(Ruta rx){
selectedItem = rx;
}
public Ruta getSelectedItem(){
return selectedItem;
}
public void updateData(Ruta bx) {
boolean nuevo = true;
for (Ruta rx : lista) {
if (rx.getId() == bx.getId()) {
lista.set(lista.indexOf(rx), bx);
nuevo = false;
}
ToastHelper.info("Se a modificado el horario.");
}
if (nuevo) {
lista.add(bx);
ToastHelper.exito("Horario asignado.");
}
notifyDataSetChanged();
}
public void deleteData(Ruta rx) {
//ToastHelper.normal("Se a eliminado el horario " + rx.getHora());
lista.remove(rx);
notifyDataSetChanged();
}
public class ViewHolder extends SwipeViewHolder implements View.OnClickListener {
private final TextView tnombre;
private LinearLayout linearFondo;
HorarioDao horarioManager = AppController.daoSession.getHorarioDao();
private Ruta currentItem;
public ViewHolder(ViewGroup itemView) {
super(itemView, R.layout.ruta_sel_template, SwipeViewHolder.NO_ID, SwipeViewHolder.NO_ID);
tnombre = findViewById(R.id.tnombre);
linearFondo = findViewById(R.id.linearFondo);
contentView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setSelectedItem(currentItem);
onItemClick.onClickItemList(v, getAdapterPosition());
}
});
}
private Ruta backItem;
private void setSelection(Ruta rx){
//if (backItem == null)
}
#Override
public void onClick(final View v) {
}
public void display(Ruta rx) {
currentItem = rx;
if (rx.getNombre() == null) tnombre.setText("");
else tnombre.setText(rx.getNombre().toString());
}
}
}
In Android Studio show me right as I want.
But in runtime, in my mobile the items have full width but wrap content.enter image description here
i think you just add notifyDataSetChanged in your class adapter
public rutaSelAdapter(List<Ruta> l, onItemClick onclick) {
lista = l;
this.onItemClick = onclick;
if (l.size() > 0)
setSelectedItem(l.get(0));
notifyDataSetChanged();
}
In your recyclerview item layout update width of these 2 textviews [tnombre and thorarios] to wrap_content
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="5dp"
android:orientation="vertical">
<TextView
android:id="#+id/tnombre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:inputType="textMultiLine"
android:lines="1"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:textSize="12sp"
android:textStyle="bold"></TextView>
<TextView
android:id="#+id/thorarios"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
android:textColor="#color/colorPrimary"
android:textSize="10sp"
android:visibility="gone"></TextView>
</LinearLayout>
If someone else have this issue, I fixed adding this line in the fragment class.
rlista.setHasFixedSize(true);

My recycler view doesn't show all items that it has, how can I fix it?

I have something wrong with recyclerView. It doesn't show all items. For example, recyclerView has 12 items, but it shows like 10 with a half items. I can set paddingBottom for it, and it shows all items, but I don't think it is a good way. How can I fix it? I think maybe it becouse of my buttons above it.
acctivity_search_coin.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:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:paddingBottom="50dp"
app:layout_constraintTop_toBottomOf="#+id/lianerForThreeBtn" />
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:background="#FFFFFF"
android:paddingStart="5dp"
android:paddingEnd="5dp"
android:textSize="15sp"
android:drawablePadding="6dp"
android:gravity="center_vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:id="#+id/lianerForThreeBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintTop_toBottomOf="#+id/button2">
<Button
android:id="#+id/btn1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:layout_weight="1"/>
<Button
android:id="#+id/btn2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:layout_weight="1"/>
<Button
android:id="#+id/btn3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:layout_weight="1"/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
activity_recycler_view_adapter_coin_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/recyclerImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<TextView
android:id="#+id/denominationTV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_marginStart="20dp"
android:layout_marginEnd="8dp"
android:layout_toEndOf="#+id/secondIV"
android:textSize="20sp" />
<TextView
android:id="#+id/yearTV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/denominationTV"
android:layout_alignStart="#+id/denominationTV"
android:layout_alignParentEnd="true"
android:layout_marginStart="0dp"
android:layout_marginTop="6dp"
android:layout_marginEnd="8dp"
android:textSize="20sp" />
<ImageView
android:id="#+id/firstIV"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_alignParentStart="true"
android:layout_marginStart="0dp"/>
<ImageView
android:id="#+id/secondIV"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_marginStart="4dp"
android:layout_toEndOf="#+id/firstIV"/>
</RelativeLayout>
RecyclerViewAdapterCoinList.java
public class RecyclerViewAdapterCoinList extends RecyclerView.Adapter<RecyclerViewAdapterCoinList.ViewHolder> {
private List<String> mYearList;
private List<String> mDenominationList;
private List<String> mImageList1;
private List<String> mImageList2;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
Context context;
RecyclerViewAdapterCoinList(Context context, List<String> denominationList,List<String> yearList, List<String> imageList1,List<String> imageList2) {
this.mInflater = LayoutInflater.from(context);
this.mYearList = yearList;
this.mDenominationList = denominationList;
this.mImageList1 = imageList1;
this.mImageList2 = imageList2;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.activity_recycler_view_adapter_coin_list, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String year = mYearList.get(position);
String denomination = mDenominationList.get(position);
String imageString1 = mImageList1.get(position);
String imageString2 = mImageList2.get(position);
holder.denominationTV.setText(denomination);
holder.yearTV.setText(year);
try {
Glide.with(context).load(imageString1).into(holder.firstIV);
Glide.with(context).load(imageString2).into(holder.secondIV);
}catch (Exception e){e.printStackTrace();}
}
// total number of rows
#Override
public int getItemCount() {
return mDenominationList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView denominationTV;
TextView yearTV;
ImageView firstIV;
ImageView secondIV;
ViewHolder(View itemView) {
super(itemView);
denominationTV = itemView.findViewById(R.id.denominationTV);
yearTV = itemView.findViewById(R.id.yearTV);
firstIV = itemView.findViewById(R.id.firstIV);
secondIV = itemView.findViewById(R.id.secondIV);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
String getItem(int id) {
return mDenominationList.get(id);
}
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
Try adding app:layout_constraintBottom_toBottomOf="parent" in the recycler view and also make the height of the recycler view to be 0dp (match_constraint).

Why there is an error in setOnItemClickListener

I use fragment and I want to set listview in m fragment.I have error in this field.
I want to use ListView of Foldingcell, but I think I have an error in my adapter.
i can not find error.
any body can't help me?
what should I do?
this is my error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.a700daneh.a700daneh.loanFragment.onCreateView(loanFragment.java:49)
this is my element for using in listView
public class Item {
String family1;
String cost1;
String family2;
String cost2;
String explain;
String code;
int Icon;
private View.OnClickListener requestBtnClickListener;
public Item() {
}
public Item(String family1, String cost1, String family2, String cost2, String explain, String code, int Icon) {
this.family1 = family1;
this.cost1 = cost1;
this.family2 = family2;
this.cost2 = cost2;
this.explain = explain;
this.code = code;
this.Icon = Icon;
//this.time = time;
}
public String getFamily1() {
return family1;
}
public void setFamily1(String family1) {
this.family1 = family1;
}
public String getCost1() {
return cost2;
}
public void setCost1(String cost2) {
this.cost2 = cost2;
}
public String getFamily2() {
return family2;
}
public void setFamily2() {
this.family2 = family2;
}
public String getCost2() {
return cost2;
}
public void setCost2() {
this.cost2 = cost2;
}
public String getExplain() {
return explain;
}
public void setExplain() {
this.explain = explain;
}
public String getCode() {
return code;
}
public void setCode() {
this.code = code;
}
public int getIcon() {
return Icon;
}
/**
* #return List of elements prepared for tests
*/
public static ArrayList<Item> getTestingList() {
ArrayList<Item> items = new ArrayList<>();
items.add(new Item("خانواده x:", "500,000 تومان", "خانواده x:", "500,000 تومان", "توضیحات:", "کد: 12345678", R.drawable.family));
items.add(new Item("خانواده x:", "500,000 تومان", "خانواده x:", "500,000 تومان", "توضیحات:", "کد: 12345678", R.drawable.family));
items.add(new Item("خانواده x:", "500,000 تومان", "خانواده x:", "500,000 تومان", "توضیحات:", "کد: 12345678", R.drawable.family));
items.add(new Item("خانواده x:", "500,000 تومان", "خانواده x:", "500,000 تومان", "توضیحات:", "کد: 12345678", R.drawable.family));
items.add(new Item("خانواده x:", "500,000 تومان", "خانواده x:", "500,000 تومان", "توضیحات:", "کد: 12345678", R.drawable.family));
return items;
}
}
this is my adapter called FoldingCellListAdapter
public class FoldingCellListAdapter extends ArrayAdapter<Item> {
private HashSet<Integer> unfoldedIndexes = new HashSet<>();
private View.OnClickListener defaultRequestBtnClickListener;
public FoldingCellListAdapter(Context context, List<Item> objects) {
super(context, 0, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// get item for selected view
Item item = getItem(position);
// if cell is exists - reuse it, if not - create the new one from resource
FoldingCell cell = (FoldingCell) convertView;
ViewHolder viewHolder;
if (cell == null) {
viewHolder = new ViewHolder();
LayoutInflater vi = LayoutInflater.from(getContext());
cell = (FoldingCell) vi.inflate(R.layout.cell, parent, false);
// binding view parts to view holder
viewHolder.family1 = (TextView) cell.findViewById(R.id.family1);
viewHolder.code = (TextView) cell.findViewById(R.id.code);
viewHolder.family2 = (TextView) cell.findViewById(R.id.family2);
viewHolder.cost2 = (TextView) cell.findViewById(R.id.cost2);
viewHolder.explain = (TextView) cell.findViewById(R.id.explain);
viewHolder.cost1 = (TextView) cell.findViewById(R.id.cost1);
viewHolder.payment = (TextView) cell.findViewById(R.id.pay);
viewHolder.familyImage1 = (ImageView) cell.findViewById(R.id.familyImage1);
viewHolder.pinkback = (ImageView) cell.findViewById(R.id.pinkback);
viewHolder.familyImage2 = (ImageView) cell.findViewById(R.id.familyImage2);
cell.setTag(viewHolder);
} else {
// for existing cell set valid valid state(without animation)
if (unfoldedIndexes.contains(position)) {
cell.unfold(true);
} else {
cell.fold(true);
}
viewHolder = (ViewHolder) cell.getTag();
}
// bind data from selected element to view through view holder
viewHolder.family1.setText(item.getFamily1());
//viewHolder.time.setText(item.getTime());
viewHolder.code.setText(item.getCode());
viewHolder.family2.setText(item.getFamily2());
viewHolder.cost2.setText(item.getCost2());
viewHolder.explain.setText(String.valueOf(item.getExplain()));
viewHolder.cost1.setText(item.getCost1());
viewHolder.familyImage1.setImageResource(item.getIcon());
viewHolder.familyImage2.setImageResource(item.getIcon());
viewHolder.pinkback.setImageResource(item.getIcon());
return cell;
}
// simple methods for register cell state changes
public void registerToggle(int position) {
if (unfoldedIndexes.contains(position))
registerFold(position);
else
registerUnfold(position);
}
public void registerFold(int position) {
unfoldedIndexes.remove(position);
}
public void registerUnfold(int position) {
unfoldedIndexes.add(position);
}
// View lookup cache
private static class ViewHolder {
TextView family1;
TextView payment;
TextView cost1;
TextView family2;
TextView cost2;
TextView explain;
TextView code;
ImageView familyImage1;
ImageView pinkback;
ImageView familyImage2;
}
}
this is my codes in loanFragment
public class loanFragment extends Fragment {
public loanFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.cell, container, false);
ListView lvlist = (ListView) view.findViewById(R.id.lvlist);
final ArrayList<Item> items = Item.getTestingList();
// create custom adapter that holds elements and their state (we need hold a id's of unfolded elements for reusable elements)
final FoldingCellListAdapter adapter = new FoldingCellListAdapter(getContext(), items);
// set elements to adapter
lvlist.setAdapter(adapter);
// set on click event listener to list view
lvlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
// toggle clicked cell state
((FoldingCell) view).toggle(false);
// register in adapter that state for selected cell is toggled
adapter.registerToggle(pos);
}
});
return view;
}
}
I had a layout called cell_content_layout for foldingcell and another layout called cell_title_layout and include these layouts in one layout called cell.
cell_title_content
<?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="horizontal"
android:baselineAligned="false"
xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout
android:id="#+id/cell_title_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/cell_content_view"
android:layout_toRightOf="#+id/cell_content_view">
<FrameLayout
android:id="#+id/familyFrame"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#dd0f70">
<TextView
android:layout_width="match_parent"
android:layout_height="100dp" />
<ImageView
android:id="#+id/familyImage1"
app:srcCompat="#drawable/family"
android:layout_width="100dp"
android:layout_height="109dp"
android:layout_alignParentBottom="true"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:visibility="visible" />
</FrameLayout>
<FrameLayout
android:id="#+id/textFrame1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#d3d8dd">
<LinearLayout
android:id="#+id/textLinear1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/family1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginRight="18dp"
android:layout_weight="1"
android:gravity="center_vertical"
android:text="۱. خانواده x"
android:textSize="18dp" />
<TextView
android:id="#+id/cost1"
android:layout_width="match_parent"
android:layout_height="51dp"
android:layout_marginRight="18dp"
android:gravity="center_vertical"
android:text="۵۰۰,۰۰۰ تومان"
android:textSize="18dp" />
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="100dp" />
</FrameLayout>
</LinearLayout>
</LinearLayout>
cell_content_layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:visibility="gone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout
android:id="#+id/cell_content_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="#ffffff"
android:orientation="vertical"
>
<FrameLayout
android:id="#+id/textFrame2"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#d3d8dd">
<ImageView
android:id="#+id/pinkback"
android:layout_width="100dp"
android:layout_height="109dp"
android:layout_alignParentBottom="true"
android:layout_gravity="left"
android:layout_weight="1"
android:background="#dd0f70"
android:visibility="visible" />
<ImageView
android:id="#+id/familyImage2"
android:layout_width="100dp"
android:layout_height="109dp"
android:layout_alignParentBottom="true"
android:layout_gravity="left"
android:layout_weight="1"
android:visibility="visible"
app:srcCompat="#drawable/family" />
<LinearLayout
android:id="#+id/textLinear2"
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="vertical">
<TextView
android:id="#+id/family2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginRight="18dp"
android:layout_weight="1"
android:gravity="center_vertical"
android:text="۱. خانواده x"
android:textSize="18dp" />
<TextView
android:id="#+id/cost2"
android:layout_width="match_parent"
android:layout_height="51dp"
android:layout_marginRight="18dp"
android:gravity="center_vertical"
android:text="۵۰۰,۰۰۰ تومان"
android:textSize="18dp" />
</LinearLayout>
</FrameLayout>
<FrameLayout
android:id="#+id/containFrame"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"></LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
</LinearLayout>
</FrameLayout>
<FrameLayout
android:id="#+id/frameContent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="150dp"
android:orientation="vertical">
<TextView
android:id="#+id/explain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginRight="18dp"
android:layout_marginTop="15dp"
android:layout_weight="1.00"
android:gravity="right"
android:text="توضیحات:" />
<TextView
android:id="#+id/code"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="18dp"
android:layout_weight="0.99"
android:gravity="right"
android:text="کد: ۱۲۳۴۵۶۷۸۹" />
<Button
android:id="#+id/pay"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:background="#drawable/button_style2"
android:text="پرداخت"
android:textColor="#color/white"
android:textSize="16dp" />
</LinearLayout>
</FrameLayout>
<TextView
android:id="#+id/textView6"
android:layout_width="match_parent"
android:layout_height="0dp" />
</LinearLayout>
cell
<?xml version="1.0" encoding="utf-8"?>
<com.ramotion.foldingcell.FoldingCell
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/folding_cell_main"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:clipChildren="false"
android:clipToPadding="false">
<include
android:id="#+id/include"
layout="#layout/cell_content_layout"
android:visibility="gone" />
<include
layout="#layout/cell_title_layout"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/include" />
</com.ramotion.foldingcell.FoldingCell>
It looks like your error is in the setAdapter not the onItemClickListener.
My guess is that ListView lvlist = (ListView) view.findViewById(R.id.lvlist); return null;
Check if "R.id.lvlist" is realy the id of your listView in the xml file.
Also, Check if "lvlist" is null after the findViewById line of code

Categories