button in fragment not working when clicked - java

I have a button in fragment, and for that button i had override onClick() method, but its not working.
i have a Taost and a Log too when the button is being clicked.
public class DataShown extends Fragment implements OnClickListener{
Button tv;
TextView textview;
Activity activity=getActivity();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("3", "started");
View rootView = inflater.inflate(R.layout.datashown, container, false);
Log.d("3", "closed");
textview=(TextView) rootView.findViewById(R.id.textView1);
tv = (Button) rootView.findViewById(R.id.configButton);
tv.setOnClickListener((OnClickListener) activity);
return rootView;
}//onCtreate
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.d("onClick","1");
Toast.makeText(activity, "on click", Toast.LENGTH_SHORT).show();
}
}
why its happening, i have no idea, may be its silly mistake.
Now the toast is showing error, is accepts context object so i provided activity, not working.

Change
tv.setOnClickListener((OnClickListener) activity);
to
tv.setOnClickListener(this);
and in onClick method change
Toast.makeText(activity, "on click", Toast.LENGTH_SHORT).show();
to
Toast.makeText(getActivity(), "on click", Toast.LENGTH_SHORT).show();
and remove
Activity activity=getActivity();
because you did initiate it before fragment attached to activity.

You are creating the view in the fragment, but binding the on click listener to the activity.
tv.setOnClickListener(this); since fragment is the one tat is overriding the onClick listener and not the activity

Yon can do this:
tv.setOnClickListener(getActivity);

This is the problem with your context in setOnClickListener, you need to give your actvivities context to work fine.
setOnClickListener(getActivity); will pass the actvities context to the onclicklistner.

Related

Dialog for fragments

Why is my showPopup grey when I already have an OnClick method on that fragment's xml?
I'm trying to make the popup_about_app XML popup when I click on the button with the OnClick.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myDialog = new Dialog(getContext());
return inflater.inflate(R.layout.fragment_settings, container, false);
}
public void showPopup(View view) {
TextView txtclose;
myDialog.setContentView(R.layout.popup_about_app);
txtclose =(TextView) myDialog.findViewById(R.id.txtClose);
txtclose.setText("X");
txtclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myDialog.dismiss();
}
});
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
myDialog.show();
}
In Android Studio, gray means its not being used yet. Either nothing is calling showPopup, or possibly that Android Studio isn't smart enough to find the thing calling showPopup (which can happen in various scenarios). I wouldn't worry about it unless you hit the button that's supposed to call showPopup and nothing happens (and then it means you forgot to call it). If the popup shows like you expect, its a non-issue.

Alert dialog in Fragment, app get crashed

I want to display the alert dialog when onClick of the button in fragment layout. I have tried but the app is crashing when it runs.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = FragmentWalletBinding.inflate(inflater, container, false);
Button button = (Button)getView().findViewById(R.id.add_money);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertdialog = new AlertDialog.Builder(view.getContext());
alertdialog.setMessage("this is message");
alertdialog.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getContext(),"toast message",Toast.LENGTH_SHORT).show();
}
}).show();
}
});
return binding.getRoot();
}
onCreateView returns View which can be further obtained by getView() method. and you are calling it before onCreateView had a chance to return own View for framework (its still inside method, didn't return binding.getRoot(); yet)
if you are using view binding then obtain your Button from there
Button button = (Button) binding.addMoney;
or even just use strictly (without additional local Button)
binding.addMoney.setOnClickListener(...
and if you REALLY WANT to use findViewById (but why...), then you can look inside binding.getRoot() even when it isn't returned/drawn yet
Button button = (Button) binding.getRoot().findViewById(R.id.add_money);
there is a problem in
(Button)getView().findViewById(R.id.add_money);
please make sure id is same as in XML.

When you open a new activity in a fragment the app stops

The problem that Teno I want to use an intro slide in my app through fragments and the third fragment I want to put a button that leads to another activity and in Android studio the code does not make any error but when I run the app and click the app button It stops what is it?
public ThirdFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_third, container, false);
viewPager = getActivity().findViewById(R.id.viewPager);
back1 = view.findViewById(R.id.slideThereback);
back1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(1);
}
});
//The TextView "Done " is the one I want to click on the Take me to another activity and that up to now gives me an error to run in the emulator
done = view.findViewById(R.id.Done);
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(getActivity(), MenuP.class);
startActivity(myIntent);
}
});
return view;
}
I hope I can provide the code or say my error to open a new activity in a fragment and not close the app to Ejecutarce on a mobile device
Use the below code in your onClick() method.
Intent myIntent = new Intent(getActivity(), MenuP.class);
getActivity().startActivity(myIntent);
Check that R.id.Done does exists in R.layout.fragment_third. if it doesn't exist then done View might be null.

Nullpointerexception thrown when trying to findViewById

I have the following Activity:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new StartFragment())
.commit();
}
Button login = (Button) findViewById(R.id.loginButton);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this,LoginActivity.class);
startActivity(intent);
}
});
}
I get a NPE when I try to invoke findViewByID for R.id.loginButton, and I'm guessing this is because loginButton is within a separate Fragment, which I have as:
public static class StartFragment extends Fragment {
public StartFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
}
However, I am unsure of how to fix this so that I can find the loginButton ID. I haven't worked with fragments before, so I realize I may be using them/implementing them incorrectly. fragment_main contains a few buttons in a LinearLayout, and activity_main has nothing but a single FrameLayout.
Try to implement your onCreateView(...) in Fragment like
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
View something = rootView.findViewById(R.id.something);
something.setOnClickListener(new View.OnClickListener() { ... });
return rootView;
}
The Button is in the fragment layout (fragment_main.xml) and not in the activity layout (activity_main.xml). onCreate() is too early in the lifecycle to find it in the activity view hierarchy, and a null is returned. Invoking a method on null causes the NPE.
Write code to initialize button from fragment becuase your button is into fragment layout not into activity's layout.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
Button login = (Button) rootView.findViewById(R.id.loginButton);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this,
LoginActivity.class);
startActivity(intent);
}
});
return rootView;
}
And remove the login button related code from onCreate of Activity.
findViewById() works with reference to a root view.
Without having a view in the first place will throw a null pointer exception
In any activity you set a view by calling setContentView(someView);.
Thus when you call findViewById() , its with reference to the someView.
Also findViewById() finds the id only if its in that someView. So in you case null pointer exception
For fragments, adapters, activity, .... any view's findViewById() will only find if the id exixts in the view
Alternately if you are inflating a view, then you can also use inflatedView.findViewById() to get a view from that inflatedView
In short make sure you have the id in your layout you are referring to or make findViewById() call in appropriate place(Ex. adapters getView(), activity's onCreate() or onResume() or onPause() , fragments onCreateView(), ....)
Also have an idea about UI & background thread's as you cannot efficiently update UI in bg-threads

Open Another Activity Using Fragment Button

Okay so I've tried two types of code to get this to work and it keeps giving me force closes when I press the button to go into another Activity. I'm using a Fragment and there's a button in that Fragments code but I can't seem to get it to work. I'm not an experienced Android developer but I'm trying my best to learn.
Here's the Java code:
1st Method
public class About extends Fragment {
Intent intent;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.about, container, false);
intent = new Intent(getActivity(), Contact_Developer.class);
final Button button = (Button) rootView.findViewById(R.id.btnContactDev);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(intent);
}
});
return rootView;
}
}
2nd Method
public class About extends Fragment {
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.about, container, false);
Button button = (Button) rootView.findViewById(R.id.btnContactDev);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getActivity(), Contact_Developer.class);
getActivity().startActivity(intent);
}
});
return rootView;
}
}
I really don't know what's going on and why I'm getting force closes but if anyone could help me and explain a little what I did wrong that'd be more than enough
Do not handle the onClick for the fragment button in the Fragment. Let it go it's parent activity. And start the activity from the parent activity.
To make sure that the button onClick event is sent to the parent activity, make sure, in your about.xml, for the button with id btnContactDev, you have the following parameter:
<Button android:id="#+id/btnContactDev"
android:onClick="buttonClick"
...
/>
and in your parent activity (parent of About fragment), you have:
public void buttonClick(View v) {
switch(v.getId()) {
case R.id.btnContactDev:
Intent myIntent = new Intent();
myIntent.setClassName(your_package_name_string, your_activity_name_string);
// for ex: your package name can be "com.example"
// your activity name will be "com.example.Contact_Developer"
startActivity(myIntent);
break;
}
}
HTH.
PS: This solution is very specific for what your requirement. In general, it's best to handle the onClick events related to the fragment inside the fragment class.
PS: Yes, as the other solution says, make sure you have registered the Contact_Developer Activity in your Manifest file.
Have you declared the proper activity in the AndroidManifest.xml? Each activity other then the first should be declared inside the application tag, like this:
<activity
android:name=".Contact_Developer"
android:label="#string/app_name" >
</activity>
If it's not found, it will give force close.
I think the issue here is that the activity is not ready.
I would not recommend you following harikris's solution even though it works. It's usually bad practice to put code (onClick() which handles the click event) in your XML file. For example, it will be very difficult to hunt that piece of code down to review/ change it in the future yourself, not to mention another developer in your team.
I'd suggest to listen to the event the activity is ready i.e. onActivityCreated() within your Fragment class. Override the implementation of the same method and call something in your activity e.g. onFragmentReady() like in the example below.
Fragment class:
public class About extends Fragment {
Intent intent;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.about, container, false);
intent = new Intent(getActivity(), Contact_Developer.class);
final Button button = (Button) rootView.findViewById(R.id.btnContactDev);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(intent);
}
});
return rootView;
}
#Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
((MyActivity) this.getActivity()).onFragmentReady();
}
}
Activity class:
public class MyActivity extends FragmentActivity {
private void onFragmentReady() {
Log.i(TAG, "testing");
intent = new Intent(getActivity(), Contact_Developer.class);
final Button button = (Button) rootView.findViewById(R.id.btnContactDev);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(intent);
}
});
}
public class About extends Fragment {
...
}
}
I think you should use getContext() or getApplicationContext() instead of getActivity()
so code will be
Intent intent =new Intent(getContext(),Contact_Developer.class);
startActivity(intent);

Categories