getSupportFragmentManager()。findFragmentById给我一个nullPointer

时间:2014-10-07 01:53:21

标签: android

我有viewpager的应用程序。当我点击第一个片段上的按钮时,我需要调用其他片段方法。

这是我的邮件活动

view plainprint?
Note: Text content in the code blocks is automatically word-wrapped
package src.com.programmingmobile.pageviewer;  

package src.com.programmingmobile.pageviewer;  

import java.util.ArrayList;  
import java.util.List;  

import android.os.Bundle;  
import android.support.v4.app.Fragment;  
import android.support.v4.app.FragmentActivity;  
import android.support.v4.app.FragmentManager;  
import android.support.v4.app.FragmentPagerAdapter;  
import android.support.v4.view.ViewPager;  
import android.widget.Toast;  

public class PageViewActivity extends FragmentActivity implements Communicator{  
    MyPageAdapter pageAdapter;  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        try{  
        super.onCreate(savedInstanceState);  

        setContentView(R.layout.activity_page_view);          
        List<Fragment> fragments = getFragments();          
        pageAdapter = new MyPageAdapter(getSupportFragmentManager(),  fragments);          
        ViewPager pager = (ViewPager)findViewById(R.id.viewpager);  
        pager.setAdapter(pageAdapter);  

        }catch(Exception e){  
            e.printStackTrace();  
        }  

    }  

    private List<Fragment> getFragments(){  
        List<Fragment> fList = new ArrayList<Fragment>();  

        fList.add(MyFragment.newInstance("Fragment 1"));  
        fList.add(MyFragment2.newInstance("Fragment 2"));  
        //fList.add(MyFragment.newInstance("Fragment 3"));  

        return fList;  
    }  

    private class MyPageAdapter extends FragmentPagerAdapter {  

        private List<Fragment> fragments;  

        public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {  
            super(fm);  
            this.fragments = fragments;  
        }  
        @Override  
        public Fragment getItem(int position) {  
            return this.fragments.get(position);  
        }  

        @Override  
        public int getCount() {  
            return this.fragments.size();  
        }  
    }  

    @Override  
    public void respond(String data) {  
        // TODO Auto-generated method stub  
        MyFragment2 fragment = (MyFragment2) getSupportFragmentManager().findFragmentById(R.id.Fragment2);   
        fragment.print();  

    }  
}  

这是我的fragment1

view plainprint?
Note: Text content in the code blocks is automatically word-wrapped
package src.com.programmingmobile.pageviewer;  

import java.io.InputStream;  

import javax.net.ssl.ManagerFactoryParameters;  

import com.epapyrus.plugpdf.SimpleDocumentReader;  
import com.epapyrus.plugpdf.SimpleDocumentReaderListener;  
import com.epapyrus.plugpdf.SimpleReaderFactory;  
import com.epapyrus.plugpdf.core.viewer.DocumentState;  

import android.app.Activity;  
import android.content.res.AssetManager;  
import android.os.Bundle;  
import android.support.v4.app.Fragment;  
import android.support.v4.app.FragmentManager;  
import android.util.Log;  
import android.view.LayoutInflater;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.view.ViewGroup;  
import android.widget.Button;  
import android.widget.LinearLayout;  
import android.widget.TextView;  

public class MyFragment extends Fragment{  
    public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";  

    Communicator com;  

    public void onAttach(Activity a) {  
        super.onAttach(a);  
        com = (Communicator) a;  
    }  

    public static final MyFragment newInstance(String message) {  
        MyFragment f = new MyFragment();  
        Bundle bdl = new Bundle(1);  
        bdl.putString(EXTRA_MESSAGE, message);  
        f.setArguments(bdl);  
        return f;  
    }  

    @Override  
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  
            Bundle savedInstanceState) {  
        String message = getArguments().getString(EXTRA_MESSAGE);  
        View v = inflater.inflate(R.layout.myfragment_layout, container, false);  
        TextView messageTextView = (TextView) v.findViewById(R.id.textView);  
        messageTextView.setText(message);  
        // OpenPdf();  

        LinearLayout mLinearLayout = (LinearLayout) inflater.inflate(  
                R.layout.myfragment_layout, container, false);  

        // note that we're looking for a button with id="@+id/myButton" in your  
        // inflated layout  
        // Naturally, this can be any View; it doesn't have to be a button  
        Button mButton = (Button) mLinearLayout.findViewById(R.id.button1);  
        mButton.setOnClickListener(new OnClickListener() {  
            @Override  
            public void onClick(View v) {  
                com.respond("Fragment ");  
            }  
        });  

        return mLinearLayout;  
    }  



} 

这是fragment2

view plainprint?
Note: Text content in the code blocks is automatically word-wrapped
package src.com.programmingmobile.pageviewer;  

import java.io.InputStream;  

import com.epapyrus.plugpdf.SimpleDocumentReader;  
import com.epapyrus.plugpdf.SimpleDocumentReaderListener;  
import com.epapyrus.plugpdf.SimpleReaderFactory;  
import com.epapyrus.plugpdf.core.viewer.DocumentState;  

import android.content.res.AssetManager;  
import android.os.Bundle;  
import android.support.v4.app.Fragment;  
import android.util.Log;  
import android.view.LayoutInflater;  
import android.view.View;  
import android.view.ViewGroup;  
import android.widget.TextView;  
import android.widget.Toast;  

public class MyFragment2 extends Fragment {  
    public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";  

    // create a listener for receiving provide pdf loading results  
    SimpleDocumentReaderListener m_listener = new SimpleDocumentReaderListener() {  

        @Override  
        public void onLoadFinish(DocumentState.OPEN state) {  
        }  
    };  

    public static final MyFragment2 newInstance(String message) {  
        MyFragment2 f = new MyFragment2();  
        Bundle bdl = new Bundle(1);  
        bdl.putString(EXTRA_MESSAGE, message);  
        f.setArguments(bdl);  
        return f;  
    }  

    @Override  
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  
            Bundle savedInstanceState) {  
        String message = getArguments().getString(EXTRA_MESSAGE);  
        View v = inflater.inflate(R.layout.myfragment_layout2, container, false);  
        TextView messageTextView = (TextView) v.findViewById(R.id.textView);  
        messageTextView.setText(message);  
        //OpenPdf();  
        return v;  
    }  

    public void print(){  
        Toast.makeText(getActivity(), " inside Respond ", 100);  
    }  

}  

这是myfragment_layout xml文件

view plainprint?
Note: Text content in the code blocks is automatically word-wrapped
package src.com.programmingmobile.pageviewer;  

import java.io.InputStream;  

import javax.net.ssl.ManagerFactoryParameters;  

import com.epapyrus.plugpdf.SimpleDocumentReader;  
import com.epapyrus.plugpdf.SimpleDocumentReaderListener;  
import com.epapyrus.plugpdf.SimpleReaderFactory;  
import com.epapyrus.plugpdf.core.viewer.DocumentState;  

import android.app.Activity;  
import android.content.res.AssetManager;  
import android.os.Bundle;  
import android.support.v4.app.Fragment;  
import android.support.v4.app.FragmentManager;  
import android.util.Log;  
import android.view.LayoutInflater;  
import android.view.View;  
import android.view.ViewGroup;  
import android.widget.TextView;  

public class MyFragment extends Fragment {  
    public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";  

    Communicator com;  

    public void onAttach(Activity a) {  
        super.onAttach(a);  
        com = (Communicator) com;  
    }  

    public static final MyFragment newInstance(String message) {  
        MyFragment f = new MyFragment();  
        Bundle bdl = new Bundle(1);  
        bdl.putString(EXTRA_MESSAGE, message);  
        f.setArguments(bdl);  
        return f;  
    }  

    @Override  
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  
            Bundle savedInstanceState) {  
        String message = getArguments().getString(EXTRA_MESSAGE);  
        View v = inflater.inflate(R.layout.myfragment_layout, container, false);  
        TextView messageTextView = (TextView) v.findViewById(R.id.textView);  
        messageTextView.setText(message);  
        // OpenPdf();  
        return v;  
    }  

    public void onclick(View v) {  

        com.respond("Fragment ");  
    }  

}  

这是my_fragment2 xml filee

view plainprint?
Note: Text content in the code blocks is automatically word-wrapped
<?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"  
    android:id="@+id/Fragment2"  
    android:orientation="vertical" >  

    <TextView  
        android:id="@+id/textView"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_centerHorizontal="true"  
        android:layout_centerVertical="true"  
        android:textAppearance="?android:attr/textAppearanceLarge"/>  

</RelativeLayout> 

当我运行应用程序时,它给了我带按钮的第一个片段。当我按下按钮时它会给我以下错误

view plainprint?
Note: Text content in the code blocks is automatically word-wrapped
10-07 09:37:52.610: E/AndroidRuntime(10907): FATAL EXCEPTION: main  
10-07 09:37:52.610: E/AndroidRuntime(10907): java.lang.NullPointerException  
10-07 09:37:52.610: E/AndroidRuntime(10907):    at src.com.programmingmobile.pageviewer.PageViewActivity.respond(PageViewActivity.java:66)  
10-07 09:37:52.610: E/AndroidRuntime(10907):    at src.com.programmingmobile.pageviewer.MyFragment$1.onClick(MyFragment.java:63)  
10-07 09:37:52.610: E/AndroidRuntime(10907):    at android.view.View.performClick(View.java:3620)  
10-07 09:37:52.610: E/AndroidRuntime(10907):    at android.view.View$PerformClick.run(View.java:14322)  
10-07 09:37:52.610: E/AndroidRuntime(10907):    at android.os.Handler.handleCallback(Handler.java:605)  
10-07 09:37:52.610: E/AndroidRuntime(10907):    at android.os.Handler.dispatchMessage(Handler.java:92)  
10-07 09:37:52.610: E/AndroidRuntime(10907):    at android.os.Looper.loop(Looper.java:137)  
10-07 09:37:52.610: E/AndroidRuntime(10907):    at android.app.ActivityThread.main(ActivityThread.java:4507)  
10-07 09:37:52.610: E/AndroidRuntime(10907):    at java.lang.reflect.Method.invokeNative(Native Method)  
10-07 09:37:52.610: E/AndroidRuntime(10907):    at java.lang.reflect.Method.invoke(Method.java:511)  
10-07 09:37:52.610: E/AndroidRuntime(10907):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:978)  
10-07 09:37:52.610: E/AndroidRuntime(10907):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)  
10-07 09:37:52.610: E/AndroidRuntime(10907):    at dalvik.system.NativeStart.main(Native Method)  

给出空指针的行在

之下
view plainprint?
Note: Text content in the code blocks is automatically word-wrapped
MyFragment2 fragment = (MyFragment2) getSupportFragmentManager().findFragmentById(R.id.Fragment2); 

1 个答案:

答案 0 :(得分:1)

查看source for FragmentPagerAdapter,他们使用FragmentManager.findFragmentByTag(name),其中name的格式为

"android:switcher:" + viewId + ":" + id;

其中viewIdandroid:id的{​​{1}}而ViewPagerid的结果(在您的情况下可能只是位置)。

注意:这不安全,可能会从支持库的版本更改为版本。它在所有以前的版本中保持不变,但您应该在两个组件之间考虑setting up an event callback interface(技术上,在您的第一个片段,活动之间,然后是第二个片段之间)。