issue with a fragment application - android

I am trying to develop an application using fragments that has two different layouts, similar to this one:
when i run my app on the phone it crashes immediatly.. here are my codes:
/layout
activity_titles_fragment.xml details_fragment.xml
/layout-land
activity_titles_fragment.xml
/sec
DetailsActivity.java DetailsFragment.java TitlesFragment.java
activity_titles_fragment.xml
<FrameLayout 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=".TitlesFragment" >
<fragment
class="com.example.fragmentsapp.TitlesFragment"
android:id="#+id/titles"
android:layout_height="match_parent"
android:layout_width="match_parent" />
</FrameLayout>
details_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/details"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
and for landscape, activity_titles_fragment.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="horizontal" >
<fragment
class="com.example.fragmentsapp.TitlesFragment"
android:id="#+id/titles"
android:layout_height="match_parent"
android:layout_width="0px"
android:layout_weight="1" />
<FrameLayout
android:id="#+id/details"
android:layout_height="match_parent"
android:layout_width="0px"
android:layout_weight="1" />
</LinearLayout>
DetailsActivity.java
package com.example.fragmentsapp;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class DetailsActivity extends FragmentActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE) {
// If the screen is now in landscape mode, we can show the
// dialog in-line so we don't need this activity.
finish();
return;
}
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(
R.id.details, details).commit();
}
}
}
DetailsFragment.java
package com.example.fragmentsapp;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DetailsFragment extends Fragment {
public static DetailsFragment newInstance(int index)
{
// supply input index as argument
DetailsFragment f = new DetailsFragment();
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
public int getShownIndex()
{
return getArguments().getInt("index", 0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(container == null)
return null;
TextView text = new TextView(getActivity());
text.setText("Fragment number: " + getShownIndex());
return text;
}
}
TitlesFragment.java
package com.example.fragmentsapp;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class TitlesFragment extends ListFragment {
boolean mDualPane;
int mCurCheckPosition = 0;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// populate list items with list view
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,
getResources().getStringArray(R.array.titles)));
// check for mobile dual pane
View detailsFrame = getActivity().findViewById(R.id.details);
mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
if (savedInstanceState != null)
{
mCurCheckPosition = savedInstanceState.getInt("curChoice",0);
}
if (mDualPane)
{
showDetails(mCurCheckPosition);
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
showDetails(position);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
private void showDetails(int index) {
mCurCheckPosition = index;
if(mDualPane)
{
DetailsFragment details = (DetailsFragment) getFragmentManager().findFragmentById(R.id.details);
if(details == null || details.getShownIndex() != index)
{
details = DetailsFragment.newInstance(index);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.details, details);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
} else {
Intent intent = new Intent();
intent.setClass(getActivity(), DetailsActivity.class);
intent.putExtra("index", index);
startActivity(intent);
}
}
}

Have you declared all of your activities in your Android ? Have you not forgotten this one ?
<activity android:name=".activities.FragmentLayout$DetailsActivity">
</activity>
Also, you should add a stacktrace each time you are facing such kind of errors.

Related

it gives null point exception when the list item is clicked

In portrait, it gives null point exceptioin when the list item is clicked but landscape works just fine... In AnotherAcitivity.java Fragment f2 gets null while debugged...
package com.example.myfragmentqadvancedel;
import com.example.myfragmentqadvancedel.FragmentA.Communicator;
import android.os.Bundle;
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Intent;
public class MainActivity extends Activity implements Communicator{
FragmentA f1;
FragmentB f2;
FragmentManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager = getFragmentManager();
f1=(FragmentA) manager.findFragmentById(R.id.fragment1);
f1.setCommunicator(this);
}
#Override
public void respond(int index) {
f2=(FragmentB) manager.findFragmentById(R.id.fragment2);
if (f2!=null && f2.isVisible()) {
f2.changeData(index );
}else {
Intent intent = new Intent(this,AnotherActivity.class);
intent.putExtra("index", index);
startActivity(intent);
}
}
}
FragmentA
package com.example.myfragmentqadvancedel;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class FragmentA extends Fragment implements OnItemClickListener {
ListView list;
Communicator communicator;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_a, container,false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
list=(ListView) getActivity().findViewById(R.id.listView1);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.chapters, android.R.layout.simple_list_item_1);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
}
public void setCommunicator(Communicator communicator) {
this.communicator = communicator;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int i, long arg3) {
communicator.respond(i);
}
public interface Communicator{
public void respond(int index);
}
}
AnotherActivity.java
package com.example.myfragmentqadvancedel;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
public class AnotherActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
Intent intent = getIntent();
int index=intent.getIntExtra("index", 0);
FragmentB f2= (FragmentB) getFragmentManager().findFragmentById(R.id.fragment2);
if(f2!=null) <-- f2 gets null, index gets +ve value as checked in debugger
f2.changeData(index);
}
}
FragmentB
package com.example.myfragmentqadvancedel;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FragmentB extends Fragment{
TextView text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_b, container,false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
text=(TextView) getActivity().findViewById(R.id.textView1);
}
public void changeData(int index){
String[] descriptions = getResources().getStringArray(R.array.description);
text.setText(descriptions[index]);
}
}
logcat
05-27 16:40:37.866: E/AndroidRuntime(961): FATAL EXCEPTION: main
05-27 16:40:37.866: E/AndroidRuntime(961): java.lang.NullPointerException
05-27 16:40:37.866: E/AndroidRuntime(961): at com.example.myfragmentqadvance.MainActivity.respond(MainActivity.java:26)
05-27 16:40:37.866: E/AndroidRuntime(961): at com.example.myfragmentqadvance.Fragment1.onItemClick(Fragment1.java:42)
05-27 16:40:37.866: E/AndroidRuntime(961): at android.widget.AdapterView.performItemClick(AdapterView.java:298)
05-27 16:40:37.866: E/AndroidRuntime(961): at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
activity_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=".MainActivity">
<fragment
android:id="#+id/fragment1"
android:name="com.example.myfragmentqadvancedel.FragmentA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
fragment_a.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="#0f0">
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
fragment_b.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="#00f" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textColor="#fff"/>
</LinearLayout>
activity_another.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=".AnotherActivity" >
<fragment
android:id="#+id/fragment2"
android:name="com.example.myfragmentqadvancedel.FragmentB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="38dp" />
</RelativeLayout>
Your interface in Fragment A seems to be Null. Instead of setting the Interface after finding fragment by id, you should use onAttach(Activity activity) method. Here you can force your parent Activity to implement this interface. Check out the code below.
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
/* Check if the Activity implemented Callbacks from this Fragment */
try {
communicator = (Communicator) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement " + this.getClass().getSimpleName() + "Callbacks");
}
}
when i keep the code frm onCreate to onStart of AnotherActivity , it works... dont know whats the prob to put them in onCreate
public class AnotherActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
}
#Override
protected void onStart() {
super.onStart();
Intent intent = getIntent();
int index=intent.getIntExtra("index", 0);
FragmentB f2= (FragmentB) getFragmentManager().findFragmentById(R.id.fragment2);
if(f2!=null)
f2.changeData(index);
}
}

how to display dialog when moving from 1 tab to another - implementation uses Fragments in Android

I have created a fragment activity with 3 tabs. When I move from tab 1 to tab 3, it takes around 5 seconds to load tab 3( due to some time consuming task ). During this loading time, I want to show a dialog.
I put the dialog inside onTabSelected(), but the dialog shows up only after the 3rd tab display comes up. I want it to show between "the time I clicked the 3rd tab" and "the time the 3rd tab actually comes up". Please do let me know ur suggestions.
Editted :
Sample code :
MainActivity.java:
package com.example.trial;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.Window;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private static final String STATE_SELECTED_NAVIGATION_ITEM ="selected_navigation_item";
ProgressDialog nDialog;
Fragment dashboardFrag = new DashboardTab();
Fragment Tab1 = new Tab1();
Fragment Tab2 = new Tab2();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_main);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.addTab(actionBar.newTab().setText("Tab1")
.setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Tab2")
.setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Tab3")
.setTabListener(this));
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
getActionBar().setSelectedNavigationItem(
savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar()
.getSelectedNavigationIndex());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
if (tab.getPosition() == 0) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, Tab1).commit();
}
else if (tab.getPosition() == 1) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, Tab2).commit();
}
else if (tab.getPosition() == 2) {
showProgress1();
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, dashboardFrag).commit();
}
}
void showProgress1(){
nDialog = new ProgressDialog(MainActivity.this); //Here I get an error: The constructor ProgressDialog(PFragment) is undefined
nDialog.setMessage("Loading..");
nDialog.setTitle("Fetching Data");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
}
Tab1.java
package com.example.trial;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Tab1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1, container, false);
return rootView;
}
}
Tab2.java
package com.example.trial;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Tab2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab2, container, false);
return rootView;
}
}
DashboardTab.java
package com.example.trial;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class DashboardTab extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.dashboard, container, false);
try {
Thread.sleep(5*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rootView;
}
}
activity_main.xml
<FrameLayout android:id="#+id/container" android:layout_height="match_parent" android:layout_width="match_parent" tools:context=".MainActivity" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
</FrameLayout>
tab1.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" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tab1"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
tab2.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" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="tab2"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
dashboard.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" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dashBoard"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
I didn't find something like you are telling, may be you are having issues with your phone memory, however an approach to show dialog when performing time consuming tasks through your code
public class DashboardTab extends Fragment {
private ProgressDialog nDialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.dashboard, container, false);
showProgress1();
YourTimeConsumingTask();
nDialog.dismiss();
return rootView;
}
private void YourTimeConsumingTask(){
try {
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void showProgress1() {
nDialog = new ProgressDialog(getActivity()); // Here I get an error:
// The constructor
// ProgressDialog(PFragment)
// is undefined
nDialog.setMessage("Loading..");
nDialog.setTitle("Fetching Data");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
}

Android FragmentTransaction won't add or replace fragment to container

This question has been asked before, however, I have not found an appropriate answer for my problem. I am building a simple fragment activity that displays three buttons at the top of the screen in one container that when pressed update the fragment in the rest of the screen. Just like a tab host. I am using android.support.v4.app.Fragment in all code, but still cannot get the transaction manager to display the fragment in the container. I've been banging my head on the keyboard for hours and connot find the problem.
Here is the main activity extending FragmentActivity:
package com.example.testudpfragment;
import com.example.testudp.R;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
public class TestUDPFragmentActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_udpfragment);
if(savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.menu_container, new MenuFragment()).commit();
}
}
}
Here is the MenuFragment class extending fragment for my tabs:
package com.example.testudpfragment;
import com.example.testudp.R;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.support.v4.app.*;
public class MenuFragment extends Fragment{
Fragment frag;
FragmentTransaction fragTransaction;
public MenuFragment() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frament_menu, container, false);
frag = new StringsFragment();
fragTransaction = getFragmentManager().beginTransaction().add(R.id.container, frag);
System.out.println(fragTransaction.toString());
fragTransaction.commit();
Button btnString = (Button) view.findViewById(R.id.button_string);
Button btnSlider = (Button) view.findViewById(R.id.button_slider);
Button btnTouch = (Button) view.findViewById(R.id.button_touch);
btnString.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
frag = new StringsFragment();
fragTransaction = getFragmentManager().beginTransaction().replace(R.id.container, frag);
fragTransaction.commit();
}
});
btnSlider.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
frag = new SlidersFragment();
fragTransaction = getFragmentManager().beginTransaction().replace(R.id.container, frag);
fragTransaction.commit();
}
});
btnTouch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
frag = new TouchFragment();
fragTransaction = getFragmentManager().beginTransaction().replace(R.id.container, frag);
fragTransaction.commit();
}
});
return view;
}
}
Here is one of the three fragments that I can't get to display:
package com.example.testudpfragment;
import com.example.testudp.R;
import android.support.v4.app.*;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class StringsFragment extends Fragment {
public StringsFragment() {
}
public View onCreatView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_strings, null);
return rootView;
}
}
activity_test_udpfragment:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/menu_container"
android:background="#eee"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</FrameLayout>
<FrameLayout
android:id="#+id/container"
android:background="#aaa"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
Here is frament_menu:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
style="android.att/buttonBarStyle" >``
<Button
android:id="#+id/button_string"
style="android.att/buttonBarButtonStyle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="String" />
<Button
android:id="#+id/button_slider"
style="android.att/buttonBarButtonStyle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Slider" />
<Button
android:id="#+id/button_touch"
style="android.att/buttonBarButtonStyle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Touch" />
</LinearLayout>
And here is fragment_strings:
<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">
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:scaleType = "centerCrop"
android:src="#drawable/me_hooded" />
</RelativeLayout>
Any help is greatly appreciated!
EDIT:
Here is new TestUDPActivityFragment with buttons to change fragment:
package com.example.testudpfragment;
import com.example.testudp.R;
import android.support.v4.app.*;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.os.Bundle;
public class TestUDPFragmentActivity extends FragmentActivity {
Fragment frag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_udpfragment);
Button btnString = (Button)findViewById(R.id.btn_string);
Button btnSlider = (Button)findViewById(R.id.btn_slider);
Button btnTouch = (Button)findViewById(R.id.btn_touch);
if(savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, new StringsFragment()).commit();
btnString.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
frag = new StringsFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.container, frag).commit();
}
});
btnSlider.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
frag = new SlidersFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.container, frag).commit();
}
});
btnTouch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
frag = new TouchFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.container, frag).commit();
}
});
}
}
}
I can see a couple of problems...
First, your FrameLayout containers are defined in your activity_test_udpfragment.xml layout file which is inflated by your TestUDPFragmentActivity. The problem with attempting to create / add your StringsFragment in your MenuFragment code using the following...
fragTransaction = getFragmentManager().beginTransaction().add(R.id.container, frag);
...is the MenuFragment inflates a layout from your frament_menu.xml which doesn't contain a FrameLayout with id of R.id.container.
That's your first problem but the second is with attempting to use a Fragment to create / add a Fragment in the first place. Your MenuFragment is not able to use the Framelayout in the TestUDPFragmentActivity.
In short, I suspect you want both Fragments to appear in your Activity layout (and not have the StringsFragment as a 'child' of MenuFragment) in which case you need to put all code for creating / adding both Fragments into your Activity.

Android: Error when triggering fragment from within the fragment itself

I'm trying to learn fragments on android and my code is not working.
FragmentCustomAnimations contains MainActivity.
What i want is the frame MainActivity to change when i push the button on MainActivity.
The error message on logcat is Could not find a method sendMessage(View) in the activity class com.example.myfirstapp.FragmentCustomAnimations for onClick handler on view class android.widget.Button with id 'button1'
Eventhough there is no function sendmessage in all my file.
FYI, its working when i put the button on FragmentCustomAnimations.
Is it impossible to use the button on fragment to trigger action to change the fragment itself?
Here is the code:
FragmentCustomAnimations.java
package com.example.myfirstapp;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentCustomAnimations extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_stack);
if (savedInstanceState == null) {
Fragment newFragment = InitialFragment.newInstance();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.simple_fragment, newFragment).commit();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
public static class InitialFragment extends Fragment {
static InitialFragment newInstance() {
InitialFragment f = new InitialFragment();
Bundle args = new Bundle();
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main, container, false);
return v;
}
}
}
fragment_stack.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:padding="4dip"
android:gravity="center_horizontal"
android:background="#drawable/window2x"
android:layout_width="match_parent" android:layout_height="match_parent">
<FrameLayout
android:id="#+id/simple_fragment"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1">
</FrameLayout>
</LinearLayout>
MainActivity.java
package com.example.myfirstapp;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button inner = (Button) findViewById(R.id.button1);
inner.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
getActionBar().setDisplayShowHomeEnabled(false);
return super.onCreateOptionsMenu(menu);
}
#Override
public void onClick(View v) {
addFragmentToStack();
}
void addFragmentToStack() {
Fragment newFragment = CountingFragment.newInstance();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(R.animator.fragment_slide_left_enter,
R.animator.fragment_slide_left_exit,
R.animator.fragment_slide_right_enter,
R.animator.fragment_slide_right_exit);
ft.replace(R.id.simple_fragment, newFragment);
ft.addToBackStack(null);
ft.commit();
}
public static class CountingFragment extends Fragment {
static CountingFragment newInstance() {
CountingFragment f = new CountingFragment();
Bundle args = new Bundle();
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_display_message, container, false);
return v;
}
}
}
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:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="?android:attr/actionBarSize"
android:layout_gravity="center_vertical"
tools:context=".MainActivity" >
<EditText
android:id="#+id/edit_message"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/edit_message"
android:layout_gravity="center_vertical"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editTextEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/editTextEmail"
android:inputType="textEmailAddress" />
<EditText
android:id="#+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/editTextPassword"
android:inputType="textPassword" />
<Button
android:id="#+id/button1"
style="#style/CodeFont"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:background="#drawable/custom_button"
android:text="#string/button_send" />
</LinearLayout>

Issue with Fragment on Android Developer Page

I was reading the documentation on Fragment on the Developer site. I created a new project targeting api 8:android 2.2. I have the Android Support Library install, and I added the android support library to the project. I started implementing the helper method showDetails, and I get the red squiggly line saying that "a_item could not be resolved". I don't remember the instruction saying create an a_item variable or add a layout with a_item id.
In addition, in the detail activity, I am getting an error message too. (getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();) It says "The method add(int, Fragment) in the type FragmentTransaction is not applicable for the arguments (int, DetailsFragment)". Did I miss something in the instructions?
Here are my sample codes:
package com.example.fragmentlayout;
import android.app.Activity;
import android.app.Fragment;
import android.content.res.Configuration;
import android.os.Bundle;
public class DetailsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getResources().getConfiguration().ORIENTATION_LANDSCAPE == Configuration.ORIENTATION_LANDSCAPE )
{
finish();
return;
}
if(savedInstanceState == null)
{
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
}
}
}
Here is the Titles Fragment:
package com.example.fragmentlayout;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class TitlesFragment extends ListFragment {
boolean mDualPane;
int mCurCheckPosition =0;
String[] titles = {"Title 1", "Title 2", "Title 3"};
String[] Details = {"Details for one", "Details for two", "Details for Three"};
#SuppressLint("InlinedApi")
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_activated_1, titles));
View detailsFrame = getActivity().findViewById(R.id.fragment2);
mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
if(savedInstanceState != null)
{
mCurCheckPosition = savedInstanceState.getInt("curChoise", 0);
}
if(mDualPane)
{
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
showDetails(mCurCheckPosition);
}
}
private void showDetails(int index) {
mCurCheckPosition = index;
if(mDualPane)
{
getListView().setItemChecked(index, true);
DetailsFragment details = (DetailsFragment) getFragmentManager().findFragmentById(R.id.fragment2);
if(details == null || details.getShownIndex() != index)
{
details = DetailsFragment.newInstance(index);
FragmentTransaction ft = getFragmentManager().beginTransaction();
if(index ==0)
{
ft.replace(R.id.fragment2, details);
} else
{
ft.replace(R.id.a_item, details);
}
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
} else
{
Intent intent = new Intent();
intent.setClass(getActivity(), DetailsActivity.class);
intent.putExtra("index", index);
startActivity(intent);
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
showDetails(position);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
}
Here is the detailsFragment:
package com.example.fragmentlayout;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import android.widget.TextView;
public class DetailsFragment extends Fragment {
String[] Details = {"Details for one", "Details for two", "Details for Three"};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(container == null)
{
return null;
}
ScrollView scroller = new ScrollView(getActivity());
TextView text = new TextView(getActivity());
int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,4, getActivity().getResources().getDisplayMetrics());
text.setPadding(padding, padding, padding, padding);
scroller.addView(text);
text.setText(Details[getShownIndex()]);
return scroller;
// return super.onCreateView(inflater, container, savedInstanceState);
}
public static DetailsFragment newInstance(int index)
{
DetailsFragment f = new DetailsFragment();
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
public int getShownIndex()
{
return getArguments().getInt("index", 0);
}
}
Here is the land and portrait layout
<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:orientation="horizontal">
<fragment
android:id="#+id/fragment1"
android:name="com.example.fragmentlayout.TitlesFragment"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1" />
<fragment
android:id="#+id/fragment2"
android:name="com.example.fragmentlayout.DetailsFragment"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"/>
</LinearLayout>
<FrameLayout 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:orientation="horizontal">
<fragment
android:id="#+id/fragment1"
android:name="com.example.fragmentlayout.TitlesFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
Perhaps, it's a mistake. The answer is here
https://code.google.com/p/android/issues/detail?id=54837
The author of linked message advises to replace code fragment
if (index == 0) {
ft.replace(R.id.details, details);
} else {
ft.replace(R.id.a_item, details);
}
with code fragment
if (index == 0) {
ft.add(R.id.details, details);
} else {
ft.replace(R.id.details, details);
}
or maybe just
ft.replace(R.id.details, details);
Your DetailsActivity should extend FragmentActivity
You should use getSupportFragmentManager()
If you nest fragments into other fragments consider using getChildFragmentManager()
(ok, i didn't look through all of the code, so not sure if 3 is applicable)
You need to use getSupportFragmentManager instead of getFragmentManager, because you are using support fragments.
The R.id.a_item references the id of the layout in your layout file. Instead of android:id="#+id/fragment1", make it android:id="#+id/a_item"

Categories

Resources