how to convert Activity to Fragment? [duplicate] - android-fragments

This question already has answers here:
converting activity into fragment
(4 answers)
Closed 7 months ago.
I have this code but every time i try to change this to fragment I always get an error. Can anyone please help me with this?
this is my RecyclerViewAdapter with cardview
public class RecyclerViewAdapter extendsRecyclerView.Adapter {
private Context mContext ;
private List<Book> mData ;
public RecyclerViewAdapter(Context mContext, List<Book> mData) {
this.mContext = mContext;
this.mData = mData;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view ;
LayoutInflater mInflater = LayoutInflater.from(mContext);
view = mInflater.inflate(R.layout.cardveiw_item_book,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.tv_book_title.setText(mData.get(position).getTitle());
holder.img_book_thumbnail.setImageResource(mData.get(position).getThumbnail());
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext,Book_Activity.class);
// passing data to the book activity
intent.putExtra("Title",mData.get(position).getTitle());
intent.putExtra("Description",mData.get(position).getDescription());
intent.putExtra("Thumbnail",mData.get(position).getThumbnail());
// start the activity
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv_book_title;
ImageView img_book_thumbnail;
CardView cardView ;
public MyViewHolder(View itemView) {
super(itemView);
tv_book_title = (TextView) itemView.findViewById(R.id.book_title_id) ;
img_book_thumbnail = (ImageView) itemView.findViewById(R.id.book_img_id);
cardView = (CardView) itemView.findViewById(R.id.cardview_id);
}
}
}
this is for MainActivity
public class MainActivity extends AppCompatActivity {
List<Book> lstBook ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstBook = new ArrayList<>();
lstBook.add(new Book("The Vegitarian","Categorie Book","Description book",R.drawable.thevigitarian));
lstBook.add(new Book("The Wild Robot","Categorie Book","Description book",R.drawable.thewildrobot));
lstBook.add(new Book("Maria Semples","Categorie Book","Description book",R.drawable.mariasemples));
lstBook.add(new Book("The Martian","Categorie Book","Description book",R.drawable.themartian));
RecyclerView myrv = (RecyclerView) findViewById(R.id.reyclerview_id);
RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(this,lstBook);
myrv.setLayoutManager(new GridLayoutManager(this,2));
myrv.setAdapter(myAdapter);
}
}
how to convert my Main Activity to fragment?

Its super simple
public class MainActivity extends Fragment {
List<Book> lstBook ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lstBook = new ArrayList<>();
lstBook.add(new Book("The Vegitarian","Categorie Book","Description book",R.drawable.thevigitarian));
lstBook.add(new Book("The Wild Robot","Categorie Book","Description book",R.drawable.thewildrobot));
lstBook.add(new Book("Maria Semples","Categorie Book","Description book",R.drawable.mariasemples));
lstBook.add(new Book("The Martian","Categorie Book","Description book",R.drawable.themartian));
}
#Nullable #Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main,container)
RecyclerView myrv = (RecyclerView) view.findViewById(R.id.reyclerview_id);
RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(getActivity(),lstBook);
myrv.setLayoutManager(new GridLayoutManager(this,2));
myrv.setAdapter(myAdapter)
return view;
}
}

Related

Why are my floating action buttons not working properly in my ViewPager?

I have a ViewPager set up with my app and am trying to also set two floating action buttons, a left one and a right one, to do the same thing as the ViewPager, so that the user has a choice in terms of navigation. I'm trying to have it set so that the left button is invisible on the first page, and the right button is invisible on the last page, but the appearances of the buttons seem to be sporadic. I've tried debugging the app, and upon testing each situation, the appropriate code is executed, so I can't understand why this behavior is happening. Any help would be appreciated.
TestFragment:
public class TestFragment extends Fragment {
public static final String ARG_ID = "Id";
private int Id;
private String title;
private TextView titleTV;
private String description;
private TextView descriptionTV;
private int number;
private TextView numberTV;
private FloatingActionButton leftBtn;
private FloatingActionButton rightBtn;
public static TestFragment newInstance(int Id) {
Bundle args = new Bundle();
args.putSerializable(ARG_ID, Id);
TestFragment fragment = new TestFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_test, container, false);
Id = getArguments().getInt(ARG_ID);
title = Test.testData[Id].getTitle();
description = Test.testData[Id].getDescription();
number = Test.testData[Id].getNumber();
titleTV = view.findViewById(R.id.title);
titleTV.setText(title);
descriptionTV = view.findViewById(R.id.description);
descriptionTV.setText(description);
numberTV = view.findViewById(R.id.number);
numberTV.setText(String.valueOf(number));
leftBtn = view.findViewById(R.id.left_btn);
rightBtn = view.findViewById(R.id.right_btn);
toggleButtons();
leftBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
testViewPager.setCurrentItem(--index);
toggleButtons();
}
});
rightBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
testViewPager.setCurrentItem(++index);
toggleButtons();
}
});
return view;
}
public void toggleButtons() {
if(index == 0) {
leftBtn.setVisibility(View.INVISIBLE);
}
else if(index == Test.testData.length - 1) {
rightBtn.setVisibility(View.INVISIBLE);
}
else {
leftBtn.setVisibility(View.VISIBLE);
rightBtn.setVisibility(View.VISIBLE);
}
}
}
TestPagerActivity:
public class TestPagerActivity extends AppCompatActivity {
public static int index;
public static ViewPager testViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_pager);
index = (int) getIntent().getSerializableExtra(EXTRA_ID);
testViewPager = findViewById(R.id.test_view_pager);
FragmentManager fragmentManager = getSupportFragmentManager();
testViewPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {
#Override
public Fragment getItem(int position) {
return TestFragment.newInstance(position);
}
#Override
public int getCount() {
return Test.testData.length;
}
});
for(int i = 0; i < Test.testData.length; i++) {
if(i == index) {
testViewPager.setCurrentItem(i);
break;
}
}
}
}

send data from popup to tabbed activity having fragments

mainActivity has button. After button is clicked a popup message show having a button and a TextInputLayout.
data is sent to a tabbed acticity having 2 fragments and
the data is shown in textview of first fragment. Error is the data wont show in the textview while running
adapter for 2 fragments--
public class adapter extends FragmentPagerAdapter {
public adapter(#NonNull FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int position) {
Fragment fragment;
if (position == 1) {
fragment = new SecondFragment();
} else {
fragment = new FirstFragment();
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
String title = null;
if (position == 0) {
title = "TextView";
} else if (position == 1) {
title = "Listview";
}
return title;
}
}
mainActivity
myDialog = new Dialog(this);
}
//for for joining match
public void ShowPopup(View view) {
myDialog.setContentView(R.layout.popup);
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
myDialog.show();
name = myDialog.findViewById(R.id.ig_name);
String igname = Objects.requireNonNull(name.getEditText()).getText().toString();
entry = myDialog.findViewById(R.id.entry);
entry.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), secondActivity.class);
intent.putExtra("igname", igname);
startActivity(intent);
finish();
});
}
}
my firstFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_first, container, false);
secondActivity activity = (secondActivity) getActivity();
TextView output = view.findViewById(R.id.textshow);
Bundle results = activity.getMyData();
String value1 = results.getString("value");
output.setText(value1);
return view;
}
secondActivity (intent is transfered from popup window)
public class secondActivity extends AppCompatActivity {
private String name;
TabLayout tabLayout;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(new adapter(getSupportFragmentManager()));
tabLayout = findViewById(R.id.tabs_layout);
tabLayout.setupWithViewPager(viewPager);
Intent intent = getIntent();
name = intent.getExtras().getString("igname");
}
public Bundle getMyData() {
Bundle bundle = new Bundle();
bundle.putString("value", name);
return bundle;
}
}

Search in Fragments that hold Recyclerview

I have 3 Fragments and they all are holding a recyclerView. But I don't know how I should call adapter.getFilter().filter(newText); in onQueryTextChange. Any ideas?
MainActivity:
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDB;
private BottomNavigationView bottomNavigationView;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
myDB = new DatabaseHelper(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//----Start Bottom Navigation Bar
bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(bottomNavMethod);
getSupportFragmentManager().beginTransaction().replace(R.id.container, new PasswortFragment()).commit();
String id = getResources().getResourceEntryName(bottomNavigationView.getId());
//----End Bottom Navigation Bar
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return true;
}
private BottomNavigationView.OnNavigationItemSelectedListener bottomNavMethod =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
switch(item.getItemId()){
case R.id.passwoerter:
fragment = new PasswortFragment();
break;
case R.id.bankdaten:
fragment = new BankdatenFragment();
break;
case R.id.kreditkarten:
fragment = new KreditkartenFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
return true;
}
};
#Override
public void onBackPressed() {
super.onBackPressed();
Fragment f = MainActivity.this.getSupportFragmentManager().findFragmentById(R.id.container);
if(f instanceof PasswortFragment)
recyclerView = findViewById(R.id.recyclerViewPasswoerter);
if(f instanceof KreditkartenFragment)
recyclerView = findViewById(R.id.recyclerViewKreditkarten);
if(f instanceof BankdatenFragment)
recyclerView = findViewById(R.id.recyclerViewBankdaten);
}
#Override
public boolean onCreateOptionsMenu(#NonNull Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
recyclerView.getAdapter().getFilter().filter(newText); //<--This is not working
return false;
}
});
return true;
}
Adapter:
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> implements Filterable{
String type;
List<String> dataAll, data1;
Context context;
public Adapter(Context ct, List<String> s1, String typ){
context = ct;
data1 = s1;
type = typ;
dataAll = new ArrayList<>(data1);
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.reihen, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
holder.mytext1.setText(data1.get(position));
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(type.equals("Passwoerter")){
Intent intent = new Intent(context, DetailsP.class);
intent.putExtra("data1", data1.get(position));
context.startActivity(intent);
} else if(type.equals("Kreditkarten")){
Intent intent = new Intent(context, DetailsK.class);
intent.putExtra("data1", data1.get(position));
context.startActivity(intent);
} else if(type.equals("Bankdaten")){
Intent intent = new Intent(context, DetailsB.class);
intent.putExtra("data1", data1.get(position));
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return data1.size();
}
#Override
public Filter getFilter() {
return filter;
}
private Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<String> filteredList = new ArrayList<>();
if(constraint == null || constraint.length() == 0){
filteredList.addAll(dataAll);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for(String item: dataAll){
if(item.toLowerCase().contains(filterPattern)){
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
data1.clear();
data1.addAll( (List) results.values);
notifyDataSetChanged();
}
};
;
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView mytext1;
ConstraintLayout mainLayout;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
mytext1 = itemView.findViewById(R.id.title);
mainLayout = itemView.findViewById(R.id.mainLayout);
}
}
PasswortFragment (the other two fragments are pretty much the same):
public class PasswortFragment extends Fragment {
public PasswortFragment() {
// Required empty public constructor
}
RecyclerView recyclerView;
String tabelle = "Passwort";
List<String> titel;
DatabaseHelper myDB;
Adapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_passwort, container, false);
myDB = new DatabaseHelper(getActivity());
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerViewPasswoerter);
titel = Arrays.asList(myDB.getItems(tabelle));
final LinearLayoutManager layoutManager = new LinearLayoutManager((getActivity()));
layoutManager.setOrientation((LinearLayoutManager.VERTICAL));
recyclerView.setLayoutManager(layoutManager);
adapter = new Adapter(getActivity(), titel, "Passwoerter");
recyclerView.setAdapter(adapter);
setHasOptionsMenu(true);
return view;
}

how to make 2 recyclerView beside each others using firebase UI?

hi I am using Firebase recyclerview UI and I succeed to perform one RecyclerView, but when I continue to add the second, the application creates error.
The question is how to add 2 recyclers in the same activity with very simple form? I just want them beside each others.
How can I do that?
this is my code
public class HarvestingActivity extends AppCompatActivity {
RecyclerView T;
RecyclerView S;
DatabaseReference mRefTot;
DatabaseReference mRefSin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.activity_harvesting);
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
assert currentUser != null;
T = (RecyclerView) findViewById(R.id.recyclerviewT);//this is for total
T.setLayoutManager(new LinearLayoutManager(this));
T.setHasFixedSize(true);
S = (RecyclerView) findViewById(R.id.recyclerviewS);//this is for single
S.setLayoutManager(new LinearLayoutManager(this));
S.setHasFixedSize(true);
mRefTot = FirebaseDatabase.getInstance().getReference()
.child("HarvestingActivity")
.child("TotalActivity");
FirebaseRecyclerAdapter<TotalUsers, TotalUsersHolder> T_Adapter = new FirebaseRecyclerAdapter<TotalUsers, TotalUsersHolder>(
TotalUsers.class,
R.layout.h_item_user_total,
TotalUsersHolder.class,
mRefTot
) {
#Override
protected void populateViewHolder(TotalUsersHolder viewHolder, TotalUsers model, int position) {
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
assert currentUser != null;
viewHolder.setName(model.getName());
}
};
mRefSin=FirebaseDatabase.getInstance().getReference()
.child("HarvestingActivity")
.child("SingleActivity");
FirebaseRecyclerAdapter<SingleUser,SingleUserHolder>
S_Adapter=new
FirebaseRecyclerAdapter<SingleUser,SingleUserHolder>(
SingleUser.class,
R.layout.h_item_users_single,
SingleUserHolder.class,
mRefSin
) {
#Override
protected void populateViewHolder(SingleUserHolder viewHolder,
SingleUser model, int position) {
FirebaseUser currentUser =
FirebaseAuth.getInstance().getCurrentUser();
assert currentUser != null;
viewHolder.setName(model.getName());
}
};
T.setAdapter(T_Adapter);
S.setAdapter(S_Adapter);
}
public static class TotalUsersHolder extends RecyclerView.ViewHolder {
View view;
public TotalUsersHolder(View itemView) {
super(itemView);
view = itemView;
}
public void setName(String name) {
TextView Harvester_Name = (TextView) view.findViewById(R.id.HarvesterName);
Harvester_Name.setText(name);
}
}
private class SingleUserHolder extends RecyclerView.ViewHolder {
View sview;
public SingleUserHolder(View itemView) {
super(itemView);
sview=itemView;
}
public void setName(String name) {
TextView Answer_Name = (TextView)
sview.findViewById(R.id.AnswerName);
Answer_Name.setText(name);
}
}
}

Can't change the fragment's TextView on realtime

So I got 2 fragments and an activity. Those 2 fragments are communicating each other via an interface.
Problem is, I can't change the TextView in the second fragment from Activity wih some text from fragment1.
There is the same problem( How to change fragment's textView's text from activity ) but there is no real solution so i thought i should open this.
Fragment 1:
public class test_layout extends Fragment {
DearListener activityCommander;
TextView custom_question_bar, list_number;
String selectedCustomQuestion;
boolean buttonClicked;
Button yiyecekButton;
Context c;
public interface DearListener {
public void getMyText(String theQuestion);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
activityCommander = (DearListener) activity;
Log.i("MYLOG", "onAttach");
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString());
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.new_test_layout, container, false);
//custom_question_bar= (TextView) v.findViewById(R.id.custom_question_bar);
//list_number= (TextView) v.findViewById(R.id.list_number);
yiyecekButton = (Button) v.findViewById(R.id.yiyecekButton);
Log.i("MYLOG", "Button referenced");
yiyecekButton.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View v){
Log.i("MYLOG", "onCLickListener Called");
onClickYiyecek(v);
}
}
);
return v;
}
public void onClickYiyecek(View v){
Log.i("MYLOG", "OnClickYiyecek");
activityCommander.getMyText("En sevdiğim yiyecek ne?");
}
public void onClickQuestionReady(View v){
if( custom_question_bar == null)
{
Toast.makeText(c, "Boşluğu doldurmadınız", Toast.LENGTH_SHORT).show();
}
activityCommander.getMyText(custom_question_bar.getText().toString());
}
}
And the Activity:
public class NewTest extends Activity implements test_layout.DearListener {
FragmentManager manager;
test_layout test_layout_frag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_holder);
manager=getFragmentManager();
test_layout_frag = new test_layout();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.the_frame_layout, test_layout_frag);
transaction.commit();
}
#Override
public void getMyText(String theQuestion) {
manager=getFragmentManager();
answer_layout answer_layout_frag = new answer_layout();
answer_layout answer_layout_obj = (answer_layout)getFragmentManager().findFragmentById(R.id.fragment2);
answer_layout_obj.changeText(theQuestion);
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.the_frame_layout, answer_layout_frag);
transaction.commit();
Log.i("MYLOG", "Transaction Called");
//transaction.addToBackStack(null);
}
}
And the second fragment:
public class answer_layout extends Fragment {
TextView yourSelectedQuestion;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.new_answer_layout, container, false);
yourSelectedQuestion= (TextView) v.findViewById(R.id.yourSelectedQuestion);
return v;
}
public void changeText(String a) {
Log.i("MYLOG", "changeText");
Log.i("MYLOG", a);
yourSelectedQuestion.setText(a);
}
}
No exception is given but the TextView in second fragment isn't changing.
Since i didn't write the xml here, I can if its needed. Using FrameLayout and it contains 2 fragments inside it.
In myFragment class write a static method:
public static myFragment newInstance(String txt) {
myFragment myfragment = new myFragment();
Bundle args = new Bundle();
args.putString("TEXT", txt);
myfragment.setArguments(args);
return myfragment;
}
after that in OnCreate method of myFragment class inflate the textView tv and
tv.setText(getArguments().getString("TEXT"));
In main FragmentActivity class do:
myFragment fragment = myFragment.newInstance(textToBeSent);
before replace,
fragmentTransaction.replace(R.id.fr_dynamic, fragment);
fragmentTransaction.commit();

Resources