Fragment in layout - android

I'am trying to communicate betwen two fragment extended classes with the help of MainActivity bt always get an error{03-01 14:30:42.675: E/AndroidRuntime(1724): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myfrag/com.example.myfrag.Tool}: android.view.InflateException: Binary XML file line #8: Error inflating class fragment}
package com.example.myfrag;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class ToolBoxFrag extends FragmentActivity implements OnSeekBarChangeListener {
private static int seekvalue = 10;
private static EditText edittext;
ToolbarListener activityCallback;
public interface ToolbarListener {
public void onButtonClick(int position, String text);
}
public void onAttach(Fragment activity) {
super.onAttachFragment(activity);
try {
activityCallback = (ToolbarListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement ToolbarListener");
}
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
seekvalue = progress;
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
setContentView(R.layout.activity_main);
edittext = (EditText)findViewById(R.id.editText1);
final SeekBar seekbar =
(SeekBar) findViewById(R.id.seekBar1);
seekbar.setOnSeekBarChangeListener(this);
final Button button =
(Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
buttonClicked(v);
}
});
return ;
}
public void buttonClicked (View view) {
activityCallback.onButtonClick(seekvalue,
edittext.getText().toString());
}
}
TextFragment.java
package com.example.myfrag;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TextFragment extends FragmentActivity {
private static TextView textview;
#Override
public void onCreate( Bundle savedInstanceState) {
setContentView(R.layout.main);
textview = (TextView) findViewById(R.id.textView1);
return;
}
public void changeTextProperties(int fontsize, String text)
{
textview.setTextSize(fontsize);
textview.setText(text);
}
}
MainActivity
package com.example.myfrag;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
public class Tool extends FragmentActivity implements ToolBoxFrag.ToolbarListener {
//public TextFragment tf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.frag2);
}
public void onButtonClick(int fontsize, String text) {
TextFragment tf = new TextFragment();
getSupportFragmentManager().findFragmentById(R.id.main);
tf.changeTextProperties(fontsize, text);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main,
menu);
return true;
}
}
xml layout
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".FragmentExampleActivity" >
<fragment
android:id="#+id/activity_main"
android:name="com.example.fragmentexample.ToolbarFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
tools:layout="#layout/activity_main" />
<fragment
android:id="#+id/main"
android:name="com.example.fragmentexample.TextFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
tools:layout="#layout/main" />
</RelativeLayout>

Problem is the class path you have described the fragment name path wrong ..
it should be com.example.myfrag not com.example.fragmentexample
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".FragmentExampleActivity" >
<fragment
android:id="#+id/activity_main"
android:name="com.example.myfrag.ToolbarFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
tools:layout="#layout/activity_main" />
<fragment
android:id="#+id/main"
android:name="com.example.myfrag.TextFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
tools:layout="#layout/main" />
</RelativeLayout>

Related

Android: Error inflating class fragment, using edittext and seekbar

I'm trying to write a project with an activity where there is a fragment with an edit text, a seekbar and a button and below a fragment with a textview. If you write on the editText and you move the seekbar you change the content and the size of the text in the textView of the fragment below. I used the following already done commented project and then I rename some elements and I corrected some parts:here
However I get an error "
Error inflating class fragment
": the following is part of the error message:
03-21 08:33:11.174 2830-2830/com.example.utente.fragmentconmutamenti
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.utente.fragmentconmutamenti, PID: 2830
java.lang.RuntimeException: Unable to start activity ComponentInfo {com.example.utente.fragmentconmutamenti/com.example.utente.fragmentconmutamenti.MainActivity}:
android.view.InflateException: Binary XML file line #13: Binary
XML file line #13: Error inflating class fragment
I read similar questions like this and their answers but I still didn't find what is the error in my code.
MainActivity.java
package com.example.utente.fragmentconmutamenti;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButtonClick(int fontsize, String text) {
TextFragment textFragment =
(TextFragment)
getFragmentManager().findFragmentById(R.id.text_fragment);
textFragment.changeTextProperties(fontsize, text);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
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.utente.fragmentconmutamenti.MainActivity">
<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="com.example.utente.fragmentconmutamenti.ToolbarFragment"
android:id="#+id/toolbar_fragment"
tools:layout="#layout/toolbar_fragment"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="com.example.utente.fragmentconmutamenti.TextFragment"
android:id="#+id/text_fragment"
android:layout_marginTop="130dp"
android:layout_below="#+id/toolbar_fragment"
android:layout_centerHorizontal="true"
tools:layout="#layout/text_fragment" />
</RelativeLayout>
ToolbarFragment.java
package com.example.utente.fragmentconmutamenti;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
public class ToolbarFragment
implements SeekBar.OnSeekBarChangeListener
{
private static int seekvalue = 10;
private static EditText edittext;
ToolbarListener activityCallback;
public interface ToolbarListener {
public void onButtonClick(int position, String text);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
activityCallback = (ToolbarListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement ToolbarListener");
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view_toolbar_fragment =inflater.inflate(R.layout.toolbar_fragment, container, false);
edittext = (EditText) view_toolbar_fragment.findViewById(R.id.editText1);
final SeekBar seekbar =
(SeekBar) view_toolbar_fragment.findViewById(R.id.seekBar1);
seekbar.setOnSeekBarChangeListener(this);
final Button button =
(Button) view_toolbar_fragment.findViewById(R.id.button_text);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
buttonClicked(v);
}
});
return view_toolbar_fragment;
}
public void buttonClicked (View view) {
activityCallback.onButtonClick(seekvalue,
edittext.getText().toString());
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
seekvalue = progress;
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onStopTrackingTouch(SeekBar arg0) {
}
}
toolbar_fragment.xml
package com.example.utente.fragmentconmutamenti;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
public class ToolbarFragment
implements SeekBar.OnSeekBarChangeListener
{
private static int seekvalue = 10;
private static EditText edittext;
ToolbarListener activityCallback;
public interface ToolbarListener {
public void onButtonClick(int position, String text);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
activityCallback = (ToolbarListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement ToolbarListener");
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view_toolbar_fragment =inflater.inflate(R.layout.toolbar_fragment, container, false);
edittext = (EditText) view_toolbar_fragment.findViewById(R.id.editText1);
final SeekBar seekbar =
(SeekBar) view_toolbar_fragment.findViewById(R.id.seekBar1);
seekbar.setOnSeekBarChangeListener(this);
final Button button =
(Button) view_toolbar_fragment.findViewById(R.id.button_text);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
buttonClicked(v);
}
});
return view_toolbar_fragment;
}
public void buttonClicked (View view) {
activityCallback.onButtonClick(seekvalue,
edittext.getText().toString());
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
seekvalue = progress;
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onStopTrackingTouch(SeekBar arg0) {
}
}
TextFragment.java
package com.example.utente.fragmentconmutamenti;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TextFragment
extends Fragment {
private static TextView textview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view_text_fragment =inflater.inflate(R.layout.text_fragment, container, false);
textview = (TextView) view_text_fragment.findViewById(R.id.TextView1);
return view_text_fragment;
}
public void changeTextProperties(int fontsize, String text)
{
textview.setTextSize(fontsize);
textview.setText(text);
}
}
text_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/TextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Fragment Two"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Update: i replaced android.app.Fragment with android.support.v4.app.Fragment; and getFragmentManager() with
getSupportFragmentManager()
but it get a very similar error:
Process: com.example.utente.fragmentconmutamenti, PID: 3170
java.lang.RuntimeException: Unable to start activity ComponentInfo
{com.example.utente.fragmentconmutamenti/com.example.utente.fragmentconmutamenti.MainActivity}:
android.view.InflateException: Binary XML file line #13: Binary XML
file line #13: Error inflating class fragment
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
Check your imports in both of the Fragments
You should go with
import android.support.v4.app.Fragment;
instead of
import android.app.Fragment;
and on click
TextFragment textFragment =
(TextFragment)
getSupportFragmentManager().findFragmentById(R.id.text_fragment);

xml layout loads but my activity doesn't respond to button clicks

I'm new at this but I already made a small app that worked the same way.
I can't see what I'm doing wrong because the code looks quiet the same as my previous app.
When I run it or debug my app it shows my layout on my emulator so it does load the page that has to be loaded but that's all it does, it doesn't listen to button clicks. I also gives me no errors.
Here's my XML code for 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity$PlaceholderFragment">
<TextView
android:text="Eventaris"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textSize="100px"
android:textStyle="bold"
android:id="#+id/lblEventaris"
/>
<LinearLayout
android:layout_width="500px"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:orientation="vertical"
android:id="#+id/login">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Gebruikersnaam"
android:id="#+id/txtGebruikersnaam"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Wachtwoord"
android:inputType="textPassword"
android:layout_below="#id/txtGebruikersnaam"
android:id="#+id/txtWachtwoord"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Inloggen"
android:id="#+id/btnInloggen"
android:layout_below="#id/txtWachtwoord"/>
</LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:layout_below="#id/login">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="nog geen account?"
android:gravity="center"
android:id="#+id/lblRegistratie"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Registeren"
android:id="#+id/btnRegistreren"
android:layout_below="#id/lblRegistratie"/>
</RelativeLayout>
</RelativeLayout>
Here's my fragmennt activity MainFragment.Java
package com.example.arno.eventaris;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import java.sql.SQLException;
/**
* Created by Arno on 28/04/2015.
*/
public class MainFragment extends Fragment {
private OnMainFragmentInteractionListener mListener;
private View view;
public MainFragment()
{
//required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view=inflater.inflate(R.layout.fragment_main, container, false);
Button btnInloggen = (Button) view.findViewById(R.id.btnInloggen);
btnInloggen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
inloggen();
} catch (SQLException e) {
e.printStackTrace();
}
}
});
Button btnRegistreren = (Button) view.findViewById(R.id.btnRegistreren);
btnRegistreren.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
navigeerRegistratie();
}
});
return view;
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try{
mListener = (OnMainFragmentInteractionListener) activity;
}
catch (ClassCastException e)
{
throw new ClassCastException(activity.toString() + "must implement OnFragmentInteractionListener");
}
}
public void inloggen() throws SQLException {
EditText gebr=(EditText) view.findViewById(R.id.txtGebruikersnaam);
EditText wachtw=(EditText) view.findViewById(R.id.txtWachtwoord);
String gebruiker = gebr.getText().toString();
String wachtwoord = wachtw.getText().toString();
mListener.login(gebruiker, wachtwoord);
}
public void navigeerRegistratie()
{
mListener.navigeerRegistratie();
}
#Override
public void onDetach()
{
super.onDetach();
mListener = null;
}
public interface OnMainFragmentInteractionListener {
//Todo: Update argument type and name
public void login(String gebruiker, String wachtwoord) throws SQLException;
public void navigeerRegistratie();
}
}
Here is my Main Activity MainActivity.java
package com.example.arno.eventaris;
import android.app.DialogFragment;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.example.arno.eventaris.Database.DBAdapter;
import java.sql.SQLException;
public class MainActivity extends ActionBarActivity implements MainFragment.OnMainFragmentInteractionListener,RegistratieFragment.OnRegistratieFragmentInteractionListener{
private Cursor gebruikerCursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.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.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void login(String gebruiker, String wachtwoord) throws SQLException {
DBAdapter db = new DBAdapter(this);
db.open();
gebruikerCursor = db.getGebruiker(gebruiker);
if(gebruikerCursor.moveToFirst()) {
gebruikerCursor.moveToFirst();
String wwControle = gebruikerCursor.getString(gebruikerCursor.getColumnIndex("wachtwoord"));
if (wachtwoord.equals(wwControle)) {
HomeFragment fragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putString("gebruikersnaam", gebruiker);
fragment.setArguments(bundle);
getFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
} else {
DialogFragment errorlogin = new ErrorLogin();
errorlogin.show(getFragmentManager(), "Wachtwoord incorrect!");
}
}
else
{
DialogFragment errorlogin = new ErrorLogin();
errorlogin.show(getFragmentManager(), "Gebruikersnaam incorrect!");
}
db.close();
}
#Override
public void navigeerRegistratie() {
getFragmentManager().beginTransaction().replace(R.id.container, new RegistratieFragment()).commit();
}
#Override
public void registreren(String gebruiker, String voornaam, String naam, String email, String wachtwoord, String herhaalWachtwoord) {
if(wachtwoord.equals(herhaalWachtwoord)) {
DBAdapter db = new DBAdapter(this);
db.open();
long id = db.insertGebruiker(gebruiker, voornaam, naam, email, wachtwoord);
getFragmentManager().beginTransaction().replace(R.id.container, new MainFragment()).commit();
}
else
{
DialogFragment errorregistratie = new ErrorRegistratie();
errorregistratie.show(getFragmentManager(), "Wachtwoorden komen niet overeen!");
}
}
/**
* 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;
}
}
}
And as last here is my activity_main.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=".MainActivity" tools:ignore="MergeRootFrame" />
Thanks in advance!
Fixed it by making a new project with the same code, had to be a problem way deeper than my code.

Text is not getting entered in the edit text control

When I am trying to create tab control and add an edit text in Android, and then enter any character from UI (within Tab1 for Edit Text), the text is not getting entered in the edit text control. I am using Android Studio 1.1.0. Code is as follows.
Main Activity.class
import android.os.Bundle;
import android.support.v4.app.FragmentTabHost;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private static final String TAB_1_TAG = "one";
private static final String TAB_2_TAG = "two";
private FragmentTabHost mTabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_tabs);
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
Bundle b = new Bundle();
mTabHost.addTab(mTabHost.newTabSpec(TAB_1_TAG).setIndicator("Tab1"), FirstContainerFragment.class, b);
b.putString("key", "One");
b = new Bundle();
b.putString("key", "Two");
mTabHost.addTab(mTabHost.newTabSpec(TAB_2_TAG).setIndicator("Tab2"), SecondContainerFragment.class, b);
}
#Override
public void onBackPressed() {
boolean isPopFragment = false;
String currentTabTag = mTabHost.getCurrentTabTag();
if (currentTabTag.equals(TAB_1_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_1_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_2_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_2_TAG)).popFragment();
}
if (!isPopFragment) {
finish();
}
}
}
my_tab.xml
<android.support.v4.app.FragmentTabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TabWidget
android:id="#android:id/tabs"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"/>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0"/>
<FrameLayout
android:id="#+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
BaseContainerFragment.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
public class BaseContainerFragment extends Fragment {
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.replace(R.id.container_framelayout, fragment);
transaction.commit();
getChildFragmentManager().executePendingTransactions();
}
public boolean popFragment() {
boolean isPop = false;
if (getChildFragmentManager().getBackStackEntryCount() > 0) {
isPop = true;
getChildFragmentManager().popBackStack();
}
return isPop;
}
}
container_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container_framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
FirstContainerFragment.java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FirstContainerFragment extends BaseContainerFragment {
private boolean mIsViewInited;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.container_fragment, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (!mIsViewInited) {
mIsViewInited = true;
initView();
}
}
private void initView() {
replaceFragment(new FirstFragment(), false);
}
}
FirstFragment.java
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class FirstFragment extends Fragment {
EditText edtTxt;
TextView txtView;
Button btnEnter;
public FirstFragment() {
// TODO Auto-generated constructor stub
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v = LayoutInflater.from(getActivity()).inflate(R.layout.first_layout,null);
edtTxt =(EditText)v.findViewById(R.id.editText);
txtView =(TextView)v.findViewById(R.id.textText222);
btnEnter = (Button)v.findViewById(R.id.button);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
btnEnter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0){
txtView.setText(edtTxt.getText());
}
});
}
}
similarly I have the following class and layouts
SecondContainerFragment.java
SecondFragment.java

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);
}
}

Android cannot access textView component from activity

I have the following actvity.
package org.dewsworld.ui;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class DetailList extends Activity {
TextView title = (TextView) findViewById(R.id.title) ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_list);
title.setText("hello world");
}
}
Which manipulate detail_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent" android:weightSum="1">
<TextView android:id="#+id/title" android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_height="wrap_content" android:layout_width="match_parent"
android:text="#string/headline" />
<ListView android:id="#+id/listView1" android:layout_width="match_parent" android:layout_height="match_parent"></ListView>
</LinearLayout>
But, when I run this, I get a runtime error. LogCat is,
try like this
public class DetailList extends Activity {
TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_list);
title = (TextView) findViewById(R.id.title) ;
title.setText("hello world");
}
}
package org.dewsworld.ui;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class DetailList extends Activity {
TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_list);
title = (TextView) findViewById(R.id.title) ;;
title.setText("hello world");
}
}
its complaining because you are trying to get the value of textView using an Activity method which is not been created yet (Since its Oncreate() is yet to run)

Categories

Resources