converting activity into fragment - android

This is a simple code to play a sound on click off a button, this code was initially written in Activity but now i want to change it to Fragments.
errors
1) The method setContentView(int) is undefined for the type Rajathmusic.
2) The method create(Context, int) in the type MediaPlayer is not applicable for the arguments (Rajathmusic, int).
3)The method findViewById(int) is undefined for the type Rajathmusic.
I am just starting off with android development, any help would be appreciated!
public class Rajathmusic extends Fragment {
private static final String TAG = "MyActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v(TAG, "Initializing sounds...");
final MediaPlayer mp = MediaPlayer.create(this, R.raw.rajath);
Button play_button = (Button)this.findViewById(R.id.button3);
play_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v(TAG, "Playing sound...");
mp.start();
}
});
Log.v(TAG, "Sounds initialized.");
}}

Fragment has a method called onCreateView(LayoutInflater, ViewGroup, Bundle). Override it, inflate using the layout and return the view.
Since create method expects a Context, pass it using getActivity()
findViewById(int) can be called as getView().findViewById(R.id.button3)
Here is a sample code:
public class Rajathmusic extends Fragment {
private static final String TAG = "MyActivity";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_main, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.v(TAG, "Initializing sounds...");
final MediaPlayer mp = MediaPlayer.create(getActivity(), R.raw.rajath);
View v = getView();
Button play_button = (Button) v.findViewById(R.id.button3);
play_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v(TAG, "Playing sound...");
mp.start();
}
});
Log.v(TAG, "Sounds initialized.");
}
}
Read more about Fragment lifecycle here to know why I've put the code in onActivityCreated and not onCreate

In fragment onCreate method is usually written as-
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
And Use-
final MediaPlayer mp = MediaPlayer.create(getActivity(), R.raw.rajath);
Button play_button = (Button) view.findViewById(R.id.button3);
If you want to read more about fragments. Check this link.

Use this code in overriden method OnActivityCreated(...) and instead of this use getActivity(), since new fragment is not activity any more.

Copy the code from the onCreate() method from the activity and paste it into the onCreateView() method of the fragment.
To fix the errors, pass getActivity in place of this keyword and use getView().findViewById().

Related

Textview in Dialog Fragment is not getting visible when we try to show the textview from its parent class

I have a class called "text". and then I have Dialog Fragment named "dialog" under this "text" class.
I am trying to make visible the text from the showText() which is located in the "text" class.
But it's getting visible. it's getting visible only from the dialog fragment.
Could anyone please help find out the issue.
private class text extends Activity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dialog dialogobj = new dialog();
dialogobj.show(mActivity.getFragmentManager(), "dialog");
dialogobj.showText();
}
public class dialog extends DialogFragment {
private TextView mText1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setStyle(STYLE_NO_TITLE, android.R.style.Theme_Material_Light_Dialog);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View dialogView = inflater.inflate(R.layout.dummy_layout, container, false);
mText1 = (TextView) dialogView.findViewById(R.id.left_img_view);
}
private void showText() {
mText1.setVisibility(View.Visible);
}
}
}
You have declared the variable mText1 as textview, but when call the findViewById method you are casting with Imageview. Check if it is causing the problem.
I advise using a capital letter as the first letter of your classes.
I think you should try to call your dialog initialization in the onCreate method of the Activity:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Dialog dialog = new Dialog();
dialog.show(getFragmentManager(), "dialog");
dialog.showText();
}

Android: "Method is never used" warning for onClick method

This is a part of my calc_fragment.xml file ,
<Button
android:id="#+id/b7"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_margin="2dp"
android:background="#drawable/roundedbutton"
android:fontFamily="sans-serif-thin"
android:text="Add"
android:textColor="#color/light_grey"
android:textSize="45sp"
android:onClick="clicked"/>
that is linked with the following fragment:
public class CalcFragment extends Fragment {
private TextView textView;
private String text;
private Vibrator vibe;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.calc_fragment, container, false);
return rootView;
}
public void clicked (View v){ <--- "Method clicked is never used"
...content...
}
I get a warning "Method clicked is never used" but I my button is linked with this method
A Fragment is tightly linked with its activity. So, the above method declaration in xml will basically look for that method in the Activity class. One of the ways is that you can explicitly link your method and the button:
public class CalcFragment extends Fragment {
private TextView textView;
private String text;
private Vibrator vibe;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.calc_fragment, container, false);
View myButton = rootView.findViewById(R.id.b7);
rootView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicked(v);
}
});
return rootView;
}
public void clicked (View v){ // Your method
...content...
}
Get rid of the 'android:onClick="clicked"' property in your xml.
This is because the XML code for handling clicks does not work for the Fragment class, it currently works only with the Activity class. As such, this method will never be called. See this question for more details.
In the onCreateView method of the CalcFragment, you need to declare and initialize the button after the initializing the rootView:
Button b7 = (Button) rootView.findViewById(R.id.b7);
You then need an onClickListener instead of defining your own clicked method. There are two methods to listen to a click of a button.
The first method:
You can set the onClickListener within the onCreatView as follows:
b7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Do something
}
});
The second method:
You can define an onClickListener as follows:
final View.OnClickListener b7OnClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
// Do something
}
};
When using the second method, you will need to set the onClickListener like you did in the first method however in this case you will pass the name of the onClickListener object you created.
Example:
b7.setOnClickListener(b7OnClickListener);

Getting error: Cannot resolve method 'makeText' in Android

I am a newbie.
Getting error:
Cannot resolve method 'makeText'
I am using navigation drawer and My class name is MainFragment.java.
Actually I was to trying to use File and Folder Explorer, only this error.
What I have tried: Tried using MainFragment.getContext() and getActivity() and context and this, in-place of MainFragment.this but none is working.
MainFragment.java
public class MainFragment extends Fragment
{
//Defined for file edittext.
EditText editText2;
public MainFragment() {
// Required empty public constructor
}
/* #Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_main, container, false);
}
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_main, container, false);
Button dirChooserButton = (Button) view.findViewById(R.id.skipButton); //Browse Button
dirChooserButton.setOnClickListener(new OnClickListener()
{
private String m_chosenDir = "";
private boolean m_newFolderEnabled = true;
#Override
public void onClick(View v)
{
// Create DirectoryChooserDialog and register a callback
DirectoryChooserDialog directoryChooserDialog =
new DirectoryChooserDialog(MainFragment.this,
new DirectoryChooserDialog.ChosenDirectoryListener()
{
#Override
public void onChosenDir(String chosenDir)
{
m_chosenDir = chosenDir;
Toast.makeText(
getActivity(), "Chosen directory: " +
chosenDir, Toast.LENGTH_LONG).show();
}
});
// Toggle new folder button enabling
directoryChooserDialog.setNewFolderEnabled(m_newFolderEnabled);
// Load directory chooser dialog for initial 'm_chosenDir' directory.
// The registered callback will be called upon final directory selection.
directoryChooserDialog.chooseDirectory(m_chosenDir);
m_newFolderEnabled = ! m_newFolderEnabled;
}
});
#Override
public void onChosenDir(String chosenDir)
{
m_chosenDir = chosenDir;
Toast.makeText(MainFragment.this, "Chosen directory: " +chosenDir,Toast.LENGTH_LONG).show();
}
}
}
DirectoryChooserDialog.java
Actually I tried this link for making File and Folder Chooser: link to the webpage
Fragment will not be able to show your toast, it has to come from activity. Try the following:
Toast.makeText(getActivity(), "Chosen directory: " + chosenDir, Toast.LENGTH_LONG).show();
try this one
Toast.makeText( MainActivity.this,"Data Inserted", Toast.LENGTH_SHORT).show();
Here Mainactivity is the name of class

Android: Button OnClick not working in SherlockFragment

I've tab activity in which i want to use a button, but when i click on button, it force closes the app. Can you please tell me what is going on, i am new to Android.
public class HomeActivity extends SherlockFragment {
private Button bt;
private Context con;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.home_layout, container, false);
bt = (Button)rootView.findViewById(R.id.btn);
bt.setOnClickListener(new View.OnClickListener(){
#Override public void onClick(View v)
{
Toast.makeText(con, "hello", Toast.LENGTH_LONG).show();
}
});
return rootView;
}
}
when i click on button, it force closes the app
Because con object of Context is null. which is used for showing Toast message in Button onClick method.
Do it as:
Toast.makeText(v.getContext(), "hello", Toast.LENGTH_LONG).show();
And initialize con object by calling getActivity() in onCreateView as:
con=getActivity();
If you can avoid that, don't keep a reference to the context; instead of the
private Context con;
get the current Activity in the code, so use
Toast.makeText(getActivity(), "hello", Toast.LENGTH_LONG).show();
Btw, this seems to be the cause of your crash, as Context is null.

Exception when showing a dialog after orientation change

I have an activity and a fragment inside it.inside fragment, there is a button, and on click of button a dialog shows.
Everything works, until user do a orientation change and click button after it.
IllegalStateException(cannot perform this action after onsaveinstancestate) occurs when user clicks button after orientation change. I'm using android support framework.
Anybody have any idea regarfing this?
Activity Code
public void openMoreDialog(String shareData, String link) {
DialogFragment dialog = new MoreDialog(shareData, link);
dialog.show(getSupportFragmentManager(), "MoreDialog");
}
Fragment Code
public void onAttach(Activity activity) {
super.onAttach(activity);
mControl = (ActivityControl)activity;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ImageButton moreButton = (ImageButton)v.findViewById(R.id.moreButton);
moreButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mControl.openMoreDialog(shareData, link);
}
});
return rootView;
}
FragmentDialog code
public class MoreDialog extends DialogFragment {
private String mShareData;
private String mLink;
public MoreDialog(String shareData, String link){
mShareData = shareData;
mLink = link;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.more_dialog, null);
Button openBtn = (Button)dialogView.findViewById(R.id.openBtn);
openBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openLink(mLink);
}
});
Button shareBtn = (Button)dialogView.findViewById(R.id.shareBtn);
shareBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
shareNews(mShareData);
}
});
builder.setView(dialogView);
return builder.create();
}
private void openLink(String link){
}
private void shareNews(String data){
}
}
Helpful link & solution how to:
https://stackoverflow.com/a/17413324/619673 and btw, constructor in fragment must be empty! Documentation:
http://developer.android.com/reference/android/app/Fragment.html
public Fragment ()
Added in API level 11
Default constructor.
Every fragment must have an empty constructor, so
it can be instantiated when restoring its activity's state. It is
strongly recommended that subclasses do not have other constructors
with parameters, since these constructors will not be called when the
fragment is re-instantiated; instead, arguments can be supplied by the
caller with setArguments(Bundle) and later retrieved by the Fragment
with getArguments().
Applications should generally not implement a constructor. The first
place application code an run where the fragment is ready to be used
is in onAttach(Activity), the point where the fragment is actually
associated with its activity. Some applications may also want to
implement onInflate(Activity, AttributeSet, Bundle) to retrieve
attributes from a layout resource, though should take care here
because this happens for the fragment is attached to its activity.

Categories

Resources