I am making an app, that will have FragmentsActivity and after clicking on Floating Action Button making a simple button on the screen. How I should implement something like that. Now I have got this:
at main.java
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.monday_act, container, false);
RelativeLayout rl = (RelativeLayout) rootView.findViewById(R.id.rel);
rl.addView(new DayView(this.getContext(), getArguments().getInt(ARG_SECTION_NUMBER)));
FloatingActionButton fab = (FloatingActionButton) getActivity().findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent addClass = new Intent(getActivity(), AddClass.class);
startActivityForResult(addClass, 1);
}
});
return rootView;
}
and the onActivityResult:
#SuppressLint("SetTextI18n")
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1)if (resultCode == RESULT_OK) {
final Button lesson = new Button(this.getActivity());
lesson.setText("Button");
lesson.setBackgroundColor(getResources().getColor(R.color.green));
lesson.setTextColor(getResources().getColor(R.color.red));
lesson.setX(100);
lesson.setY(100);
lesson.setWidth(100);
lesson.setHeight(150);
lesson.setTextSize(100);
RelativeLayout(this.getActivity());
rl.addView(lesson);
}
}
Both functions are in public static class PlaceholderFragment extends Fragment {
You don't use onActivityResult() between Activity and Fragment
you use it between two Activities
A activity will command another activity to do some work on some data passed to it or a request is made to the other activity to fetch something or do something and return the result.
after the work is done the worker Activity finishes it self and returns the result to the activity which started it.
And the activity who issues the work will have onActivityResult() it updated the UI depending on the result it gets
Related
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.
i have two fragments of the same activity(navigation drawer) i added a button on one among them to switch to another but i am getting an error.i don't know how this works . please help me
public class HomeFragment extends Fragment {
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
SwitchBtn= (AppCompatButton) rootView.findViewById(R.id.btnswitch);
// Register Button Click event
SwitchBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(getActivity(),
FriendsFragment.class);
getActivity().startActivity(intent);
}
});
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
You're switching between fragments, not starting a new activity.
Replace this
Intent intent = new Intent(getActivity(),
FriendsFragment.class);
getActivity().startActivity(intent);
With this
getFragmentManager().beginTransaction()
.replace(R.id.your_container_id, new FriendsFragment())
.commit()
You can't open a fragment as such. What you need to do is either create them on the same activity, use a 'screen' variable that controls display by using the .setVisible on your components.
Or, what you can do is put your fragments on different activities using intent.
private Content C = getApplicationContext();
Intent myIntent = new Intent(C,yourActivity.class);
C.startActivity(myIntent);
I have a fragment (FragmentA) with a RecyclerView displaying some CardViews. I wanted to make the cardviews clickable , so the solution I found for this was to implement View.OnClickListener in the ViewHolder inside de adapter class. Something like this:
fragmentAAdapter.java
public class fragmentAViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public fragmentAViewHolder (View itemView) {
super(itemView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
//do something..
}
}
The onClick() method gets the data from the clicked cardview and start an activity (InfoActivity) who displays the data.
OnClick() method
#Override
public void onClick(View v) {
Intent intent = new Intent(itemView.getContext(), InfoActivity.class);
Bundle mBundle = new Bundle();
mBundle.putParcelable("someData", someData);
intent.putExtras(mBundle);
itemView.getContext().startActivity(intent);
}
In the InfoActivity I can update and delete the data. After that I want to finish the InfoActivity and refresh the FragmentA to get the new data.
To close the activity and refresh the previous fragment I am trying to use the startActivityForResult(). Like this:
#Override
public void onClick(View v) {
Intent intent = new Intent(itemView.getContext(), InfoActivity.class);
((Activity) itemView.getContext()).startActivityForResult(intent, 10001);
}
InfoActivity.java
#Override
public void onClick(DialogInterface dialog, int which) {
setResult(InfoActivity.RESULT_OK);
finish();
}
FragmentA.java
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if ((requestCode == 10001) && (resultCode == InfoActivity.RESULT_OK)) {
FragmentAfragment = new FragmentA();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
}
But when I close the InfoActivity nothing happens.
The problem is that the setResult(InfoActivity.RESULT_OK) returns the result to the adapter class (fragmentAAdapter) not to FragmentA, so the method onActivityResult() in FragmentA is never called.
How do I refresh the FragmentA after close InfoActivity who was started inside the onClick() method in the fragmentAAdapter??
Update - Solution
I overwrote the method onActivityResult() in the activity of the FragmentA. Like this:
MainActivity.java
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ((requestCode == 10001) && (resultCode == 10001)) {
FragmentA fragment = new FragmentA();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
}
and in InfoActivity.java:
#Override
public void onClick(DialogInterface dialog, int which) {
setResult(10001);
finish();
}
Every time it closes an activity and go back to the FragmentA the onActivityResult() in the MainActivity is called, and when the condition if((requestCode == 10001) && (resultCode == 10001)) is true the FragmentA is refreshed.
In the activity of your fragment you can do something like this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
requestCode &= 0xffff;
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
if (fragment != null) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
Or you can use a Event bus like: http://square.github.io/otto/
The problem you are issuing is the things like that
Fragment(startActivityForResult()) -> Activity
Fragment(onActivityResult()) <- Activity (setResult(Result_OK))
You should avoid to do the onActivityResult() in your activity class since the role of the activity in this process is just a mailer to send the data back to the fragment.
If you are going to call the activity inside the fragment you can call it getActivity().startActivityForResult() directly
Fragment(getActivity().startActivityForResult) -> Activity
Activity(onActivityResult()) <- Activity (setResult(Result_OK))
#Options
Activity(Loop the fragment and find Fragment and call onActivityResult() like Agustin Sivoplas suggested.) -> Fragment
Even though you are inside the adapter view holder, it should be also located inside the fragment.Try to utilize the fragment function and not make extra code in Activity
Possible duplicate
onActivityResult is not being called in Fragment
I am having some trouble with my simple app. The app starts in the MainActivity where you can press a camera icon. This opens an implicit intent for taking a photo. When the photo is taken, another activity DisplayImageActivity is opened. This activity consists of two fragments: one that holds an ImageView for displaying the photo and another one that holds some TextViews that displays some information about the photo (filename, size, location etc.). I use a ViewPager for having horizontal swipe capabilities.
Now to the problem. I should note that this is not a consistent problem. Sometimes the app crashes, sometimes it works just fine. The problem lies in getting the image path from the onActivityResult in MainActivity to the two fragments so I can get the image and info. Here is my onActivityResult method:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 42 && resultCode == RESULT_OK) {
Log.d(TAG, "MainActivity onActivityResult method called.");
Intent intentShowPicture = new Intent(this, DisplayImageActivity.class);
intentShowPicture.putExtra(PICTURE_KEY, imgPath);
startActivity(intentShowPicture);
}
}
So I just put the image path I get from taking the picture in the bundle and start the DisplayImageActivity. Then in my DisplayImageActivity, I do this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_image);
Log.d(MainActivity.TAG, "DisplayImageActivity onCreate called.");
imgPath = getIntent().getExtras().getString(MainActivity.PICTURE_KEY);
mAdapter = new FragmentAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAdapter);
Then I have a method that just return the straing imgPath:
public String getImgPath() {
return imgPath;
}
Then inside the fragment (PictureFragment) I try to retrieve the imgPath like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
DisplayImageActivity activity = (DisplayImageActivity) getActivity();
imgPath = activity.getImgPath();
But as I mentioned earlier, sometimes the getImgPath method just returns null and the app crashes when I try to retrieve the photo. But sometimes it works fine. I am kinda lost as to why this is. Is it because the fragment is sometimes constructed before the imgPath variable is assigned in the DisplayImageActivity, so the variable is just null?
I am kinda new to android, so this might not be the best approach. I just did it from the top of my head. Any ideas why this is happening?
If you want to pass data from an Activity to a Fragment, you could use this approach:
In the Activity:
Bundle bundle = new Bundle();
String imgPath = "path/to/my/image";
bundle.putString("imgPath", imgPath );
PictureFragment frag = new PictureFragment();
frag.setArguments(bundle);
transaction.replace(R.id.fragment_single, frag);
transaction.commit();
Fragment:
Reading the value in fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String myValue = this.getArguments().getString("imgPath");
...
...
...
}
For more information, take a look at this question How to pass a variable from Activity to Fragment, and pass it back?
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);