将数据从Activity发送到Class extent Fragment

时间:2015-10-21 07:35:23

标签: java android android-fragments

我在Activity中使用ViewPager

编写代码
//mycode
public class ViewPagerActivity extends FragmentActivity implements
    ActionBar.TabListener {
    private ViewPager viewPager;
    private TabsPagerAdapterHehe mAdapter1;
    private ActionBar actionBar;
    // Tab titles
    private String[] tabs = {"Feed", "Search", "Status"};
    Toast mToast = null;
    // set ActionBar;
    private LinearLayout layout_btn_search, layout_image_view, layout_edt_search, layout_btn_logout;
    private EditText edt_search_1;
    String key_word;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_pager);

        // check internet cho app
        cd = new ConnectionDetector(getApplicationContext());
        isInternetPresent = cd.checkMobileInternetConn();

        // isOnline
        boolean b = isOnline();
        if (isOnline()) {
            setActionBar();
            // Initilization
            viewPager = (ViewPager) findViewById(R.id.pager);
            actionBar = getActionBar();
            mAdapter1 = new TabsPagerAdapterHehe(getSupportFragmentManager());
            viewPager.setAdapter(mAdapter1);
            actionBar.setHomeButtonEnabled(false);
         actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

            // Adding Tabs
            for (String tab_name : tabs) {
                actionBar.addTab(actionBar.newTab().setText(tab_name)
                        .setTabListener(ViewPagerActivity.this));
            }

            /**
             * on swiping the viewpager make respective tab selected
             * */
            viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                    // on changing the page
                    // make respected tab selected
                    actionBar.setSelectedNavigationItem(position);
                }
            });
        } else {
            Toast.makeText(ViewPagerActivity.this, "ネットワーク環境がありません", Toast.LENGTH_SHORT).show();
        }
    }

    // show dialog check Internet cho app
    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        hideSoftKeyboard();
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        layout_edt_search.setVisibility(View.GONE);
        layout_btn_search.setVisibility(View.VISIBLE);
        edt_search_1.setText("");
        hideSoftKeyboard();
        // on tab selected
        // show respected fragment view
        boolean b = isOnline();
        if (isOnline()) {
            viewPager.setCurrentItem(tab.getPosition());
        } else {
            viewPager.setCurrentItem(tab.getPosition());
            Toast.makeText(ViewPagerActivity.this, "ネットワーク環境がありません", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        hideSoftKeyboard();
    }
    // set ActionBar
    private void setActionBar() {
        actionBar = getActionBar();
        actionBar.setDisplayShowHomeEnabled(false);
        actionBar.setDisplayShowTitleEnabled(false);
        LayoutInflater inflater = LayoutInflater.from(this);
        View mView = inflater.inflate(R.layout.custom_actionbar, null);


        edt_search_1.setOnEditorActionListener(new EditText.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // hide keyboard
                          Bundle b = new Bundle();
                            key_word = edt_search_1.getText().toString();
                            b.putString("keyword", keyword);
                            FragmentSearch fgsearch = new FragmentSearch();
                            fgsearch.setArguments(b);
                            Log.e("KEYWORD", key_word);
                            Toast.makeText(getApplication(), "HEHE", Toast.LENGTH_SHORT).show();



                    }
                    return true;
                }
                return false;
            }
        });
            }

        });
        actionBar.setCustomView(mView);
        actionBar.setDisplayShowCustomEnabled(true);
    }

    /// do Search
    private void doSeachNew() {



    }


    private class TabsPagerAdapterHehe extends FragmentPagerAdapter {

        public TabsPagerAdapterHehe(FragmentManager fm) {
            super(fm);
        }


        @Override
        public Fragment getItem(int i) {

            switch (i) {
                case 1:
                    return new FragmentSearch();
                case 2:
                    return new New_Status();
                default:
                    return new HomeTimelineFragment();
                //return new FragmentHomeTimeLine();
            }
        }

        @Override
        public int getCount() {
            return 3;
        }
    }

    public void hideSoftKeyboard() {
        if (getCurrentFocus() != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //  intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    public static class CheckNetwork {


        static String TAG = CheckNetwork.class.getSimpleName();


        public static boolean isInternetAvailable(Context context) {
            NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
                    context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

            if (info == null) {
                Log.d(TAG, "no internet connection");
                return false;
            } else {
                if (info.isConnected()) {
                    Log.d(TAG, " internet connection available...");
                    return true;
                } else {
                    Log.d(TAG, " internet connection");
                    return true;
                }

            }
        }
    }

}

和我的片段

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_search_list, container, false);
    Bundle bundle = this.getArguments();
    keyword = bundle.getString("keyword");
    Log.e("KeyWord", keyword);
    return view;
}

这是我的错误

10-21 14:11:26.639    7278-7278/vn.seesaa.nguyentrunghieu.logintwitter E/SetSizeByPercent﹕ java.lang.NullPointerException
10-21 14:11:26.709    7278-7278/vn.seesaa.nguyentrunghieu.logintwitter E/client﹕ vn.seesaa.nguyentrunghieu.client.TwitterClient@44a626e0
10-21 14:11:26.849    7278-7278/vn.seesaa.nguyentrunghieu.logintwitter E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: vn.seesaa.nguyentrunghieu.logintwitter, PID: 7278
java.lang.NullPointerException
        at vn.seesaa.nguyentrunghieu.viewpager.FragmentSearch.onCreateView(FragmentSearch.java:73)
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1026)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1207)
        at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1572)
        at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:545)
        at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
        at android.support.v4.view.ViewPager.populate(ViewPager.java:1106)
        at android.support.v4.view.ViewPager.populate(ViewPager.java:952)
        at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1474)
        at android.view.View.measure(View.java:16628)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
        at android.view.View.measure(View.java:16628)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
        at android.view.View.measure(View.java:16628)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
        at android.view.View.measure(View.java:16628)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
        at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327)
        at android.view.View.measure(View.java:16628)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
        at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2298)
        at android.view.View.measure(View.java:16628)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1920)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1117)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1299)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5692)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
        at android.view.Choreographer.doCallbacks(Choreographer.java:574)
        at android.view.Choreographer.doFrame(Choreographer.java:544)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:212)
        at android.app.ActivityThread.main(ActivityThread.java:5151)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
        at dalvik.system.NativeStart.main(Native Method)

请!帮我修复bug !! 非常感谢你!

2 个答案:

答案 0 :(得分:0)

getItem()方法中,您将返回片段的新实例。

return new FragmentSearch();

在这种情况下,没有为片段设置参数。因此调用getArguments()将返回null。因此,nullpointerexception。

在那里做一个空检查。

更新:如果您只是希望异常消失,则以下是修复。如果您关心传递的参数,那么您需要setArguments()FragmentSearch方法中创建getItem()

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_search_list, container, false);
    Bundle bundle = this.getArguments();
    if(bundle != null){
       keyword = bundle.getString("keyword");
       Log.e("KeyWord", keyword);
    }
    return view;
}

最佳实践: 始终只使用onCreateView()来扩充布局并将其返回。所有其他代码应放在onActivityCreated()回调中。

答案 1 :(得分:0)

您可能应该更改创建Fragment实例的方案吗?例如,在Android Studio中,如果要创建新的BlankFragment而不使用任何回调但使用片段工厂方法,则会生成以下内容:

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BlankFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BlankFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;


    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment BlankFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static BlankFragment newInstance(String param1, String param2) {
        BlankFragment fragment = new BlankFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public BlankFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_blank, container, false);
    }
}

在您的情况下,您的ARG_PARAM1是"关键字"。一切都是你的需要 - 使用工厂方法创建片段,如下所示:

BlankFragment fragment = BlankFragment.newInstance("hello")

希望这会对你有所帮助。