How to add Fragment from BaseAdapter - java

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?

Related

ViewPager inside Dialog not showing

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("&#8226"));
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'd like to make an internal grid view added by clicking the button on the external recyclerview

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

custom listview to show notification

#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
super.onNotificationRemoved(sbn);
}
public List<String> getText(Notification notification) {
if (null == notification) {
return null;
}
RemoteViews views = notification.bigContentView;
if (views == null) {
views = notification.contentView;
}
if (views == null) {
return null;
}
How to put this code in android list view
to show notifications in list.
also provide xml layout for it.
First create a XML file my_list_view.xml for your simple ListView like this
<ListView
android:id="#+id/simpleListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:dividerHeight="1dp"/>
Then create another xml file row_view.xml which will be the layout of each row in your ListView
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="10dp">
<TextView
android:id="#+id/title"
android:textSize="25sp"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
<TextView
android:id="#+id/subTitle"
android:textSize="20sp"
android:layout_below="#+id/title"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
</RelativeLayout>
Your next step is to create a CustomAdapter to properly inflate your ListView with notifications
public class CustomAdapter extends BaseAdapter {
Context context;
String titles[];
String subTitles[];
LayoutInflater inflter;
public CustomAdapter(Context applicationContext, String[] titles, String[] subTitles)
{
this.context = context;
this.titles = titles;
this.subTitles=subTitles;
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return titles.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.row_view, null);
Textview tv1=(TextView)view.findViewById(R.id.title);
Textview tv2=(TextView)view.findViewById(R.id.subTitle);
tv1.setText(titles[i]);
tv2.setText(subTitles[i]);
return view;
}
}
and finally in your MainActivity.java do the following
String notTitles[] = YOUR_NOTIFICATION_TITLES;
String notSubTitles[]=YOUR_NOTIFICATION_SUBTITLES;
ListView simpleList= (ListView) findViewById(R.id.simpleListView);
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), notTitles, notSubTitles);
simpleList.setAdapter(customAdapter);
that's it. :)

RecyclerView - I can't add more than 1 line

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!

Why is my RecyclerView not showing anything? / What happend if Recycler Adapter is set again after notifyDataSetChanged() called?

I am new to Android Programming and I've been trying to make a fragment which displays a list of items using RecyclerView. Everything seems fine and there is no error when I run the app.
Here is my code:
FriendsFragment.java
public class FriendsFragment extends android.support.v4.app.Fragment {
#Bind(R.id.friendList)
RecyclerView friendList;
RecyclerView.LayoutManager friendsManager;
FriendListAdapter friendListAdapter;
public FriendsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_friends, container, false);
ButterKnife.bind(this, view);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
friendList.setHasFixedSize(true);
friendsManager = new LinearLayoutManager(view.getContext());
friendList.setLayoutManager(friendsManager);
friendListAdapter = new FriendListAdapter(new ArrayList<Friends>());
friendList.setAdapter(friendListAdapter);
test();
friendListAdapter.notifyDataSetChanged();
friendList.setAdapter(friendListAdapter);
super.onViewCreated(view, savedInstanceState);
}
private void test() {
Friends friend = new Friends();
friend.setName("Junjie Saitamaria");
friendListAdapter.addNewFriend(friend);
}
}
FriendListAdapter.java
public class FriendListAdapter extends RecyclerView.Adapter<FriendListAdapter.ViewHolderFriend> {
private List<Friends> friendList;
public FriendListAdapter(List<Friends> friends) {
if(friends != null) {
friendList = friends;
}
}
public void addNewFriend(Friends friend) {
friendList.add(0, friend);
}
#Override
public ViewHolderFriend onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_friend, parent, false);
ViewHolderFriend viewHolder = new ViewHolderFriend(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolderFriend holder, int position) {
Friends currentFriend = friendList.get(position);
holder.friendName.setText(currentFriend.getName());
}
#Override
public int getItemCount() {
return friendList.size();
}
static class ViewHolderFriend extends RecyclerView.ViewHolder {
#Bind(R.id.friend_avatar)
public ImageView friendThumbnail;
#Bind(R.id.friend_name)
public TextView friendName;
Context currentContext = null;
public ViewHolderFriend(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
this.currentContext = itemView.getContext();
}
}
}
fragment_friends.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="match_parent"
android:layout_margin="10dp"
tools:context="com.cebuinstituteoftechnology_university.citumessenger.FriendsFragment">
<android.support.v7.widget.RecyclerView
android:id="#+id/friendList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true" >
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
list_item_friend.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="match_parent"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="80dp"
android:id="#+id/friends_card"
android:elevation="2dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- icon -->
<ImageView
android:id="#+id/friend_avatar"
android:layout_width="64dp"
android:layout_height="64dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp"
android:contentDescription="icon"
android:src="#drawable/avatar"
/>
<!-- title -->
<TextView
android:id="#+id/friend_name"
android:layout_width= "wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_toRightOf="#+id/friend_avatar"
android:layout_alignBaseline="#+id/friend_avatar"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:text="Name" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Looks everything fine except this extra line friendList.setAdapter(friendListAdapter); in below code:
friendList.setAdapter(friendListAdapter);
test();
friendListAdapter.notifyDataSetChanged();
friendList.setAdapter(friendListAdapter);
Replace above 3 lines with this and see :
friendList.setAdapter(friendListAdapter);
test();
friendListAdapter.notifyDataSetChanged();
Remove following line from onViewCreated() Method
friendList.setAdapter(friendListAdapter);
other code is fine.

Categories