I'm with a problem to add more than 1 line(item) in my RecyclerView, the item overwrites the previous one when I tap the button, but if I create a List<> with data in hardcoded on onCreate, It works adding more than 1 line in the RecyclerView. Follow the code:
ListChecklistAdapter
public class ListChecklistAdapter extends RecyclerView.Adapter<ListChecklistAdapter.ListChecklistViewHolder> {
private List<Checklist> mChecklist;
private Context mCtx;
public ListChecklistAdapter(Context ctx, List<Checklist> checklists) {
mCtx = ctx;
mChecklist = checklists;
}
#Override
public ListChecklistViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mCtx).inflate(R.layout.item_checklist, parent, false);
return new ListChecklistViewHolder(view);
}
#Override
public void onBindViewHolder(ListChecklistViewHolder holder, int position) {
holder.cbItem.setText(mChecklist.get(position).getDescricao());
holder.cbItem.setChecked(mChecklist.get(position).isCheckado());
}
#Override
public int getItemCount() {
return mChecklist.size();
}
public class ListChecklistViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.item_checkbox)
CheckBox cbItem;
public ListChecklistViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
public void refreshData(List<Checklist> item) {
this.mChecklist.clear();
this.mChecklist.addAll(item);
notifyDataSetChanged();
}
}
item_checklist
<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="wrap_content">
<CheckBox
android:id="#+id/item_checkbox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:paddingLeft="6dp"
android:text=" "
tools:text="Exemplo de item de lista" />
</RelativeLayout>
MainActivity
public class MainActivity extends AppCompatActivity {
#BindView(R.id.rcv_lista)
RecyclerView rvLista;
int valor;
private List<Checklist> lista;
private ListChecklistAdapter listChecklistAdapter;
#BindView(R.id.btn_add_item)
Button btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
private int cont() {
return valor++;
}
public void novoItem(View view) {
lista = new ArrayList<>();
lista.add(new Checklist("Item " + (cont() + 1), true));
loadRecycler(lista);
}
private void loadRecycler(List<Checklist> lista) {
if (listChecklistAdapter == null) {
Log.i("LOG", "IF");
listChecklistAdapter = new ListChecklistAdapter(this, lista);
rvLista.setAdapter(listChecklistAdapter);
rvLista.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
rvLista.addItemDecoration(new DividerItemDecoration(this, 1));
return;
} else {
Log.i("LOG", "ELSE");
listChecklistAdapter.refreshData(lista);
listChecklistAdapter.onAttachedToRecyclerView(rvLista);
}
}
}
activity_main
<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="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context="teste.com.br.recyclercomcheckbox.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/rcv_lista"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btn_add_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginTop="5dp"
android:background="#android:color/transparent"
android:onClick="novoItem"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:text="+ novo item"
android:textColor="#009688" />
</LinearLayout>
Just remove this line this.mChecklist.clear(); from your refreshData() method.
public void refreshData(List<Checklist> item) {
this.mChecklist.addAll(item);
notifyDataSetChanged();
}
#Nilesh Rathod solved the problem! I just deleted this.mChecklist.clear(); from the ListCheckAdapter.java > refreshData()
Thanks for everyone to help too!
Related
I have a custom dialog that has a ViewPager inside of it, when the dialog shows the ViewPager is just blank, not progressing on swipe or when pressing the "Next" button I implemented. I tried slightly altering my code and it didn't work. I saw several posts like this, but none of their solutions worked. PS if some things don't make sense or have mismatched names then that's because I renamed/removed some of the files/variables to simplify.
SliderAdapter:
public class SliderAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
private ArrayList<String> text;
public SliderAdapter(Context context, ArrayList<String> text) {
this.context = context;
this.text = text;
}
public String[] txtH = {
"test1",
"test2",
"test3"
};
#Override
public int getCount() {
return txtH.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == (ConstraintLayout) object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.slide_layout_wr, container, false);
TextView txt1 = view.findViewById(R.id.txt11);
TextView txt2 = view.findViewById(R.id.txt22);
txt1.setText(txtH[position]);
txt2.setText(text.get(position));
container.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((ConstraintLayout) object);
}
}
Dialog itself:
public class DialogWeeklyReport extends AppCompatDialogFragment {
...
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),
R.style.Dialog);
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog, null);
preferences = getActivity().getSharedPreferences("label", 0);
Random random = new Random();
text.add("test1");
text.add("test2");
text.add("test3");
viewPager = view.findViewById(R.id.viewPager);
dotLayout = view.findViewById(R.id.dotLayout);
next = view.findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (next.getText().toString().equals("Proceed")) {
dismiss();
} else {
viewPager.setCurrentItem(currentPage + 1);
}
}
});
back = view.findViewById(R.id.back);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(currentPage--);
}
});
builder.setView(view)
.setCancelable(true);
addDotsIndicator(0);
viewPager.setOnPageChangeListener(viewListener);
adapter = new SliderAdapter(getActivity(), text);
return builder.create();
}
private void addDotsIndicator(int position) {
dots = new TextView[3];
dotLayout.removeAllViews();
for (int i = 0; i<dots.length; i++) {
dots[i] = new TextView(getActivity());
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(Color.parseColor("#404040"));
dotLayout.addView(dots[i]);
}
if(dots.length > 0) {
dots[position].setTextColor(Color.BLACK);
}
if (currentPage == 0) {
back.setEnabled(false);
next.setEnabled(true);
back.setText("");
next.setText("Next");
}
}
ViewPager.OnPageChangeListener viewListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
addDotsIndicator(position);
currentPage = position;
if (currentPage == 0) {
back.setEnabled(false);
next.setEnabled(true);
back.setText("");
next.setText("Next");
} else if (currentPage == 1) {
back.setEnabled(true);
next.setEnabled(true);
back.setText("Back");
next.setText("Next");
} else if (currentPage == 2) {
back.setEnabled(true);
next.setEnabled(false);
back.setText("Back");
next.setText("Proceed");
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
}
Dialog XML:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/dialog_bg"
app:cardCornerRadius="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/dotLayout"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_centerHorizontal="true"
android:layout_margin="15dp"
android:layout_below="#+id/viewPager"
android:orientation="horizontal" />
<Button
android:id="#+id/back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_below="#+id/viewPager"
android:background="#android:color/transparent"
android:elevation="0dp"
android:text="Back"
android:textColor="#android:color/black" />
<Button
android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="#+id/viewPager"
android:layout_margin="5dp"
android:background="#android:color/transparent"
android:elevation="0dp"
android:text="Next"
android:textColor="#android:color/black" />
</RelativeLayout>
ViewPager's slide layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:background="#android:color/white">
<TextView
android:id="#+id/txt11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEST"
android:textColor="#android:color/black"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.24000001" />
<TextView
android:id="#+id/txt22"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Test"
android:textColor="#android:color/black"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/txt11"
app:layout_constraintStart_toStartOf="#+id/txt11"
app:layout_constraintTop_toBottomOf="#+id/txt11"
app:layout_constraintVertical_bias="0.26" />
</androidx.constraintlayout.widget.ConstraintLayout>
The problem is that you didn't set the ViewPager adapter
public class DialogWeeklyReport extends AppCompatDialogFragment {
...
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
...
viewPager = view.findViewById(R.id.viewPager);
...
adapter = new SliderAdapter(getActivity(), text);
viewPager.setAdapter(adapter); // <<<<<< change here
return builder.create();
}
...
Here is my test
I want to make an internal grid view(room) added by clicking the button on the external recycler view(floor). but Null pointer extension occurs in onBindViewHolder. please help me
public class FloorAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements OnFloorItemClickListener {
OnFloorItemClickListener listener;
static public ArrayList<FloorData> floors;
private Context context;
private LayoutInflater layoutInflater;
private OnItemClickListener mListener = null;
public FloorAdapter(ArrayList<FloorData> floors, Context context) {
this.floors = floors;
this.context = context;
this.layoutInflater = LayoutInflater.from(context);
}
public interface OnItemClickListener{
void onItemClick(View v, int pos);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.mListener = listener ;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.signle_floor, parent, false);
return new GridViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((GridViewHolder)holder).recyclerView.setAdapter(new RoomAdapter(context, floors.get(position).rooms));
((GridViewHolder)holder).recyclerView.setLayoutManager(new GridLayoutManager(context, 2));
((GridViewHolder)holder).recyclerView.setHasFixedSize(true);
((GridViewHolder)holder).tvFloorNum.setText(String.valueOf(floors.get(position).floorNum));
}
#Override
public int getItemCount() {
return floors.size();
}
#Override public void onItemClick(RecyclerView.ViewHolder holder, View view, int position) {
if(listener != null){
listener.onItemClick(holder,view,position);
}
}
#Override
public int getItemViewType(int position) {
return floors.get(position).id;
}
public class GridViewHolder extends RecyclerView.ViewHolder {
RecyclerView recyclerView;
TextView tvFloorNum;
Button btnPlusRoom;
public GridViewHolder(View itemView) {
super(itemView);
recyclerView = itemView.findViewById(R.id.rvRooms);
tvFloorNum = itemView.findViewById(R.id.tvRoomNumber);
btnPlusRoom = (Button)itemView.findViewById(R.id.btnPlusRoom);
btnPlusRoom.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v)
{
int pos = getAdapterPosition();
if (pos != RecyclerView.NO_POSITION)
{
if(mListener != null){
mListener.onItemClick(v, pos);
}
}
}
});
}
}
}
public class RoomAdapter extends RecyclerView.Adapter<RoomAdapter.CustomViewHolder> {
private Context context;
private ArrayList<RoomData> rooms;
private LayoutInflater inflater;
public RoomAdapter(Context context, ArrayList<RoomData> rooms) {
this.context = context;
this.rooms = rooms;
this.inflater = LayoutInflater.from(context);
}
#Override
public CustomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
view = inflater.inflate(R.layout.single_room, parent, false);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull CustomViewHolder holder, int position) {
RoomData room = rooms.get(position);
holder.tvRoomNum.setText(String.valueOf(room.roomNum));
}
#Override
public int getItemCount() {
return rooms.size();
}
public static class CustomViewHolder extends RecyclerView.ViewHolder {
public TextView tvRoomNum;
public CustomViewHolder(View itemView) {
super(itemView);
tvRoomNum = (TextView) itemView.findViewById(R.id.tvRoomNumber);
}
}
}
public class RoomActivity extends AppCompatActivity {
private RecyclerView rvFloor;
private FloorAdapter floorAdapter;
public ArrayList<FloorData> globalfloors;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_room);
globalfloors = prepareData();
rvFloor = findViewById(R.id.rvFloors);
floorAdapter = new FloorAdapter(globalfloors, RoomActivity.this);
LinearLayoutManager manager = new LinearLayoutManager(RoomActivity.this);
rvFloor.setLayoutManager(manager);
rvFloor.setAdapter(floorAdapter);
floorAdapter.setOnItemClickListener(new FloorAdapter.OnItemClickListener() {
#Override
public void onItemClick(View v, int position) {
FloorData floor = globalfloors.get(position);
RoomData newRoom = new RoomData();
floor.finalRoomNum++;
newRoom.roomNum = floor.finalRoomNum;
floor.rooms.add(newRoom);
rvFloor.setAdapter(floorAdapter);
}
});
}
private ArrayList<FloorData> prepareData() {
ArrayList<FloorData> floors = new ArrayList<FloorData>();
//첫번째 subject 추가
FloorData floor1 = new FloorData();
floor1.floorNum = 1;
RoomData room101 = new RoomData();
room101.roomNum = 101;
RoomData room102 = new RoomData();
room102.roomNum = 102;
RoomData room103 = new RoomData();
room103.roomNum = 103;
floor1.finalRoomNum = 103;
floor1.rooms.add(room101);
floor1.rooms.add(room102);
floor1.rooms.add(room103);
floors.add(floor1);
FloorData floor2 = new FloorData();
floor2.floorNum = 2;
floor2.finalRoomNum = 200;
floors.add(floor2);
return floors;
}
}
activity_room
<?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"
tools:context=".tools.RewardActivity"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolBar_room"
android:layout_width="match_parent"
android:layout_gravity="center"
android:layout_height="60dp"
android:background="#color/colorPrimaryDark"
app:title="호실 등록"
android:theme="#style/ToolbarTheme" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvFloors"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
single_floor
<?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="wrap_content"
android:orientation="vertical">
<LinearLayout
android:orientation="vertical"
android:background="#FFFFFF"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="15dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/tvFloorNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:textSize="30dp"
android:textColor="#000000" />
<Button
android:id="#+id/btnPlusRoom"
android:layout_width="40dp"
android:layout_height="40dp"
android:text="+"
android:textSize="30dp"
android:layout_marginTop="10dp"
android:background="#color/colorPrimaryDark"/>
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:columnCount="5"
android:id="#+id/rvRooms"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</LinearLayout>
single_room
<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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="2dp">
<TextView
android:id="#+id/tvRoomNumber"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:ellipsize="end"
android:singleLine="true"
android:background="#color/colorAccent"
android:gravity="center"
android:textSize="30dp"
/>
</LinearLayout>
</LinearLayout>
error message describes "java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.eos.parcelnoticemanager.tools.FloorAdapter.onBindViewHolder"
The GridViewHolder inside your FloorAdapter is pointing to the wrong XML Id tag for the TextView that's why it's throwing NullPointerException
Change this in your GridViewHolder
tvFloorNum = itemView.findViewById(R.id.tvRoomNumber);
to this
tvFloorNum = itemView.findViewById(R.id.tvFloorNumber);
Then it should work
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm having these error on my coding
Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference onBindViewHolder(BrandAdapter.java:67) and
BrandAdapter.onBindViewHolder(BrandAdapter.java:34).
I'm not really sure what went wrong as I follow the tutorial very closely. And my database is not empty.
It contains child.
this is my adapter class
public class BrandAdapter extends RecyclerView.Adapter<BrandAdapter.MyViewHolder> {
private Context context;
List<String> key;
ArrayList<Brand> brandList;
public BrandAdapter(ArrayList<Brand> brandList) {
this.brandList = brandList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.brand_list, viewGroup, false);
context = viewGroup.getContext();
return new BrandAdapter.MyViewHolder(view);
}
public BrandAdapter(Context c) {
this.context = c;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, final int i) {
myViewHolder.brand_name.setText(brandList.get(i).getBrand_name());
Picasso.with(context).load(brandList.get(i).getBrand_image()).into(myViewHolder.image);
// Picasso.with(mcontext).load(brand.getBrand_image()).into(myViewHolder.image);
myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String bName = brandList.get(i).getBrand_name();
String pic = brandList.get(i).getBrand_image();
Log.i("loz", bName);
Intent intent = new Intent(context, updateBrand.class);
intent.putExtra("brand_name", bName);
intent.putExtra("imgurl", pic);
context.startActivity(intent);
}
});
#Override
public int getItemCount() {
return brandList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView brand_name;
CardView brand_cv;
ImageView image, btnDelete;
LinearLayout frame_layout;
public MyViewHolder(View itemView) {
super(itemView);
brand_name = itemView.findViewById(R.id.name);
image = itemView.findViewById(R.id.image);
brand_cv = itemView.findViewById(R.id.brand_cv);
btnDelete = itemView.findViewById(R.id.delete);
frame_layout = itemView.findViewById(R.id.frame_layout);
}
}
}
my Brand Activity class
public class BrandActivity extends AppCompatActivity {
DatabaseReference databaseReference;
ArrayList<Brand> brandList;
RecyclerView recyclerView;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_brand);
databaseReference = FirebaseDatabase.getInstance().getReference("Brand").child("");
recyclerView = findViewById(R.id.rv);
searchView = findViewById(R.id.searchView);
}
#Override
protected void onStart() {
super.onStart();
if (databaseReference != null) {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
brandList = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
brandList.add(ds.getValue(Brand.class));
}
}
BrandAdapter brandAdapter = new BrandAdapter(brandList);
recyclerView.setAdapter(brandAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(BrandActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
app:cardElevation="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#color/lightgray">
<TextView
android:id="#+id/brand_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="sample"
android:textStyle="bold"
android:textColor="#color/white"
android:textAlignment="center"
android:background="#color/black"
android:textSize="20sp"
android:textAppearance="#style/TextAppearance.AppCompat.Headline" />
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#FCFAFA"
android:scaleType="centerCrop"
android:adjustViewBounds="true"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/delete"
android:layout_width="60dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:padding="8dp"
android:visibility="visible"
app:srcCompat="#drawable/trash" />
</LinearLayout>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#000" />
</androidx.cardview.widget.CardView>
Brand model
public class Brand {
public String brand_id;
public String brand_name;
public String brand_image;
public Brand(){}
public Brand(String brand_id, String brand_name, String brand_image) {
this.brand_id = brand_id;
this.brand_name = brand_name;
this.brand_image = brand_image;
}
public String getBrand_id() {
return brand_id;
}
public void setBrand_id(String brand_id) {
this.brand_id = brand_id;
}
public String getBrand_name() {
return brand_name;
}
public void setBrand_name(String brand_name) {
this.brand_name = brand_name;
}
public String getBrand_image() {
return brand_image;
}
public void setBrand_image(String brand_image) {
this.brand_image = brand_image;
}
}
In your MyViewHolder you are trying to find view that doesn't exist in your layout. So, try to change brand_name = itemView.findViewById(R.id.name) to brand_name = itemView.findViewById(R.id.brand_name). The same problem is also related to the other views in layout except image and delete: you don't have views with brand_cv and frame_layout ids.
I have a problem, I learnt how to use a SearchView with text, but I have an Activity where the listView have an image and text, but I couldnt find the way to display the filter.
So, I debug the code in order to understand why this happens and I get this in the LogCat:
java.lang.RuntimeException: Unable to start activity ComponentInfo{mundo.hola.app.frank.com.universidad2/mundo.hola.app.frank.com.universidad2.RankingActividad}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SearchView.setOnQueryTextListener(android.widget.SearchView$OnQueryTextListener)' on a null object reference
the code compiles great, but when I try to have access to this activity trough an Intent the App crashes.
If someone could help me i would be greatful.
activity
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbarLayout_po"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<android.support.v7.widget.Toolbar
android:id="#+id/appbar_rank"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:minHeight="?attr/actionBarSize"
>
<ImageView
android:id="#+id/home_rank"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:scaleType="center"
tools:ignore="ContentDescription"
android:src="#drawable/ic_first_page_24dp" />
<SearchView
android:id="#+id/search_tecnico"
android:layout_width="match_parent"
android:layout_height="match_parent">
<requestFocus />
</SearchView>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<ListView
android:id="#+id/rankinglista"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
</android.support.design.widget.CoordinatorLayout>
item_list
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorBlanco"
android:foreground="?attr/selectableItemBackground"
android:orientation="vertical"
android:paddingBottom="8dp"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="8dp">
<ImageView
android:id="#+id/imagenR"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_centerVertical="true" />
<TextView
android:id="#+id/tv_nombreUR"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="false"
android:layout_marginLeft="56dp"
android:layout_marginStart="65dp"
android:textColor="#android:color/black"
tools:text="NombreU" />
<TextView
android:id="#+id/tv_PuntajeR"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tv_nombreUR"
android:layout_alignStart="#+id/tv_nombreUR"
android:layout_below="#+id/tv_nombreUR"
tools:text="Puntaje" />
<TextView
android:id="#+id/tv_NpuntajeR"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tv_PuntajeR"
android:layout_alignParentBottom="false"
android:layout_alignStart="#+id/tv_PuntajeR"
android:layout_alignWithParentIfMissing="false"
android:layout_below="#+id/tv_PuntajeR"
android:textColor="#android:color/holo_red_dark"
tools:text="11223344" />
</RelativeLayout>
Class Ranking
public class Ranking {
private int Id;
private String Titulo;
private String Puntaje;
private String NPuntaje;
private int Imagen;
public Ranking(int id, String titulo, String puntaje, String NPuntaje, int imagen) {
Id = id;
Titulo = titulo;
Puntaje = puntaje;
this.NPuntaje = NPuntaje;
Imagen = imagen;
}
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getTitulo() {
return Titulo;
}
public void setTitulo(String titulo) {
Titulo = titulo;
}
public String getPuntaje() {
return Puntaje;
}
public void setPuntaje(String puntaje) {
Puntaje = puntaje;
}
public String getNPuntaje() {
return NPuntaje;
}
public void setNPuntaje(String NPuntaje) {
this.NPuntaje = NPuntaje;
}
public int getImagen() {
return Imagen;
}
public void setImagen(int imagen) {
Imagen = imagen;
}
}
Activity Class
public class RankingActividad extends AppCompatActivity {
ImageView inicio1;
SearchView sv;
Toolbar toolbar1;
ListView listadatos;
ArrayList<Ranking> Lista;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ranking_actividad);
inicio1 = (ImageView) findViewById(R.id.home_rank);
sv = (SearchView) findViewById(R.id.search);
toolbar1 = (Toolbar) findViewById(R.id.appbar_rank);
listadatos = (ListView) findViewById(R.id.rankinglista);
Lista = new ArrayList<Ranking>();
Lista.add(new Ranking(1,"Universidad 1","Puntaje","4512",R.drawable.ufps));
Lista.add(new Ranking(2,"universidad 2","Puntaje","4512",R.drawable.unip));
Lista.add(new Ranking(3,"universidad 3","Puntaje","4512",R.drawable.ufps));
Lista.add(new Ranking(4,"universidad 4","Puntaje","4512",R.drawable.ufps));
final RankingAdaptador rankingAdaptador = new RankingAdaptador(getApplicationContext(),Lista);
listadatos.setAdapter(rankingAdaptador);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if(TextUtils.isEmpty(s)){
rankingAdaptador.filter("");
listadatos.clearTextFilter();
}else{
String texto = s;
rankingAdaptador.filter(s);
}
return true;
}
});
Adapter Class
public class RankingAdaptador extends BaseAdapter {
Context context;
LayoutInflater inflater;
List<Ranking> ListaObjetos;
private ArrayList<Ranking> arraylist;
public RankingAdaptador(Context context, List<Ranking> listaObjetos) {
this.context = context;
ListaObjetos = listaObjetos;
inflater = LayoutInflater.from(context);
this.arraylist = new ArrayList<Ranking>();
this.arraylist.addAll(ListaObjetos);
}
public class ViewHolder{
TextView mtitulo,mpuntaje,npuntaje;
ImageView mimagen;
}
#Override
public int getCount() {
return ListaObjetos.size(); //retorna la cantidad de elementos de la lista
}
#Override
public Object getItem(int i) {
return ListaObjetos.get(i);
}
#Override
public long getItemId(int i) {
return ListaObjetos.get(i).getId();
}
#Override
public View getView(int position, View view, ViewGroup parent) {
ViewHolder holder;
if (view==null){
holder = new ViewHolder();
view = inflater.inflate(R.layout.ranking_item_lista,null);
// localizar los items de la lista
holder.mimagen = view.findViewById(R.id.imagenR);
holder.mtitulo = view.findViewById(R.id.tv_nombreUR);
holder.mpuntaje = view.findViewById(R.id.tv_PuntajeR);
holder.npuntaje = view.findViewById(R.id.tv_NpuntajeR);
view.setTag(holder);
}else {
holder = (ViewHolder)view.getTag();
}
// setear los textos de la lista
holder.mtitulo.setText(ListaObjetos.get(position).getTitulo());
holder.mpuntaje.setText(ListaObjetos.get(position).getPuntaje());
holder.npuntaje.setText(ListaObjetos.get(position).getNPuntaje());
// setear las imagenes de la lista
holder.mimagen.setImageResource(ListaObjetos.get(position).getImagen());
return null;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
ListaObjetos.clear();
if (charText.length() == 0) {
ListaObjetos.addAll(arraylist);
} else {
for (Ranking wp : arraylist) {
if (wp.getTitulo().toLowerCase(Locale.getDefault()).contains(charText)) {
ListaObjetos.add(wp);
}
}
}
notifyDataSetChanged();
}}
sv.setOnQueryTextListener(new Sear...
You never initialized sv, so it's null. Add this:
sv = (SearchView) findViewById(R.id.search_tecnico);
I'm developing an English-Japanese learning app, where it has a stack of cards where users can swipe through, and on each current card, the user can touch the card to flip to the other side of a card, which show the meaning of the word.
For the swipe function, I'm using a library SwipeFlingAdapterView, which support setOnItemClick. Now I need to do the flipping part. I read the tutorial here, which requires 2 fragments to do the flip:
https://developer.android.com/training/animation/cardflip.html
The structure Im setting below:
stack_of_cards_fragment.xml
<FrameLayout 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"
......
>
<com.lorentzos.flingswipe.SwipeFlingAdapterView
android:id="#+id/swipeFlingAdapterViewFront"
android:layout_width="match_parent"
android:layout_height="match_parent"
</com.lorentzos.flingswipe.SwipeFlingAdapterView>
</FrameLayout>
StackOfCardsFragment.java
public class StackOfCardsFragment extends Fragment {
ArrayList<TestModel> cardsList;
Context context;
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.stack_of_cards_fragment,container,false);
final CardsAdapter arrayCardsAdapter;
cardsList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
//dump data
TestModel model = new TestModel();
model.isFlipped = false;
cardsList.add(model);
}
SwipeFlingAdapterView flingContainer = ButterKnife.findById(view,R.id.swipeFlingAdapterViewFront);
ButterKnife.bind(this, view);
arrayCardsAdapter = new CardsAdapter(context, cardsList);
flingContainer.setAdapter(arrayCardsAdapter);
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
Log.d("LIST", "removed object!");
if(!cardsList.isEmpty())
{arrayCardsAdapter.remove(0);}
}
#Override
public void onLeftCardExit(Object dataObject) {
Log.e("Swipe Direction","Left");
}
#Override
public void onRightCardExit(Object dataObject) {
Log.e("Swipe Direction","Right");
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
if(!cardsList.isEmpty()) {
arrayCardsAdapter.notifyDataSetChanged();
Log.d("LIST", "notified");
}else Log.e("Check Empty","Its empty");
}
#Override
public void onScroll(float scrollProgressPercent) {
Log.e("onScroll", "scrollProgressPercent");
}
});
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
//This is where I want to change the Front Card Fragment to Back Card Fragment.
}
});
return view;
}
}
and below is the part where I'm struggling to do.
flash_card_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/holo_blue_dark">
<LinearLayout
android:id="#+id/child_fragment_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
CardsAdapter.java
public class CardsAdapter extends BaseAdapter {
Context context;
ArrayList<TestModel> cardsList;
ViewFlipper viewFlipper;
public CardsAdapter(Context context, ArrayList cardsList ) {
this.context = context;
this.cardsList = cardsList;
}
#Override
public int getCount() {
return cardsList.size();
}
#Override
public Object getItem(final int i) {
return cardsList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int i, View view, final ViewGroup viewGroup) {
if (view == null) {
LayoutInflater vi = (LayoutInflater) viewGroup.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.flash_card_layout, viewGroup, false);
//This is where I want to set the Front Card Fragment
Fragment frontCardFragment = new EachFrontCardFragment();
FragmentTransaction transaction = ((VocabularyGameActivity) context).getSupportFragmentManager().beginTransaction();
transaction.addToBackStack(null);
transaction.add(R.id.child_fragment_container, frontCardFragment);
transaction.commit();
}
return view;
}
public void remove(int i) {
cardsList.remove(i);
notifyDataSetChanged();
}
}
each_card_front_fragment.xml and one for the each_card_back_fragment.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/cardviewfront">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingTop="20dp"
android:paddingLeft="20dp"
android:paddingRight="20dp">
<TextView android:id="#+id/txtWord_cardfront"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="English"
android:textStyle="bold"
android:textSize="50sp"
android:textColor="#android:color/black"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:layout_marginBottom="50dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"/>
</LinearLayout>
</android.support.v7.widget.CardView>
</FrameLayout>
I already created 2 fragments for each_card_front_fragment and each_card_back_fragment.
What am I missing here? All the code above is only showing me the cardAdapter in the StackOfCardsFragment(which is only a background), but the each_card_front_fragment doesn't show up.
I already try set up a BroadcastReceiver from (CardsAdapter)BaseAdapter to send to the VocabulartyActivity to set the each_card_front_fragment there but the same outcome.
is the any other way to set the Fragment in the BaseAdapter?