无法将数据从活动发送到Android Studio上的片段

时间:2019-10-10 09:59:23

标签: android android-fragments android-intent

从Fragment打开一个活动,然后将数据从该活动发送到该Fragment。但是该数据未显示在片段上

这里是扩展片段类

public final class AddEditAlarmFragment extends Fragment {
private TimePicker mTimePicker;
private EditText mLabel,mPath;
private CheckBox mMon, mTues, mWed, mThurs, mFri, mSat, mSun;
public static AddEditAlarmFragment newInstance(Alarm alarm) {
    Bundle args = new Bundle();
    args.putParcelable(AddEditAlarmActivity.ALARM_EXTRA, alarm);
    AddEditAlarmFragment fragment = new AddEditAlarmFragment();
    fragment.setArguments(args);
    return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    final View v = inflater.inflate(R.layout.fragment_add_edit_alarm, container, false);
    setHasOptionsMenu(true);
    final Alarm alarm = getAlarm();
    mTimePicker = (TimePicker) v.findViewById(R.id.edit_alarm_time_picker);
    ViewUtils.setTimePickerTime(mTimePicker, alarm.getTime());
    mLabel = (EditText) v.findViewById(R.id.edit_alarm_label);
    mLabel.setText(alarm.getLabel());
    mPath = (EditText) v.findViewById(R.id.edit_alarm_path);
 // event to go PathActivity
    mPath.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intend = new Intent(getActivity(), PathActivity.class);
            startActivity(intend);              
        }
    });

    String strtext = getArguments().getString("edttext");
    mLabel.setText(strtext);

    setDayCheckboxes(alarm);

    return v;
}

这是AppCompatActivity类的扩展

public class PathActivity extends AppCompatActivity {
private final static int READ_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE = 13;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView( R.layout.path_activity);
    int permissionCheck = ContextCompat.checkSelfPermission(this,
            Manifest.permission.READ_EXTERNAL_STORAGE);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                READ_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
    } else {
        addFileChooserFragment();
    }
}
private void addFileChooserFragment() {
    FileChooser.Builder builder = new FileChooser.Builder(FileChooser.ChooserType.FILE_CHOOSER,
            new FileChooser.ChooserListener() {
 // Send back data to mPath(Edittext) of AddEditAlarmFragment class
                @Override
                public void onSelect(String path) {
                    File selected= new File(path);
                    Bundle bundle = new Bundle();
                    bundle.putString("edttext", selected.getParent().toString());
                    AddEditAlarmFragment fragobj = new AddEditAlarmFragment();
                    fragobj.setArguments(bundle);
                    finish();
                }
            });
    try {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.file_chooser_fragment_container_framelayout, builder.build())
                .commit();
    } catch (ExternalStorageNotAvailableException e) {
        Toast.makeText(this, "There is no external storage available on this device.",
                Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }
}
}

对我来说真的是挑战。我是android studio的新手,正在寻找您的来信。谢谢

3 个答案:

答案 0 :(得分:0)

在您的片段中:

替换

startActivity(intend);  

使用

startActivityForResult(intend, 100);

onSelect()方法中的内部PathActivity使用此代码将数据发送回片段:

Intent resultIntent = new Intent();
resultIntent.putExtra("edttext", selected.getParent().toString());
setResult(Activity.RESULT_OK, resultIntent);
finish();

现在要获取片段中的数据,请在片段类中编写以下代码:

@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode == Activity.RESULT_OK){
        if(requestCode == 100){
            // here comes the data from activity
            String text = data.getStringExtra("edttext");
        }
    }
}

答案 1 :(得分:0)

有一些简单的代码块可以将数据从活动传递到片段。 步骤1:将数据从活动传递到片段,

Bundle bundle = new Bundle();
bundle.putString("params", "My String data");
// set MyFragment Arguments
MyFragment myObj = new MyFragment();
myObj.setArguments(bundle);

第2步:将数据接收到片段,

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString("params");
    }
}

sourceLink

答案 2 :(得分:0)

请使用以下代码段,并注意不要触发getActivity().startActivityForResult()的其他onActivityResult()活动

AddEditAlarmFragment.java

public final class AddEditAlarmFragment extends Fragment {
    private TimePicker mTimePicker;
    private EditText mLabel,mPath;
    private CheckBox mMon, mTues, mWed, mThurs, mFri, mSat, mSun;
    public static AddEditAlarmFragment newInstance(Alarm alarm) {
        Bundle args = new Bundle();
        args.putParcelable(AddEditAlarmActivity.ALARM_EXTRA, alarm);
        AddEditAlarmFragment fragment = new AddEditAlarmFragment();
        fragment.setArguments(args);
        return fragment;
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View v = inflater.inflate(R.layout.fragment_add_edit_alarm, container, false);
        setHasOptionsMenu(true);
        final Alarm alarm = getAlarm();
        mTimePicker = (TimePicker) v.findViewById(R.id.edit_alarm_time_picker);
        ViewUtils.setTimePickerTime(mTimePicker, alarm.getTime());
        mLabel = (EditText) v.findViewById(R.id.edit_alarm_label);
        mLabel.setText(alarm.getLabel());
        mPath = (EditText) v.findViewById(R.id.edit_alarm_path);
     // event to go PathActivity
        mPath.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intend = new Intent(getActivity(), PathActivity.class);
                startActivityForResult(intend,100);              
            }
        });

        String strtext = getArguments().getString("edttext");
        mLabel.setText(strtext);

        setDayCheckboxes(alarm);

        return v;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

        if(resultCode == Activity.RESULT_OK){
            if(requestCode == 100){
                // here comes the data from activity
                String path = data.getStringExtra("path");
                // use path
                return;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}

PathActivity.java

public class PathActivity extends AppCompatActivity {
    private final static int READ_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE = 13;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView( R.layout.path_activity);
        int permissionCheck = ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE);
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    READ_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
        } else {
            addFileChooserFragment();
        }
    }
    private void addFileChooserFragment() {
        FileChooser.Builder builder = new FileChooser.Builder(FileChooser.ChooserType.FILE_CHOOSER,
                new FileChooser.ChooserListener() {
     // Send back data to mPath(Edittext) of AddEditAlarmFragment class
                    @Override
                    public void onSelect(String path) {
                        Intent resultIntent = new Intent();
                        resultIntent.putExtra("edttext", selected.getParent().toString());
                        setResult(Activity.RESULT_OK, resultIntent);
                        finish();
                    }
                });
        try {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.file_chooser_fragment_container_framelayout, builder.build())
                    .commit();
        } catch (ExternalStorageNotAvailableException e) {
            Toast.makeText(this, "There is no external storage available on this device.",
                    Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
}