Passing context for a radio group in a fragment instead of activity? - android-studio

I'm trying to use a RadioGroup widget inside a fragment instead of an activity. I'm getting an error on the following line of code:
RadioButton button = new RadioButton(this);
I'm not sure what to pass instead of 'this'
I believe the problem is either in the snippet above or here:
RadioGroup group = (RadioGroup) getView().findViewById(R.id.radioGroup);
Full code:
public class fragment1 extends Fragment {
private Button btnNextFrag;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment1_layout, container, false);
createRadioButtons();
return view;
}
private void createRadioButtons() {
RadioGroup group = (RadioGroup) getView().findViewById(R.id.radioGroup);
String[] questions1 = getResources().getStringArray(R.array.question_1_answers);
for (int i=0;i<questions1.length;i++){
String question = questions1[i];
RadioButton button = new RadioButton(this);
button.setText(question);
group.addView(button);
}
}
}

The constructor requires context so use getActivity() instead of this. You can also use getContext().

public class fragment1 extends Fragment {
private Button btnNextFrag;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment1_layout, container, false);
createRadioButton(view);
return view;
}
private void createRadioButton(View view) {
RadioGroup group = (RadioGroup)view.findViewById(R.id.radioGroup);
String[] questions1 = getResources().getStringArray(R.array.question_1_answers);
for (int i=0;i<questions1.length;i++){
String question = questions1[i];
RadioButton button = new RadioButton(getActivity());
button.setText(question);
group.addView(button);
}
}
}

Related

Cannot infer arguments (unable to resolve constructor)

I am trying to make a program with a tablayout, each tab representing a fragment. In the second fragment (AddFragment), im want to make a list that displays the strings I entered in the EditText. But its giving me the error above. More detailed:
error: cannot infer type arguments for ArrayAdapter<>
itemsAdapter = new ArrayAdapter<>(AddFragment.this, android.R.layout.simple_list_item_1, items);
Code for the AddFragment class:
public class AddFragment extends Fragment {
EditText etPlan;
EditText etExercise;
ImageButton imageButton;
ArrayList<String> items;
ArrayAdapter<String> itemsAdapter;
ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_add, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
findViews();
super.onViewCreated(view, savedInstanceState);
}
private void findViews() {
listView = getView().findViewById(R.id.listView);
etPlan = getView().findViewById(R.id.etPlan);
etExercise = getView().findViewById(R.id.etExercise);
imageButton = getView().findViewById(R.id.imageButton);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
items = new ArrayList<>();
itemsAdapter = new ArrayAdapter<>(AddFragment.this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(itemsAdapter);
setUpListViewListener();
}
private void setUpListViewListener() {
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Context context = getContext();
Toast.makeText(context, "Item Removed", Toast.LENGTH_LONG).show();
items.remove(position);
itemsAdapter.notifyDataSetChanged();
return true;
}
});
}
});
}
}
The declaration that you have works if working directly in the activity JAVA file. While working in the fragment, you need to establish clearly the type of argument and provide the correct context.
The following should work (assuming that you are passing strings):
itemsAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);

use Onclick in extends PagerAdapter

Hi I’m trying to create a horizontal slide where each horizontal page will have a button that will call a Dialog but onClick is not working in extends Pageradapter can anyone tell me what I’m doing wrong?
I gave the name onClickApprove to onClick that I want you to call Dialog. This Dialog is calling an Activity with a Ratingbar to make an assessment.
Thank you.
public class SliderAdapterUsado extends PagerAdapter {
Context context;
LayoutInflater layoutInflater;
BottomSheetDialog dialog;
Button show;
public SliderAdapterUsado(Context context){
this.context = context;
}
public String[] slide_rota ={
"Titulo1",
"Titulo2"
};
public String[] slide_nome={
"Descrção do titulo 1",
"Descrção do titulo 2"
};
#Override
public int getCount(){
return slide_rota.length;
}
#Override
public boolean isViewFromObject(View view, Object object){
return view == (LinearLayout) object;
}
#Override
public Object instantiateItem(ViewGroup container, int position){
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.slide_layout_usados, container, false);
TextView slideHeading = view.findViewById(R.id.slide_rota);
TextView slideDescricao = view.findViewById(R.id.slide_nome);
slideHeading.setText(slide_rota[position]);
slideDescricao.setText(slide_nome[position]);
container.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object){
container.removeView((LinearLayout)object);
}
public void onClickAvaliar(View view) {
show = view.findViewById(R.id.show);
dialog = new BottomSheetDialog(dialog.getContext());
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createDialog();
dialog.show();
}
});
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
}
private void createDialog(){
View view = layoutInflater.inflate(R.layout.activity_rating, null, false);
Button FeedBack = view.findViewById(R.id.FeedBack);
FeedBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.setContentView(view);
}
}
Please read the documentation.
Note this in particular (emphasis mine):
To define the click event handler for a button, add the android:onClick attribute to the element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.
The expectation is that the value set on the onClick xml attribute will be a method on the hosting Activity. Yours is in the adapter. That's why it doesn't work.
So either move that method to the hosting activity, or just handle the click event explicitly:
...
TextView slideHeading = view.findViewById(R.id.slide_rota);
TextView slideDescricao = view.findViewById(R.id.slide_nome);
Button slideButton = view.findViewById(R.id.slide_button);
slideButton.setOnClickListener (...)
...

How do I put the adapter into the viewpager?

This is the code of MyPageAdapter
public class MyPageAdapter extends PagerAdapter {
int[] images = {R.drawable.img1, R.drawable.img2, R.drawable.img3, R.drawable.img4, R.drawable.img5, R.drawable.img6, R.drawable.img7, R.drawable.img8, R.drawable.img9, R.drawable.img10, R.drawable.img11, R.drawable.img12, R.drawable.img13
, R.drawable.img14, R.drawable.img15, R.drawable.img16, R.drawable.img17, R.drawable.img18, R.drawable.img19, R.drawable.img20, R.drawable.img21, R.drawable.img22, R.drawable.img23, R.drawable.img24
, R.drawable.img25, R.drawable.img26, R.drawable.img27, R.drawable.img28, R.drawable.img29, R.drawable.img30};
private LayoutInflater inflater;
private Context context;
public MyPageAdapter(Context context){
this.context = context;
}
#Override
public int getCount() {
return images.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == ((LinearLayout)object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.fragment_slideshow, container, false);
EditText editText = v.findViewById(R.id.editTextNumberDecimal);
ImageView imageView = (ImageView)v.findViewById(R.id.imageView2);
imageView.setImageResource(images[position]);
int text = position+1;
editText.setText(text);
container.addView(v);
return v;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.invalidate();
}
}
AND this is the code of SlideshowFragment.
public class SlideshowFragment extends Fragment {
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_slideshow, container, false);
ViewPager2 viewPager2 = (ViewPager2) root.findViewById(R.id.pager);
MyPageAdapter adapter = new MyPageAdapter(this);
viewPager2.setAdapter(adapter);
return root;
}
}
I would like to add a view pager to the slide fragment so that 30 photos can be viewed as a slide show.
But I can't do setAdapter in viewpager.
Really, is there anything other than a way to make and put each fragment for each of the 30 pictures?
Please let me know how to modify my code.
You are mixing Viewpager and Viewpager2 these are implemented in 2 totally different ways.
try
ViewPager viewPager = (ViewPager) root.findViewById(R.id.pager);
MyPageAdapter adapter = new MyPageAdapter(this);
viewPager.setAdapter(adapter);
and change your xml to also be a ViewPager widget.
Alternatively you could probably change your adapter to a RecyclerView.Adapter https://developer.android.com/reference/androidx/recyclerview/widget/RecyclerView.Adapter
As Viewpager2 is just a customised RecyclerView.

Android Studio recyclerview No adapter attached; skipping layout

Hello everyone i have a problem with recyclerview
the app works in my emulator bluestacks but when I started testing on other devices the program gives such an error recyclerview No adapter attached; skipping layout
this fragment activity code:
public class AsosiyFragment extends Fragment {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.form_asosiy, container, false);
return rootView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
DBAdapter mDBAdapter = new DBAdapter(getContext());
Spinner spinner_viloyatlar = view.findViewById(R.id.spinner_viloyatlar);
RecyclerView recyclerView = view.findViewById(R.id.roza_vaqtlari);
recyclerView.setHasFixedSize(true);
Context context = view.getContext();
LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
List<RamazonAdapter> ramazonAdapters = new ArrayList<>();
ramazonAdapters.clear();
String[] VILOYAT_NOMI_KIRIL = {
"Андижон","Бухоро",
"Жиззах","Қашқадарё",
"Қорақалпоғистон","Навоий",
"Наманган","Самарқанд",
"Сурхондарё","Сирдарё",
"Тошкент","Фарғона",
"Хоразм"
};
// Add viloyatlar to spinner
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i <= 12; i++){
list.add(VILOYAT_NOMI_KIRIL[i]);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),R.layout.spinner_item,R.id.item,list);
spinner_viloyatlar.setAdapter(adapter);
// get all data from sqlite
Cursor res = mDBAdapter.getAllData();
final RamazonAdapter[] rAdapters = {null};
while (res.moveToNext()){
String data1 = res.getString(1);
String data2 = res.getString(2);
String data3 = res.getString(3);
String data4 = res.getString(4);
rAdapters[0] = new RamazonAdapter(data1,data2,data3,data4);
ramazonAdapters.add(rAdapters[0]);
Adapter adapter1 = new Adapter(getActivity(), ramazonAdapters);
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter1);
}
}
}
this adapter:
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder>{
Context context;
private List<RamazonAdapter> ramazonAdapterList;
public Adapter(Context context, List<RamazonAdapter> ramazonAdapterList){
this.context = context;
this.ramazonAdapterList = ramazonAdapterList;
}
#NonNull
#Override
public Adapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.ramazon_item,parent,false);
return new Adapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull Adapter.ViewHolder holder, int position) {
RamazonAdapter ramazonAdapter = ramazonAdapterList.get(position);
holder.nameOfDay.setText(ramazonAdapter.getNameOfDay());
holder.dateOfRoza.setText(ramazonAdapter.getDate());
holder.iftorlikTime.setText(ramazonAdapter.getIftorlikTime());
holder.saharlikTime.setText(ramazonAdapter.getSaharlikTime());
}
#Override
public int getItemCount() {
return ramazonAdapterList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView nameOfDay;
TextView dateOfRoza;
TextView iftorlikTime;
TextView saharlikTime;
public ViewHolder(#NonNull View itemView) {
super(itemView);
nameOfDay = itemView.findViewById(R.id.nameOfDay);
dateOfRoza = itemView.findViewById(R.id.dateOfRoza);
iftorlikTime = itemView.findViewById(R.id.iftorlikTime);
saharlikTime = itemView.findViewById(R.id.saharlikTime);
}
}
}
I found several answers on this topic and tried them but I didn’t succeed help please
I think the error you are facing is due to the below line code
Adapter adapter1 = new Adapter(getActivity(), ramazonAdapters);
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter1);
in the above block of code you are trying to notify an adapter before setting the adapter to recyclerview

Getting Error while using "this"

Getting Error when using "this" in fragement,instead of that what can i use.Below is the given code:
public class Tab1 extends Fragment {
private List<DataJobs> datajobs = new ArrayList<>();
private RecyclerView recyclerView;
private EventsAdapter mAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab_1, container, false);
return rootView;
recyclerView = (RecyclerView)getView().findViewById(R.id.recycler_view);
mAdapter = new EventsAdapter(datajobs);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new DividerItemDecoration(**this**, LinearLayoutManager.VERTICAL));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
prepareMovieData();
}
Use getActivity() instead
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL));

Resources