I have created fragment activity using viewpager with two tabs, and created listview with two textviews. I want to sent the two texts from tab one to tab two as title and description. I have successfully sent the description, but I failed to send the title (]I can only send one text to listview).
My fragment_one.java :
public void onViewCreated(final View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
viewPager = (ViewPager)view.findViewById(R.id.viewPager);
Button btnPassData = (Button) view.findViewById(R.id.btnPassData);
final ListView list=(ListView)view.findViewById(R.id.list_view);
final EditText inData = (EditText) view.findViewById(R.id.inMessage);
btnPassData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SM.sendData(inData.getText().toString().trim());
}
});
}
interface SendMessage {
void sendData(String message);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
SM = (SendMessage) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException("Error in retrieving data. Please try again");
}
}
}
my fragment_two.java :
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_two, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
listView = (ListView) view.findViewById(R.id.list_view);
adapter = new ArrayAdapter<String>(getActivity(), R.layout.single_item,R.id.tvdesc, arrayList);
listView.setAdapter(adapter);
}
protected void displayReceivedData(String message) {
arrayList.add(0,message);
adapter.notifyDataSetChanged();
}
}
You should use call back data from fragment_one to main activity , and send data from activity to fragment_two (and refresh view)
Callback fragment to activity you can use How to make a callback between Activity and Fragment?
and Fragment_two you can set this value in Activity,
EX,
private Fragment mFragmentTwo;
.........
mFragmentTwo= new Fragment();
and can set value by funtion : mFragmentTwo.displayReceivedData(yourString)
Related
I am trying to get user input using EditText from fragment after pressing a button. For some reason the button is clickable but no data from EditText.
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/txtUserInput"/>
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/btnTest"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"/>
public class MainActivity extends AppCompatActivity {
TestFragment testFragment = new TestFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, testFragment)
.commit();
}
}
public class TestFragment extends Fragment {
Button btnTest;
EditText txtUserInput;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_test, container, false);
btnTest = view.findViewById(R.id.btnTest);
txtUserInput = view.findViewById(R.id.txtUserInput);
String input = txtUserInput.getText().toString();
btnTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), input, Toast.LENGTH_LONG).show();
}
});
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
Add gettext() inside your click listener
btnTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { String input=txtUserInput.getText().toString()
Toast.makeText(getActivity(), input, Toast.LENGTH_LONG).show();
}
});
as you want data from edite text after clicking the button so once you click then on click event is triggered and then you should get data from edit field
you can do this thing like
and View is used to get root view for the fragment.
View view = inflater. Inflate(R.layout.fragment_test, container, false);
EditText editText = view.findViewById(R.id.txtUserInput);
Button btnTest = view.findViewById(R.id.btnTest);
String input ="";
btnTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
input=editText.getText().toString()
}
});
I'm trying to get a Toast to appear in a tabbed fragment when an EditText is left empty.
Here is my MainActivity's onCreate:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
}
My Tabbed Fragment works fine with this code:
public class SignupFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_signup, container, false);
}
}
But it doesn't work when creating the Toast like this:
public class SignupFragment extends Fragment {
EditText textFillCheck;
Button submitCheck;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
submitCheck = (Button) submitCheck.findViewById(R.id.signupBtn);
textFillCheck = (EditText) textFillCheck.findViewById(R.id.signupFirstName);
submitCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TextUtils.isEmpty(textFillCheck.getText().toString())) {
Intent intent = new Intent(getActivity(), SignupFragment.class);
startActivity(intent);
Toast.makeText(getActivity(), "Please fill in all fields", Toast.LENGTH_SHORT).show();
}
else{Toast.makeText(getActivity(), textFillCheck.getText().toString(), Toast.LENGTH_LONG).show();
}
}
});
return inflater.inflate(R.layout.fragment_signup, container, false);
}
}
You're not accessing the views of your Fragment's layout so the layout you're returning in onCreateView() doesn't have your logic attached to it. You should set up your Fragment to look something like this:
public class SignupFragment extends Fragment {
EditText textFillCheck;
Button submitCheck;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState){
// Store a reference to your Fragment's inflated layout
View root = inflater.inflate(R.layout.fragment_signup, container, false);
// Use the reference to access your Fragment's views
submitCheck = (Button) root.findViewById(R.id.signupBtn);
textFillCheck = (EditText) root.findViewById(R.id.signupFirstName);
submitCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(TextUtils.isEmpty(textFillCheck.getText().toString())) {
Toast.makeText(getActivity(), "Please fill in all fields", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), textFillCheck.getText().toString(), Toast.LENGTH_LONG).show();
}
}
});
// Return the inflated layout
return root;
}
}
I am amazed why your code is not having any error like VIEW DOES NOT EXIST or NULL POINTER EXCEPTION because
First, you change the activity before showing the Toast secondly you are inflating the layout after the initialization of views and not getting the context properly, Right way of doing what you are trying to achieve is using OnViewCreated() like this
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
submitCheck = (Button) view.findViewById(R.id.signupBtn);
textFillCheck = (EditText) view.findViewById(R.id.signupFirstName);
submitCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TextUtils.isEmpty(textFillCheck.getText().toString())) {
Toast.makeText(getActivity(), "Please fill in all fields",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), SignupFragment.class);
startActivity(intent);
}
else{
Toast.makeText(getActivity(), textFillCheck.getText().toString(),
Toast.LENGTH_LONG).show();
}
}
});
}
I am making a program that will include a Spinner within a fragment rather than an activity. I have researched why this may be crashing, but to no avail. My initial concern was a .getView().findViewById(), but now I'm not so sure that's the problem because . Here's the code.
public class Add extends Fragment {
public Add() {
// Required empty public constructor
}
ArrayList<String> ingredients = new ArrayList<>();
SpinnerDialog spinnerDialog;
Button add;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
add = (Button) getView().findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
spinnerDialog.showSpinerDialog();
}
});
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_add, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
spinnerDialog = new SpinnerDialog(getActivity(), ingredients, "Select An Ingredient");
spinnerDialog.bindOnSpinerListener(new OnSpinerItemClick() {
#Override
public void onClick(String Ingredient, int i) {
Toast.makeText(Add.super.getContext(), "Selected ", Toast.LENGTH_SHORT).show();
}
});
Without seeing the stack trace I cannot say for sure, but I suspect this line is crashing:
add = (Button) getView().findViewById(R.id.add);
This is because getView() will return the View instance returned by onCreateView()... but you're currently inside onCreateView(), so getView() will return null.
You can re-write your onCreateView() as follows and it should work.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_add, container, false);
add = (Button) root.findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
spinnerDialog.showSpinerDialog();
}
});
return root;
}
Got two empty Activites(A and B), which just hold two fragments inside ViewPager of Activity A.
I do not have code errors, everything seems fine.
When I lunch my app and click on button, nothing happens.I was trying just to log something, but still nothing is happening.
I am using ButterKnife, and so far everything was perfect.I got almost same Fragment and it is performing fine, but OnClick inside Fragment B is not working.I tried to add some more OnClick methods, but none of them worked for me.XML looks good,looks almost same as fragment A.
Fragment B is not complex, it just three TextViews and Button.
Here is code for my fragment B:
public class ForgotPasswordFragmentComplete extends BaseFragment
implements BaseView {
private Realm realm;
private Email model;
#Bind(R.id.btn_resend)
AppCompatButton resendEmail;
#Inject
ForgotPasswordPresenter presenter;
#OnClick(R.id.btn_resend)
public void resendButton() {
Log.d("ResendOnclick", "Checking OnClickMethod ");
Realm realm2 = getRealm();
RealmQuery<Email> queryUserResend = realm2.where(Email.class);
Email resultResend = queryUserResend.findFirst();
ForgotPasswordPayload forgotPayload = new ForgotPasswordPayload(resultResend.getUsername());
this.presenter.subscribe(forgotPayload);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DaggerForgotPasswordCompletedComponent.builder()
.applicationComponent(
((AndroidApplication) getActivity().getApplication()).getApplicationComponent())
.forgotPasswordCompletedModule(new ForgotPasswordCompletedModule())
.build()
.inject(this);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
protected void onCreateViewWidgetInitialization(View view) {
super.onCreateViewWidgetInitialization(view);
}
#Override
public void onStart() {
super.onStart();
getEmail();
}
public void getEmail(){
Realm realm = getRealm();
RealmQuery<Email> queryUser = realm.where(Email.class);
Email result1 = queryUser.findFirst();
resendEmailTxt = (AutoResizeTextView) getView().findViewById(R.id.resend_user_email);
if (resendEmailTxt != null) {
this.resendEmailTxt.setText(result1.getUsername());
}
}
#Override
public void onDestroy() {
super.onDestroy();
realm.close();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_forgot_password_fragment_complete, container, false);
}
#Override
protected int getFragmentLayoutId() {
return R.layout.fragment_forgot_password_fragment_complete;
}
You need to bind the fragment's view object before you can use it. Try putting the following code inside onCreateView() :
View rootView = inflater.inflate(R.layout.fragment_forgot_password_fragment_complete, container, false);
ButterKnife.bind(this, rootView);
return rootView;
I have a MainActivity like this
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
} }
and this
public class MyListFragment extends ListFragment implements OnItemClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_fragment, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.Planets, android.R.layout.simple_list_item_1);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
int count = getListView().getCount();
getListView().setSelection(getListView().getCount() - 1);
test();
}
public void test(){
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.Planets, android.R.layout.simple_list_item_1);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
int count = getListView().getCount();
getListView().setSelection(getListView().getCount() - 1);
Toast.makeText(getActivity(), "ccc"+count, Toast.LENGTH_SHORT)
.show();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(getActivity(), "Item: " + position, Toast.LENGTH_SHORT)
.show();
} }
The activity_main.xml has a
fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.example.mike.mqtt.MyListFragment"
android:id="#+id/fragment_content" />
When the application starts I get the fragment_content filled up with some rows.
How can I access the ListFragment(MyListFragment.java) from inside the MainActivity.java in the onCreate.
When I press a button the get the ListFragment content count, and to set focus at the end of the list.
I have no idea.Thank you.
MyListFragment fragment = (MyListFragment) getFragmentManager().findFragmentById(R.id.fragment_content)
I avoid using fragments in XML as it alows me to replace them on-the-fly. I usually use something like this:
private MyListFragment mListFragment;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// the usual business
FragmentManager fm = getSupportFragmentManager();
if (savedInstanceState == null) {
// the activity opened for the first time, we create and commit fragment
mListFragment = new MyListFragment();
fm.beginTransaction().replace(android.R.id.content, f).commit);
} else {
// activity is recreating so it's safe to find already added fragments
mListFragment = fm.findFragmentById(android.R.id.content);
}
}