How can I use set fragment inside my class which extends the Fragment class?

大兔子大兔子 提交于 2019-12-13 05:42:39

问题


Null returned from ((MessageTextFragment)fragment).setActionButtonStateListener(bAction);

Here is the SetupMessageFragment.java

package com.mayday.md.fragment;

import com.mayday.md.MainActivity;
import com.mayday.md.R;
import com.mayday.md.WizardActivity;
import com.mayday.md.adapter.PageItemAdapter;
import com.mayday.md.common.AppConstants;
import com.mayday.md.common.AppUtil;
import com.mayday.md.common.ApplicationSettings;
import com.mayday.md.common.MyTagHandler;
import com.mayday.md.data.PBDatabase;
import com.mayday.md.model.Page;
import com.mayday.md.model.PageItem;
import com.mayday.md.model.SMSSettings;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


/**
 * Created by aoe on 12/12/13.
 */
public class SetupMessageFragment extends Fragment {
    private EditText smsEditText;

    private static final String PAGE_ID = "page_id";
    private static final String PARENT_ACTIVITY = "parent_activity";
    private Activity activity;

    DisplayMetrics metrics;

    TextView tvTitle, tvContent, tvIntro, tvWarning;
    Button bAction;
    ListView lvItems;
    LinearLayout llWarning;

    Page currentPage;
    PageItemAdapter pageItemAdapter;

    public static SetupMessageFragment newInstance(String pageId, int parentActivity) {
        SetupMessageFragment f = new SetupMessageFragment();
        Bundle args = new Bundle();
        args.putString(PAGE_ID, pageId);
        args.putInt(PARENT_ACTIVITY, parentActivity);
        f.setArguments(args);
        return(f);
    }


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

        View view = inflater.inflate(R.layout.fragment_type_interactive_message, container, false);

        tvTitle = (TextView) view.findViewById(R.id.fragment_title);
        tvIntro = (TextView) view.findViewById(R.id.fragment_intro);
        tvContent = (TextView) view.findViewById(R.id.fragment_contents);

        bAction = (Button) view.findViewById(R.id.fragment_action);
        bAction.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e(">>>>", "action button pressed");
                String msg =  getSMSSettingsFromView();

                SMSSettings.saveMessage(activity, msg);
                displaySettings(msg);

                String pageId = currentPage.getAction().get(0).getLink();
                int parentActivity = getArguments().getInt(PARENT_ACTIVITY);
                Intent i;

                if(parentActivity == AppConstants.FROM_WIZARD_ACTIVITY){
                    i = new Intent(activity, WizardActivity.class);
                } else{
//                  AppUtil.showToast("Message saved.", 1000, activity);
                    String confirmation = (currentPage.getAction().get(0).getConfirmation() == null)
                            ? AppConstants.DEFAULT_CONFIRMATION_MESSAGE
                            : currentPage.getAction().get(0).getConfirmation();
                    Toast.makeText(activity, confirmation, Toast.LENGTH_SHORT).show();

                    i = new Intent(activity, MainActivity.class);
                }
                i.putExtra("page_id", pageId);
                startActivity(i);

                if(parentActivity == AppConstants.FROM_MAIN_ACTIVITY){
                    activity.finish();
                }
            }
        });


        lvItems = (ListView) view.findViewById(R.id.fragment_item_list);

        llWarning = (LinearLayout) view.findViewById(R.id.ll_fragment_warning);
        tvWarning  = (TextView) view.findViewById(R.id.fragment_warning);

        lvItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                PageItem selectedItem = (PageItem) parent.getItemAtPosition(position);

                String pageId = selectedItem.getLink();
                int parentActivity = getArguments().getInt(PARENT_ACTIVITY);
                Intent i;

                if(parentActivity == AppConstants.FROM_WIZARD_ACTIVITY){
                    i = new Intent(activity, WizardActivity.class);
                } else{
                    i = new Intent(activity, MainActivity.class);
                }
                i.putExtra("page_id", pageId);
                startActivity(i);

            }
        });

        return view;
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        activity = getActivity();
        if (activity != null) {
            metrics = new DisplayMetrics();
            activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);

            Fragment fragment = getFragmentManager().findFragmentById(R.id.sms_message);
            ((MessageTextFragment)fragment).setActionButtonStateListener(bAction);
            smsEditText = (EditText) fragment.getView().findViewById(R.id.message_edit_text);

            String currentMsg = SMSSettings.retrieveMessage(activity);
            if(currentMsg != null) {
                displaySettings(currentMsg);
            }
            bAction.setEnabled(!smsEditText.getText().toString().trim().equals(""));

            String pageId = getArguments().getString(PAGE_ID);
            String selectedLang = ApplicationSettings.getSelectedLanguage(activity);

            PBDatabase dbInstance = new PBDatabase(activity);
            dbInstance.open();
            currentPage = dbInstance.retrievePage(pageId, selectedLang);
            dbInstance.close();

            tvTitle.setText(currentPage.getTitle());

            if(currentPage.getContent() == null)
                tvContent.setVisibility(View.GONE);
            else
                tvContent.setText(Html.fromHtml(currentPage.getContent(), null, new MyTagHandler()));

            if(currentPage.getIntroduction() == null)
                tvIntro.setVisibility(View.GONE);
            else
                tvIntro.setText(currentPage.getIntroduction());

            if(currentPage.getWarning() == null)
                llWarning.setVisibility(View.GONE);
            else
                tvWarning.setText(currentPage.getWarning());

            bAction.setText(currentPage.getAction().get(0).getTitle());

            pageItemAdapter = new PageItemAdapter(activity, null);
            lvItems.setAdapter(pageItemAdapter);
            pageItemAdapter.setData(currentPage.getItems());

            AppUtil.updateImages(true, currentPage.getContent(), activity, metrics, tvContent, AppConstants.IMAGE_INLINE);

        }
    }


    private void displaySettings(String msg) {
        smsEditText.setText(msg);
    }


    private String getSMSSettingsFromView() {
        String message = smsEditText.getText().toString().trim();
        return message;
    }
}

The error logs.

02-14 00:56:35.054  26659-26659/com.mayday.md E/SimpleFragment.onPause﹕ settings
02-14 00:56:35.054  26659-26659/com.mayday.md E/MainActivity.onPause﹕ .
02-14 00:56:35.054  26659-26659/com.mayday.md E/MainActivity.onPause﹕ flagRiseFromPause = true
02-14 00:56:35.084  26659-26659/com.mayday.md D/AbsListView﹕ unregisterIRListener() is called
02-14 00:56:35.084  26659-26659/com.mayday.md D/AbsListView﹕ unregisterIRListener() is called
02-14 00:56:35.094  26659-26659/com.mayday.md E/>>>>>﹕ Registering finish activity in oncreate -> BaseFragmentActivity
02-14 00:56:35.114  26659-26659/com.mayday.md E/MainActivity.onCreate﹕ pageId = settings-message
02-14 00:56:35.164  26659-26659/com.mayday.md D/skia﹕ GFXPNG PNG bitmap created width:33 height:72 bitmap id is 282
02-14 00:56:35.164  26659-26659/com.mayday.md D/skia﹕ GFXPNG PNG bitmap created width:33 height:72 bitmap id is 283
02-14 00:56:35.164  26659-26659/com.mayday.md D/skia﹕ GFXPNG PNG bitmap created width:33 height:72 bitmap id is 284
02-14 00:56:35.164  26659-26659/com.mayday.md D/skia﹕ GFXPNG PNG bitmap created width:33 height:72 bitmap id is 285
02-14 00:56:35.204  26659-26659/com.mayday.md D/AbsListView﹕ Get MotionRecognitionManager
02-14 00:56:35.204  26659-26659/com.mayday.md D/AndroidRuntime﹕ Shutting down VM
02-14 00:56:35.204  26659-26659/com.mayday.md W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41765da0)
02-14 00:56:35.214  26659-26659/com.mayday.md E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.mayday.md, PID: 26659
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mayday.md/com.mayday.md.MainActivity}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2395)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2453)
            at android.app.ActivityThread.access$900(ActivityThread.java:173)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5579)
            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:1268)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at com.mayday.md.fragment.SetupMessageFragment.onActivityCreated(SetupMessageFragment.java:149)
            at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1794)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:967)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
            at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:548)
            at com.mayday.md.MainActivity.onStart(MainActivity.java:219)
            at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1177)
            at android.app.Activity.performStart(Activity.java:5461)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2368)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2453)
            at android.app.ActivityThread.access$900(ActivityThread.java:173)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5579)
            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:1268)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
            at dalvik.system.NativeStart.main(Native Method)

回答1:


If ((MessageTextFragment)fragment).setActionButtonStateListener(bAction); is line 219, then you need to make sure that MessageTextFragment was added by the FragmentManager with the id of sms_message and was done before you called it.

You need to change:

Fragment fragment = getFragmentManager().findFragmentById(R.id.sms_message);
((MessageTextFragment)fragment).setActionButtonStateListener(bAction);
smsEditText = (EditText) fragment.getView().findViewById(R.id.message_edit_text);

to something like:

Fragment fragment = new MessageTextFragment(); 
FragmentTransaction transaction = getChildFragmentManager().beginTransaction(); 
transaction.add(R.id.sms_message, fragment).commit(); 

Fragment fragment2 = getChildFragmentManager().findFragmentById(R.id.sms_message); 
((MessageTextFragment) fragment2).setActionButtonStateListener(bAction); 
smsEditText = (EditText) fragment2.getView().findViewById(R.id.message_edit_text);


来源:https://stackoverflow.com/questions/28512939/how-can-i-use-set-fragment-inside-my-class-which-extends-the-fragment-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!