Show data from Firebase in a Recyclerview in a Fragment | Java - java

How can I take data from Firebase into a recyclerview and show it inside a fragment?
I followed This video to create a recyclerview inside a fragment. But in it the data is static. (retrieved from the strings file)
I then tried to incorporate this video to retrieve data from Firebase.
But it doesn't work. Maybe I have to call the functions in a different override??
My Fragment Class (HomeFragemnt.java)
package com.example.foodapp.deliverer;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.foodapp.R;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class HomeFragment extends Fragment {
private ArrayList<OrderItem> orderItemArrayList;
RecyclerView recyclerview;
DatabaseReference DB;
ItemRecyclerAdapter itemRecyclerAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.delivery_fragment_home, container, false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recyclerview = view.findViewById(R.id.delivery_orders_recyclerView);
DB = FirebaseDatabase.getInstance().getReference("Delivery");
recyclerview.setHasFixedSize(true);
recyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
orderItemArrayList = new ArrayList<>();
itemRecyclerAdapter = new ItemRecyclerAdapter(getContext(), orderItemArrayList);
recyclerview.setAdapter(itemRecyclerAdapter);
DB.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot dataSnapshot: snapshot.getChildren()){
OrderItem item = dataSnapshot.child("Delivery").getValue(OrderItem.class);
orderItemArrayList.add(item);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
itemRecyclerAdapter.notifyDataSetChanged();
}
}
My Fragment Layout (delivery_fragment_home.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"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".deliverer.HomeFragment" >
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/delivery_orders_recyclerView"
android:layout_width="409dp"
android:layout_height="729dp"
android:background="#CDDC39"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:listitem="#layout/delivery_orderitem" />
</androidx.constraintlayout.widget.ConstraintLayout>
Item into Recyclerview class (OrderItem.java)
package com.example.foodapp.deliverer;
public class OrderItem {
private String orderID;
private String Address;
public OrderItem(String orderID, String Address) {
this.orderID = orderID;
this.Address = Address;
}
public String getOrderID() {
return orderID;
}
public String getAddress() {
return Address;
}
}
Item into recyclerview layout (delivery_orderItem.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginTop="15dp"
android:text="#string/lbl_orderId"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="15dp"
android:text="#string/lbl_address"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView2" />
<TextView
android:id="#+id/lbl_orderId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:layout_marginTop="15dp"
android:text="TextView"
app:layout_constraintStart_toEndOf="#+id/textView2"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/lbl_address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="15dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="#+id/lbl_orderId"
app:layout_constraintTop_toBottomOf="#+id/lbl_orderId" />
</androidx.constraintlayout.widget.ConstraintLayout>
Adapter class (ItemRecyclerAdapter.java)
package com.example.foodapp.deliverer;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.foodapp.R;
import java.util.ArrayList;
public class ItemRecyclerAdapter extends RecyclerView.Adapter<ItemRecyclerAdapter.DriverItemViewHolder> {
Context context;
ArrayList<OrderItem> itemArrayList;
public ItemRecyclerAdapter(Context context, ArrayList<OrderItem> itemList) {
this.context = context;
this.itemArrayList = itemList;
}
#NonNull
#Override
public DriverItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.delivery_orderitem, parent, false);
return new DriverItemViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ItemRecyclerAdapter.DriverItemViewHolder holder, int position) {
OrderItem order = itemArrayList.get(position);
holder.orderID.setText(order.getOrderID());
holder.address.setText(order.getAddress());
}
#Override
public int getItemCount() {
return itemArrayList .size();
}
public static class DriverItemViewHolder extends RecyclerView.ViewHolder{
private TextView orderID;
private TextView address;
public DriverItemViewHolder(#NonNull View itemView) {
super(itemView);
this.orderID = itemView.findViewById(R.id.lbl_orderId);
this.address = itemView.findViewById(R.id.lbl_address);
}
}
}
What am I doing wrong?

Related

size of recycler view item changes when user scrolls down and up

I am working on a chat functionality to implement in my app. The purpose is that when a message comes from another user, the message item will align parent's start and when the user sends a message, it will align to the end. The send button on upper left corner simulates the other user sending a message. The problem is that when items recycles, some of them mathes the width of parent layout. I do not really understand why this happens and how to fix it. Thanks in advance...
package com.example.messageapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Activity;
import android.content.Context;
import android.database.Observable;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button sendBtn;
Button otherSendBtn;
EditText editText;
RecyclerView recyclerView;
MessagesAdapter adapter;
List<ChatMessage> messageList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
messageList=new ArrayList<>();
sendBtn=findViewById(R.id.sendBtn);
otherSendBtn=findViewById(R.id.otherSendBtn);
editText=findViewById(R.id.editText);
recyclerView=findViewById(R.id.recyclerView);
adapter=new MessagesAdapter(this,messageList);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
for(int i=0; i<4; i++){
if(i%2==0){
messageList.add(new ChatMessage("from him","self"));
}else{
messageList.add(new ChatMessage("from me","other"));
}
adapter.notifyItemInserted(messageList.size()-1);
}
otherSendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
messageList.add(new ChatMessage("random","other"));
adapter.notifyItemInserted(messageList.size()-1);
}
});
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String txt=editText.getText().toString();
messageList.add(new ChatMessage(txt, "self"));
adapter.notifyItemInserted(messageList.size()-1);
editText.setText("");
hideKeyboardFrom(MainActivity.this, view);
}
});
}
public static void hideKeyboardFrom(Context context, View view) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
model class for messages
package com.example.messageapp;
public class ChatMessage {
public String text;
public String user;
public ChatMessage(String text, String user) {
this.text = text;
this.user = user;
}
}
recycler view adapter
package com.example.messageapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class MessagesAdapter extends RecyclerView.Adapter {
Context context;
List<ChatMessage> messages;
public void setMessages(List<ChatMessage> messages) {
this.messages = messages;
}
public MessagesAdapter(Context context, List<ChatMessage> messages) {
this.context = context;
this.messages = messages;
}
private static class MessageViewHolder extends RecyclerView.ViewHolder{
TextView textView;
RelativeLayout relativeLayout;
public MessageViewHolder(#NonNull View itemView) {
super(itemView);
textView=itemView.findViewById(R.id.messageTextView);
relativeLayout=itemView.findViewById(R.id.item_parent);
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v= LayoutInflater.from(context).inflate(R.layout.message_item,parent,false);
return new MessageViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
ChatMessage message=messages.get(position);
((MessageViewHolder) holder).textView.setText(message.text);
RelativeLayout.LayoutParams params= (RelativeLayout.LayoutParams) ((MessageViewHolder) holder).relativeLayout.getLayoutParams();
if(message.user.equals("self")){
params.addRule(RelativeLayout.ALIGN_PARENT_END);
((MessageViewHolder) holder).relativeLayout.setBackgroundColor(context.getResources().getColor(R.color.teal_200));
}else{
params.addRule(RelativeLayout.ALIGN_PARENT_START);
((MessageViewHolder) holder).relativeLayout.setBackgroundColor(context.getResources().getColor(R.color.purple_200));
}
((MessageViewHolder) holder).relativeLayout.setLayoutParams(params);
}
#Override
public int getItemCount() {
return messages.size();
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="10dp">
<RelativeLayout
android:id="#+id/item_parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/teal_700">
<TextView
android:padding="10dp"
android:id="#+id/messageTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/otherSendBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="send"
android:layout_centerHorizontal="true"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/otherSendBtn"
tools:listitem="#layout/message_item"/>
<RelativeLayout
android:id="#+id/linear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toStartOf="#+id/sendBtn"
android:layout_marginEnd="5dp"/>
<Button
android:background="#drawable/ic_baseline_send_24"
android:id="#+id/sendBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
</RelativeLayout>

How to change fragment from the Recycler View OnClick Listener when RecyclerView item is clicked using Navigation Components

Basically I want to change fragment when an item is clicked in recyclerView List. But when I did it in OnClick method of RecyclerViewAdapterForClassList it is showing error
NavHostFragment.findNavController(SecondFragment.this).navigate(R.id.action_SecondFragment_to_studentListFragment);
MainActivity.java
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.android.studentattendancerecorder.databinding.ActivityMainBinding;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration appBarConfiguration;
private ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.toolbar);
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.about) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
return NavigationUI.navigateUp(navController, appBarConfiguration)
|| super.onSupportNavigateUp();
}
}
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"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/Theme.StudentAttendanceRecorder.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/Theme.StudentAttendanceRecorder.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
<include layout="#layout/content_main" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
FirstFragemnt.java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;
import androidx.recyclerview.widget.RecyclerView;
import com.android.studentattendancerecorder.Adapters.RecyclerViewAdapterForClassList;
import com.android.studentattendancerecorder.databinding.FragmentFirstBinding;
public class FirstFragment extends Fragment {
private FragmentFirstBinding binding;
#Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
binding = FragmentFirstBinding.inflate(inflater, container, false);
return binding.getRoot();
}
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
binding.buttonFirst.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NavHostFragment.findNavController(FirstFragment.this)
.navigate(R.id.action_FirstFragment_to_SecondFragment);
}
});
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
}
fragment_first.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FirstFragment">
<TextView
android:id="#+id/textview_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_first_fragment"
app:layout_constraintBottom_toTopOf="#id/button_first"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/next"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/textview_first" />
</androidx.constraintlayout.widget.ConstraintLayout>
SecondFragment.java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.studentattendancerecorder.Adapters.RecyclerViewAdapterForClassList;
import com.android.studentattendancerecorder.Model.ClassAndSubjectDetails;
import com.android.studentattendancerecorder.databinding.FragmentSecondBinding;
import java.util.ArrayList;
public class SecondFragment extends Fragment {
private RecyclerView recyclerViewClass;
private RecyclerViewAdapterForClassList recyclerViewAdapterForClassList;
private ArrayList<ClassAndSubjectDetails> classAndSubjectDetailsArrayList;
private ArrayAdapter<String> arrayAdapter;
private FragmentSecondBinding binding;
#Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
binding = FragmentSecondBinding.inflate(inflater, container, false);
return binding.getRoot();
}
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recyclerViewClass= view.findViewById(R.id.recyclerViewClass);
recyclerViewClass.setHasFixedSize(true);
recyclerViewClass.setLayoutManager(new LinearLayoutManager(getActivity()));
classAndSubjectDetailsArrayList=new ArrayList<ClassAndSubjectDetails>();
classAndSubjectDetailsArrayList.add(new ClassAndSubjectDetails("MCA I","Operating System"));
classAndSubjectDetailsArrayList.add(new ClassAndSubjectDetails("MCA II","Oops"));
classAndSubjectDetailsArrayList.add(new ClassAndSubjectDetails("MCA II","Oops"));
classAndSubjectDetailsArrayList.add(new ClassAndSubjectDetails("M.Tech","System Design"));
classAndSubjectDetailsArrayList.add(new ClassAndSubjectDetails("B.tech.","Computer Network"));
classAndSubjectDetailsArrayList.add(new ClassAndSubjectDetails("MCA","Teleport System"));
classAndSubjectDetailsArrayList.add(new ClassAndSubjectDetails("MCA II","Operating System"));
classAndSubjectDetailsArrayList.add(new ClassAndSubjectDetails("MCA II","Oops"));
classAndSubjectDetailsArrayList.add(new ClassAndSubjectDetails("M.Tech","System Design"));
classAndSubjectDetailsArrayList.add(new ClassAndSubjectDetails("B.tech.","Computer Network"));
classAndSubjectDetailsArrayList.add(new ClassAndSubjectDetails("MCA","Teleport System"));
classAndSubjectDetailsArrayList.add(new ClassAndSubjectDetails("MCA II","Operating System"));
classAndSubjectDetailsArrayList.add(new ClassAndSubjectDetails("M.Tech","System Design"));
classAndSubjectDetailsArrayList.add(new ClassAndSubjectDetails("B.tech.","Computer Network"));
classAndSubjectDetailsArrayList.add(new ClassAndSubjectDetails("MCA","Teleport System"));
classAndSubjectDetailsArrayList.add(new ClassAndSubjectDetails("MCA II","Operating System"));
recyclerViewAdapterForClassList=new RecyclerViewAdapterForClassList(getContext(),classAndSubjectDetailsArrayList);
recyclerViewClass.setAdapter(recyclerViewAdapterForClassList);
/* binding.buttonSecond.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NavHostFragment.findNavController(SecondFragment.this)
.navigate(R.id.action_SecondFragment_to_FirstFragment);
}
});*/
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
}
fragment_second.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerViewClass"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/floatingActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="36dp"
android:layout_marginBottom="36dp"
android:clickable="true"
android:src="#android:drawable/ic_input_add"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
StudentListFragment.java
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class StudentListFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_student_list, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
RecyclerViewAdpaterForClassList.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;
import androidx.recyclerview.widget.RecyclerView;
import com.android.studentattendancerecorder.FirstFragment;
import com.android.studentattendancerecorder.Model.ClassAndSubjectDetails;
import com.android.studentattendancerecorder.R;
import com.android.studentattendancerecorder.SecondFragment;
import com.google.android.material.snackbar.Snackbar;
import java.util.List;
public class RecyclerViewAdapterForClassList extends RecyclerView.Adapter<RecyclerViewAdapterForClassList.ViewHolder> {
private Context context;
private List<ClassAndSubjectDetails> classAndSubjectDetailsList;
public RecyclerViewAdapterForClassList(Context context, List<ClassAndSubjectDetails> classAndSubjectDetailsList) {
this.context = context;
this.classAndSubjectDetailsList = classAndSubjectDetailsList;
}
//create card/item/holder
#NonNull
#Override
public RecyclerViewAdapterForClassList.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.classlistitem,parent,false);
return new ViewHolder(view);
}
//set details of each holder/card/item
#Override
public void onBindViewHolder(#NonNull RecyclerViewAdapterForClassList.ViewHolder holder, int position) {
ClassAndSubjectDetails classAndSubjectDetails=classAndSubjectDetailsList.get(position);
holder.class_name.setText(classAndSubjectDetails.getClass_name());
holder.subject_name.setText(classAndSubjectDetails.getSubject_name());
}
#Override
public int getItemCount() {
return classAndSubjectDetailsList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView class_name;
public TextView subject_name;
public ViewHolder(#NonNull View itemView) {
super(itemView);
itemView.setOnClickListener(this);
class_name=itemView.findViewById(R.id.className);
subject_name=itemView.findViewById(R.id.subjectName);
}
#Override
public void onClick(View v) {
}
}
}
fragment_student_list.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
tools:context=".StudentListFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
</FrameLayout>
ClassAndSubjectDetails.java
import androidx.annotation.NonNull;
public class ClassAndSubjectDetails {
private String class_name;
private String subject_name;
static int id=0;
public ClassAndSubjectDetails(String aClass, String subject) {
class_name = aClass;
subject_name = subject;
}
public String getClass_name() {
return class_name;
}
public void setClass_name(String class_name) {
this.class_name = class_name;
}
public String getSubject_name() {
return subject_name;
}
public void setSubject_name(String subject_name) {
this.subject_name = subject_name;
}
public static int getId() {
return id;
}
public static void setId(int id) {
ClassAndSubjectDetails.id = id;
}
}
classListItem.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 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="100dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/className"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:layout_marginTop="12dp"
android:text="MCA ( IIIrd Sem. )"
android:textAllCaps="true"
android:textColor="#000000"
android:textSize="34sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/subjectName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:layout_marginTop="3dp"
android:text="Object Oriented Programming"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/className" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
navGraph.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation 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/nav_graph"
app:startDestination="#id/FirstFragment">
<fragment
android:id="#+id/FirstFragment"
android:name="com.android.studentattendancerecorder.FirstFragment"
android:label="#string/first_fragment_label"
tools:layout="#layout/fragment_first">
<action
android:id="#+id/action_FirstFragment_to_SecondFragment"
app:destination="#id/SecondFragment" />
</fragment>
<fragment
android:id="#+id/SecondFragment"
android:name="com.android.studentattendancerecorder.SecondFragment"
android:label="#string/second_fragment_label"
tools:layout="#layout/fragment_second">
<action
android:id="#+id/action_SecondFragment_to_FirstFragment"
app:destination="#id/FirstFragment" />
<action
android:id="#+id/action_SecondFragment_to_studentListFragment"
app:destination="#id/studentListFragment" />
</fragment>
<fragment
android:id="#+id/studentListFragment"
android:name="com.android.studentattendancerecorder.StudentListFragment"
android:label="fragment_student_list"
tools:layout="#layout/fragment_student_list" >
<action
android:id="#+id/action_studentListFragment_to_SecondFragment"
app:destination="#id/SecondFragment" />
</fragment>
</navigation>
Perhaps it solves your problem.
Add interface in your viewModel
public interface CallListener{
public void myChoice(int position);
}
Create realisation it in your Fragment,
and give your viewModel in constructor
public RecyclerViewAdapterForClassList(Context context,
List<ClassAndSubjectDetails> classAndSubjectDetailsList, CallListener listener) {
this.context = context;
this.classAndSubjectDetailsList = classAndSubjectDetailsList;
this.listener = listener;
}
then add listener to your holder
holder.itemView.setOnClickListener((view) ->{
if (listener!= null) listener.myChoice(holder.getAdapterPosition());
});
or you can just call that
AppCompatActivity activity = ((AppCompatActivity) holder.itemView.getContext());
Navigation.findNavController(activity,R.id.nav_host_fragment_content_main).navigate(R.id.myFragment);

E/Volley: [6074] BasicNetwork.performRequest: Unexpected response code 403 for

activity_main.xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rView"
android:layout_width="409dp"
android:layout_height="729dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
2.activity_frame.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 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="500dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageView"
android:layout_width="411dp"
android:layout_height="360dp"
android:scaleType="centerCrop"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:srcCompat="#tools:sample/avatars"
android:contentDescription="#string/todo" />
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/textview1"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView"
app:layout_constraintVertical_bias="0.173" />
<TextView
android:id="#+id/textView2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/textview2"
android:maxLines="1"
android:ellipsize="end"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/textView1"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView1" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
HDNews.java
package com.example.android.hdnews;
public class HDNews {
private String title;
private String author;
private String image;
public HDNews(String title, String author, String image) {
this.title = title;
this.author = author;
this.image = image;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getImage() {
return image;
}
}
MainActivity.java
package com.example.android.hdnews;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.widget.LinearLayout;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ArrayList al;
private HDNewsAdapter hdNewsAdapter;
private RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView=findViewById(R.id.rView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
al=new ArrayList<HDNews>();
requestQueue= Volley.newRequestQueue(this);
extractingDataFromInternet();
}
//http://newsapi.org/v2/top-headlines?country=in&apiKey=94bf8bcc374b494485309e325e3656f9
public void extractingDataFromInternet(){
String url="http://newsapi.org/v2/top-headlines?country=in&category=business&apiKey=94bf8bcc374b494485309e325e3656f9";
JsonObjectRequest JsonObjReq=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("articles");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject ca = jsonArray.getJSONObject(i);
String authorNames = ca.optString("author");
String titleNames = ca.optString("title");
String imageUrls = ca.getString("urlToImage");
al.add(new HDNews(titleNames, authorNames, imageUrls));
}
hdNewsAdapter = new HDNewsAdapter(MainActivity.this, al);
recyclerView.setAdapter(hdNewsAdapter);
} catch ( JSONException e ) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(JsonObjReq);
}
}
HDNewsAdapter
package com.example.android.hdnews;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class HDNewsAdapter extends RecyclerView.Adapter<HDNewsAdapter.ViewHolder>{
private Context context;
private ArrayList<HDNews> al;
public HDNewsAdapter(Context context, ArrayList<HDNews> al) {
this.context = context;
this.al = al;
}
#NonNull
#Override
public HDNewsAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View views= LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_frame,parent,false);
return new ViewHolder(views);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
HDNews currentposition=al.get(position);
String imgurl=currentposition.getImage();
String athName=currentposition.getAuthor();
String ttleName=currentposition.getTitle();
holder.titleName01.setText(ttleName);
holder.authorName01.setText(athName);
Glide.with(context).load(imgurl).into(holder.imageurl01);
}
#Override
public int getItemCount() {
return al.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView authorName01;
public TextView titleName01;
public ImageView imageurl01;
public ViewHolder(#NonNull View itemView) {
super(itemView);
authorName01=itemView.findViewById(R.id.textView1);
titleName01=itemView.findViewById(R.id.textView2);
imageurl01=itemView.findViewById(R.id.imageView);
}
#Override
public void onClick(View view) {
}
}
}

Showing xml for correct view

When a user logs in to my app, they can either click the view students button or daily grading button. The view students will display a student's image and their name. The daily grading will display the student's image, name, and two checkboxes that says pass or fail. Now the issue I have is that the checkboxes for pass and fail are showing up in my activity_view_students.xml view when it should not be. It should only show when a user clicks daily grading. I will put images below to make it clearer
What it looks like in the activity_view_students.xml
What it should look like in activity_view_students.xml
I will paste all relevant code below.
ViewStudents.java
package com.example.studenttracker;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class ViewStudents extends AppCompatActivity {
RecyclerView recyclerView;
Button addStudent;
private DatabaseReference myRef;
public ArrayList<Students> students;
private RecyclerAdapter recyclerAdapter;
private Button orderStudents;
private EditText mEditTextAge;
private EditText mEditTextAssignment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_students);
recyclerView = findViewById(R.id.recyclerView);
addStudent = findViewById(R.id.addStudentButton);
mEditTextAge = findViewById(R.id.EditTextAge);
mEditTextAssignment = findViewById(R.id.EditTextAssignment);
orderStudents = findViewById(R.id.orderStudents);
addStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ViewStudents.this, AddStudent.class));
}
});
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
recyclerView.setHasFixedSize(true);
myRef = FirebaseDatabase.getInstance().getReference();
students = new ArrayList<>();
ClearAll();
GetDataFromFirebase();
}
private void GetDataFromFirebase() {
Query query = myRef.child("student");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
ClearAll();
for(DataSnapshot snapshot: dataSnapshot.getChildren()) {
Students student = new Students();
if (snapshot.child("url").getValue() == null) {
student.setImageUrl(snapshot.child("imageUrl").getValue().toString());
}
else {
student.setImageUrl(snapshot.child("url").getValue().toString());
}
// student.setAge(mEditTextAge.getText().toString());
// student.setAssignment(mEditTextAssignment.getText().toString().trim());
student.setName(snapshot.child("name").getValue().toString());
students.add(student);
}
recyclerAdapter = new RecyclerAdapter(getApplicationContext(), students);
recyclerView.setAdapter(recyclerAdapter);
recyclerAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void ClearAll() {
if (students != null) {
students.clear();
if(recyclerAdapter != null) {
recyclerAdapter.notifyDataSetChanged();
}
}
students = new ArrayList<>();
}
public void orderStudents(View view) {
Collections.sort( students, new Comparator<Students>() {
#Override
public int compare( Students o1, Students o2 ) {
return o1.name.compareTo( o2.name );
}
});
recyclerAdapter.notifyDataSetChanged();
}
}
RecyclerAdapter.java
package com.example.studenttracker;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
private static final String Tag = "RecyclerView";
private Context mContext;
private ArrayList<Students> studentsArrayList;
public RecyclerAdapter(Context mContext, ArrayList<Students> studentsArrayList) {
this.mContext = mContext;
this.studentsArrayList = studentsArrayList;
}
#NonNull
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_student_item,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
//TextView
holder.textView.setText(studentsArrayList.get(position).getName());
Glide.with(mContext).load(studentsArrayList.get(position).getImageUrl()).into(holder.imageView);
// if (studentsArrayList.get(position).get) { //check if you need the buttons or not
// holder..setVisibility(View.VISIBLE);
// holder.checkBox2.setVisibility(View.VISIBLE);
// } else {
// holder.checkBox.setVisibility(View.GONE);
// holder.checkBox2.setVisibility(View.GONE);
// }
}
#Override
public int getItemCount() {
return studentsArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView textView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
textView = itemView.findViewById(R.id.textView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
}
}
});
}
}
}
activity_view_students.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ViewStudents">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="409dp"
android:layout_height="729dp"
android:layout_marginEnd="1dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" >
</androidx.recyclerview.widget.RecyclerView>
<Button
android:id="#+id/addStudentButton"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:text="Add Students"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/orderStudents"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="orderStudents"
android:text="Order Students"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
daily_grading.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DailyGrading">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="409dp"
android:layout_height="729dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
activity_student_item.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".DailyGrading">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:foreground="?android:attr/selectableItemBackground"
app:cardElevation="2dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</androidx.cardview.widget.CardView>
<RelativeLayout
android:id="#+id/relativeLayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="52dp">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginTop="50dp"
android:paddingTop="20dp"
android:scaleType="centerCrop" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView"
android:layout_margin="10dp"
android:textSize="16sp" />
<CheckBox
android:id="#+id/passc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textView"
android:text="PASS" />
<CheckBox
android:id="#+id/failc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textView"
android:layout_toRightOf="#+id/passc"
android:text="FAIL" />
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
GradingRecyclerAdapter
package com.example.studenttracker;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class GradingRecyclerAdapter extends RecyclerView.Adapter<GradingRecyclerAdapter.ViewHolder> {
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
private static final String Tag = "RecyclerView";
private Context mContext;
private ArrayList<Students> studentsArrayList;
public GradingRecyclerAdapter(Context mContext, ArrayList<Students> studentsArrayList) {
this.mContext = mContext;
this.studentsArrayList = studentsArrayList;
}
#NonNull
#Override
public GradingRecyclerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_grading_student_item,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
//TextView
holder.textView.setText(studentsArrayList.get(position).getName());
Glide.with(mContext).load(studentsArrayList.get(position).getImageUrl()).into(holder.imageView);
}
#Override
public int getItemCount() {
return studentsArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView textView;
Button passButton;
Button failButton;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
textView = itemView.findViewById(R.id.textView);
passButton = itemView.findViewById(R.id.PASS);
failButton = itemView.findViewById(R.id.FAIL);
// passButton.setVisibility(View.GONE);
// failButton.setVisibility(View.GONE);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
}
}
});
}
}
}
activity_grading_student_item
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".DailyGrading">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:foreground="?android:attr/selectableItemBackground"
app:cardElevation="2dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</androidx.cardview.widget.CardView>
<RelativeLayout
android:id="#+id/relativeLayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="52dp">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginTop="50dp"
android:paddingTop="20dp"
android:scaleType="centerCrop" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView"
android:layout_margin="10dp"
android:textSize="16sp" />
<CheckBox
android:id="#+id/PASS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textView"
android:text="PASS" />
<CheckBox
android:id="#+id/FAIL"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textView"
android:layout_toRightOf="#+id/PASS"
android:text="FAIL" />
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
You can simply use different adapters
create another activity_student_item.xml let's say activity_view_student_item.xml and remove the checkboxes from that one
create another adapter for that recyclerView but change
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_student_item,parent,false);
in the new adapter to
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_view_student_item,parent,false);
and in the ViewStudents activity set the recycler's Adapter to that new adapter

null object reference on set adapter

I know that there are a lot of question like this, but i can't find one that can help me. Please pay no attention at strings that are hard coded or other things like that, i will fix. I don't see anything wrong in adapter class or in the fragments. I use Disco class for fill a place list, the Place class contains all the methods that after i use in the adapter.Can anyone help me please? Thank you.
Class MainActivity
package com.techmind.tourguideapp;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager manager = getSupportFragmentManager();
ViewPager pager = findViewById(R.id.tourPager);
pager.setAdapter(new FragmentAdapter(manager));
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(pager);
}
}
class Disco
package com.techmind.tourguideapp;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Nahuel on 31.05.2018.
*/
public class Disco {
public static ArrayList<Places> initDiscoList(ArrayList<Places> places) {
places.add(new Places().
setAddress("via a").
setImage(1).
setName("casino").
setPhone("333").
setPrice("20€").
setHour("10:30"));
return places;
}
}
Class DiscoFragment
package com.techmind.tourguideapp;
import android.support.v4.app.Fragment;
import android.location.Location;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Nahuel on 31.05.2018.
*/
public class DiscoFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ArrayList<Places> list = new ArrayList<>();
list = Disco.initDiscoList(list);
PlacesAdapter adapter = new PlacesAdapter(getActivity(), list);
View view = inflater.inflate(R.layout.row_item, container, false);
ListView listView = (ListView) view.findViewById(R.id.list_items);
listView.setAdapter(adapter);
return view;
}
}
Class FragmentAdapter
package com.techmind.tourguideapp;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/**
* Created by Nahuel on 31.05.2018.
*/
public class FragmentAdapter extends FragmentPagerAdapter {
public FragmentAdapter (FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new DiscoFragment();
}
#Override
public int getCount() {
return 3;
}
public CharSequence getPageTitle(int position) {
return "Gradara";
}
}
Class Places
package com.techmind.tourguideapp;
/**
* Created by Nahuel on 31.05.2018.
*/
public class Places {
private String name;
private String price;
private String phone;
private String Address;
private String hour;
private int image;
private final int NO_IMAGE = -1;
public Places () {
}
public String getHour() {
return hour;
}
public String getName() {
return name;
}
public String getPrice() {
return price;
}
public String getPhone() {
return phone;
}
public String getAddress() {
return Address;
}
public int getImage() {
return image;
}
public Places setName(String name) {
this.name = name;
return this;
}
public Places setHour(String hour) {
this.hour = hour;
return this;
}
public Places setPrice(String price) {
this.price = price;
return this;
}
public Places setPhone(String phone) {
this.phone = phone;
return this;
}
public Places setAddress(String address) {
Address = address;
return this;
}
public Places setImage(int image) {
this.image = image;
return this;
}
}
Class PlaceAdapter
package com.techmind.tourguideapp;
import android.content.Context;
import android.location.Location;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class PlacesAdapter extends ArrayAdapter<Places> {
public PlacesAdapter(Context context, List<Places> places) {
super(context,-1, places);
}
public View getView (int position, ViewGroup parent, View convertView) {
View listView = convertView;
Places place = getItem(position);
if(listView == null) {
listView = LayoutInflater.from(getContext()).inflate(
R.layout.row_item, parent, false);
}
TextView location = listView.findViewById(R.id.locationName);
location.setText("casino");
TextView hour = listView.findViewById(R.id.txthour);
hour.setText("aaa");
TextView address = listView.findViewById(R.id.address);
address.setText("aaaaa");
TextView price = listView.findViewById(R.id.txtmoney);
price.setText("aaaaa");
TextView phone = listView.findViewById(R.id.phone);
phone.setText("aaaaa");
ImageView img = listView.findViewById(R.id.imgRow);
img.setImageResource(R.drawable.ic_launcher_background);
return listView;
}
}
Activity_Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.techmind.tourguideapp.MainActivity">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMaxWidth="0dp"
/>
<android.support.v4.view.ViewPager
android:id="#+id/tourPager"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
List_item.xml
</LinearLayout>
<?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">
<ListView
android:id="#+id/list_items"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
Row_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="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/imgRow"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:src="#drawable/gradara" />
<TextView
android:id="#+id/locationName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="24sp"
android:textStyle="bold"
android:text=""/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="0.5">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp">
<ImageView
android:id="#+id/positionIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:src="#mipmap/position"
android:layout_alignParentStart="true"/>
<TextView
android:id="#+id/txtPosition"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/positionIcon"
android:layout_marginTop="5dp"
android:text="" />
<TextView
android:id="#+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/positionIcon"
android:layout_toRightOf="#id/positionIcon"
android:text="" />
</RelativeLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp">
<ImageView
android:id="#+id/moneyIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:src="#mipmap/money"
android:layout_alignParentStart="true"/>
<TextView
android:id="#+id/txtmoney"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/moneyIcon"
android:layout_marginTop="15dp"
android:text="10€ - 20€" />
</LinearLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp">
<ImageView
android:id="#+id/hourIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:src="#mipmap/hour"
android:layout_alignParentStart="true"/>
<TextView
android:id="#+id/txthour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/hourIcon"
android:layout_marginTop="15dp"
android:text="09:30 - 23:00" />
</RelativeLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone:"
android:layout_marginEnd="5dp"
android:textStyle="bold"/>
<TextView
android:id="#+id/phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3334323560"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
You said you got a null pointer on set adapter. Are you talking about
this line in file DiscoFragment?
listView.setAdapter(adapter)
if listView is null then the findViewByID didn't find a view. Or maybe something inside adapter is null. It is hard to tell from what you said.
i found the error in
ArrayList<Places> list = new ArrayList<>();
list = Disco.initDiscoList(list);
PlacesAdapter adapter = new PlacesAdapter(getActivity(), list);
View view = inflater.inflate(R.layout.row_item, container, false);
ListView listView = (ListView) view.findViewById(R.id.list_items);
listView.setAdapter(adapter);
return view;
}
When i use the inflate method the first parameter was wrong, i used the layout of the row instead of the listView layout.
Thank you for your answers, next times i will post logs and less useless code :)

Categories