Simple timepicker function is failing with Fatal Exception - NullPointerException and java.lang.reflect.InvocationTargetException on following line :
int hour = time_picker.getCurrentHour();
Fragment_main.xml :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.calapp1.MainActivity$PlaceholderFragment" >
<TimePicker
android:id="#+id/timePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="80dp" />
<TextClock
android:id="#+id/textClock1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="TextClock" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="60dp"
android:text="Show Time"
android:onClick="setTime"
/>
MainActivity.java :
public class MainActivity extends Activity {
TimePicker time_picker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
time_picker = (TimePicker) findViewById(R.id.timePicker1);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public void setTime(View v)
{
int hour = time_picker.getCurrentHour();
int minute = time_picker.getCurrentMinute();
try{
Toast.makeText(getBaseContext(), "select time is "+hour, Toast.LENGTH_LONG).show();
}
catch(Exception e){
e.printStackTrace();
Toast.makeText(getBaseContext(), "problem", Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
Can you please assist?
Thank you,
Yogesh.
You timepicker is in the fragment layout and not in the activity layout. Activity onCreate() is too early to find it in the activity view hierarchy.
Move the findViewById() to fragment onCreateView() and change it to rootView.findViewById().
Please be noted that you have your timepicker in Fragment_main.xml and you're trying it in the onCreate where the contentview is set as setContentView(R.layout.activity_main); so please move the line to onCreateView() and use rootView.findViewById(). That will srely solve the issue.
Related
I have a layout defined in fragment.xml which is called in activity....
and I want to make it visible when a button in parent activity action bar is pressed which is in onOptionsItemSelected() .when i do this it make a error of null object reference....
fragment.xml
<RelativeLayout
android:visibility="invisible"
android:id="#+id/relative_layout_current_job"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/text_view_current_job"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/text_current_job"
android:layout_centerHorizontal="true" />
</RelativeLayout>
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_passenger_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.passenger_main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_job_confirm) {
Button b = (Button) findViewById(R.id.action_job_confirm);
RelativeLayout layoutCurrentJob = (RelativeLayout) findViewById(R.id.relative_layout_current_job);
TextView status = (TextView) findViewById(R.id.text_view_current_job_status_in_history);
if((b.getText().toString()) == "job confirm") {
status.setVisibility(View.INVISIBLE);
b.setText("Job Started");
layoutCurrentJob.setVisibility(View.VISIBLE);
} else {
status.setVisibility(View.VISIBLE);
b.setText("jon confirm");
layoutCurrentJob.setVisibility(View.INVISIBLE);
}
}
return super.onOptionsItemSelected(item);
}
mainmenu.xml
<item
android:id="#+id/action_job_confirm"
android:title="job confirm"
app:showAsAction="never"/>
Screenshot
On your code, Intializing
RelativeLayout layoutCurrentJob=(RelativeLayout) findViewById(R.id.relative_layout_current_job);
is wrong. Because the RelativeLayout you want to hide/show is part of your Fragment .you cannot initialized RelativeLayout by this.
It should be like as shown in below on your Fragment's onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View root = inflater.inflate(R.layout.fragment, container, false);
RelativeLayout layoutCurrentJob=(RelativeLayout) findViewById(R.id.relative_layout_current_job);
}`
You can access widgets of your Fragment by below method
RelativeLayout layoutCurrentJob = (RelativeLayout )fragmentobj.getView().findViewById(R.id.img_one));
layoutCurrentJob.setVisibility(View.VISIBLE);
Do it for your fragment like this:
public class testFragment extends Fragment implements Handler.Callback{
public final Handler handler = new Handler(testFragment.this);
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View root = inflater.inflate(R.layout.fragment, container, false);
}
#Override
public boolean handleMessage(Message msg) {
// TODO Auto-generated method stub
if (msg.what == 1) {
//do your job here
}
return false;
}
}
Call it from your activity like this:
testFragment frag = (testFragment) getFragmentManager()
.findFragmentByTag("Fragment_1");
Message ms = Message.obtain(frag.handler,1);
frag.handler.sendMessage(ms);
I was just trying to get to know well how to change activities and i made a simple example and yet nothing.
The thing is, i dont know how to go back to the main activity after changing to the second activity.
here is MainActivity.java
public class MainActivity extends ActionBarActivity implements OnClickListener{
private String DEBUG_TAG1 = "tag";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button pauseButton = (Button) findViewById(R.id.pause_button);
pauseButton.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
if (v.getId() == R.id.pause_button)
{
Log.d(DEBUG_TAG1,"pause");
Intent i = new Intent(this, SecondActivity.class);
Log.d(DEBUG_TAG1,"intent created");
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
}
protected void onStop() {
super.onStop();
Log.d(DEBUG_TAG1,"on stop");
}
protected void onResume() {
super.onResume();
Log.d(DEBUG_TAG1,"on resume");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
here is SecondActivity.java
public class SecondActivity extends ActionBarActivity implements OnClickListener{
private String DEBUG_TAG2 = "tag";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Button pauseButton2 = (Button) findViewById(R.id.pause_button2);
pauseButton2.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
if(v.getId() == R.id.pause_button2)
{
//here i have to get back to the MainActivity
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
and here are the XML files:
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="net.iversoncru.changeact.MainActivity" >
<Button
android:id="#+id/pause_button"
android:layout_gravity="center"
android:text="||"
android:textColor="#ff0000"
android:textSize="18sp"
android:textStyle="bold"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/buttonshape"
android:shadowColor="#A8A8A8"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="5"
/>
</LinearLayout>
and activity_second.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#000000"
tools:context="net.iversoncru.changeact.SecondActivity" >
<Button
android:id="#+id/pause_button2"
android:layout_gravity="center"
android:text="||"
android:textColor="#aa0000"
android:textSize="18sp"
android:textStyle="bold"
android:layout_width="90dp"
android:layout_height="90dp"
android:background="#drawable/buttonshape"
android:shadowColor="#A8A8A8"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="5"
/>
</LinearLayout>
can anyone tell me how?
I noticed that, when SecondActivity starts, OnStop() is called on MainActivity.
How do i use OnResume()?
Also i read that maybe i have to save the state of MainActivity to be able to be back to it...
Im a little bit lost.
#Override
public void onClick(View v)
{
if(v.getId() == R.id.pause_button2)
{
//here i have to get back to the MainActivity
finish();
}
}
when you switch to the next activity OS pushes current activity on the stack and brings forward the requested activity.
finish() method from activity class will announce to the system that you are done with your work in current activity and restore my previous activity on the stack.
I am new at android app development.I have a problem with my app.I am doing a simple 'Todo List App'. When I deploy my app to android phone.First time it works well.When I change orientation of device, onCreateView() and onActivityCreated() in MyAddFragment works multiple.And 'Add Button' doesn't work after changing orientation.****Please help me how to get rid of the problem.
The following my activity and fragment classes and xml files.
public class MainActivity extends Activity implements Communicator{
FragmentManager man;
private ArrayAdapter<String> todoArrayAdapter;
private ArrayList<String> todoItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
man = getFragmentManager();
MyAddFragment f1 = new MyAddFragment();
MyListFragment f2 = new MyListFragment();
FragmentTransaction transaction = man.beginTransaction();
transaction.add(R.id.frameLayout1, f1, "Add");
transaction.add(R.id.frameLayout2, f2,"List");
Log.i("a", "onCreate - ADDED FRAGMENT");
if (savedInstanceState == null) {
todoItems = new ArrayList<String>();
}else {
todoItems = savedInstanceState.getStringArrayList("veri");
}
todoArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,todoItems);
f2.setListAdapter(todoArrayAdapter);
transaction.commit();
}
public void respond(String data) {
MyListFragment fb = (MyListFragment) man.findFragmentById(R.id.frameLayout2);
todoItems.add(data);
todoArrayAdapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putStringArrayList("veri", todoItems);
}
}
public class MyAddFragment extends Fragment{
Button btnAdd;
EditText txtEdit;
Communicator comm;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_add, container,false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
btnAdd = (Button) getActivity().findViewById(R.id.btnAdd);
txtEdit = (EditText) getActivity().findViewById(R.id.txtEdit);
comm = (Communicator) getActivity();
btnAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String newRecord = txtEdit.getText().toString();
comm.respond(newRecord);
txtEdit.setText("");
}
});
}
}
public class MyListFragment extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list, container,false);
return view;
}
}
public interface Communicator {
public void respond(String data);
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.ceng389hw1.MainActivity" >
<FrameLayout
android:id="#+id/frameLayout1"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:background="#ab3e0f" >
</FrameLayout>
<FrameLayout
android:id="#+id/frameLayout2"
android:layout_width="fill_parent"
android:layout_height="20dp"
android:layout_alignParentBottom="true"
android:layout_below="#+id/frameLayout1"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:background="#ab3eab"
>
</FrameLayout>
</RelativeLayout>
fragment_add.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ab3e0f">
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="#string/btnStringAdd" />
<EditText
android:id="#+id/txtEdit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/btnAdd"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#+id/btnAdd"
android:ems="10"
android:inputType="text" />
</RelativeLayout>
fragment_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ab5810" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
You should change two files in your Application.
First step, you should add following code in androidmanifest file.
android:configChanges="orientation|screenSize"
After you add the code to Androidmanifest, Your androidmanifes file must be like below.
<activity
android:name="com.example.ceng389hw1.MainActivity"
android:configChanges="orientation|screenSize"
android:label="#string/app_name" >
Secon Step, You must be override onConfigurationChanged function like below.
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText( this, "landscape", Toast.LENGTH_SHORT ).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
For more detail -> http://developer.android.com/guide/topics/resources/runtime-changes.html#HandlingTheChange
In your main activity check is fragment already added in activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
...
if(getFragmentManager().getFragment("Add")==null) {
//initialize fragment, create transaction and commit
}
...
}
You can add configChanges parametre inside manifest.xml it will provide you to ignore reinilizating after config changes you can do it simply like that
<activity
android:name="com.youractivity"
android:configChanges="orientation" />
I hope it will help you :)
I'm trying to make an android application. It has two activities: MainActivity and Activity_Service. In MainActivity, there is a button "service" used to pass to Activity_Service. I want to send a string from MainActivity to Activity_Service and then display it in a textview. I would like to show you the codes.
Create the Intent in the MainActivity:
service.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String message = "bla bla bla";
Intent intent = new Intent(MainActivity.this, ActivityService.class);
intent.putExtra("message", message);
startActivity(intent);
}
});
And onCreate() method in the Activity_Service:
public class ActivityService extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
System.out.println(message);
//TextView txtView = new TextView(this);
TextView txtView = (TextView)findViewById(R.id.name);
txtView.setText(message);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_activity,
container, false);
return rootView;
}
}
}
The XML files created by Eclipse while creating the new activity (Activity_Service):
activity_service.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.alljoynandroid.ActivityService"
tools:ignore="MergeRootFrame" />
Fragment_activity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.example.alljoynandroid.ActivityService$PlaceholderFragment" >
<TextView
android:id = "#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
In onCreate() method of Activity_Service, if I use TextView txtView = new TextView(this);, It works: It can pass from MainActivity to Activity_Service, but then we can't setText. Other side, if I use TextView txtView = (TextView)findViewById(R.id.name);, it doesn't work all. Could you please help me to solve it? I was trying for 2 days and now I have no idea.
Remove this code part from your Activity
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
and change
setContentView(R.layout.activity_service);
to
setContentView(R.layout.fragment_activity);
I created two activities and used intents to switch from first activity to second. Also I used fragments in the second activity. When I tried to run the app,the app gets started and it stops unfortunately. When I remove fragments from my app, the app runs. What should I do to get rid of this error? This is my code...
First Activity code
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i=new Intent(MainActivity.this,FirstActivity.class);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Second Activity code
public class FirstActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
public void selectFrag(View view)
{
Fragment fr;
if(view == findViewById(R.id.button2))
{
fr = new FragmentOne();
}
else if(view==findViewById(R.id.button3)){
fr = new FragmentOne();
}
else
{
fr=new FragmentOne();
}
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_first, fr);
fragmentTransaction.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.first, menu);
return true;
}
}
Fragment code
public class FragmentOne extends Fragment {
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
//Inflate the layout for this fragment
return inflater.inflate(
R.layout.fragment_one, container, false);
}
}
Manifest of Second Activity in which I tried to use fragments
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".FirstActivity" >
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button2"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/button2"
android:layout_marginBottom="66dp"
android:text="#string/IDE" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/button3"
android:layout_alignLeft="#+id/button1"
android:layout_marginBottom="42dp"
android:layout_toLeftOf="#+id/fragment_first"
android:text="#string/Applications" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/fragment_first"
android:layout_alignBottom="#+id/fragment_first"
android:layout_alignParentLeft="true"
android:layout_marginLeft="18dp"
android:text="#string/Operating_Systems" />
<fragment
android:id="#+id/fragment_first"
android:name="com.example.test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button3"
android:layout_alignParentTop="true"
android:layout_marginTop="56dp"
android:layout_toRightOf="#+id/button1" />
You are trying to replace a static Fragment. Static Fragments (ones defined in xml) cannot be manipulated via FragmentTransactions.
Also, you are telling Android to inflate a Fragment called com.example.test here:
<fragment
android:id="#+id/fragment_first"
android:name="com.example.test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button3"
android:layout_alignParentTop="true"
android:layout_marginTop="56dp"
android:layout_toRightOf="#+id/button1" />
First, create a container in your FirstActivity's layout
Secondly, using the fragment manager, set FragmentOne to it
That is pretty much all you need to get this working!