0

I have a Fragment and an Activty, the activity has 3 editText and a Image. You can upload the image from your device. But know i'm trying to connect both fragment and pass all the information from Activity B to Fragment A.

Fragment has a button for edit the profile, 3 TextView and an ImageView, if you click in the button, you go to Activity and in there you have the 3 edit Text (name, email, and description) and you have a button for upload an image from your device. And a last button for save the changes.

I want to save the changes with the save button and give the information of the edittext and the image to the Fragment.

I'm doing in JAVA.

Fragment File

  public class NotificationFragment extends Fragment {
    private static String name;
    private static String mail2;
    private static String des;
    Button btnclose;
    Button btnedit;
    Button btnDisponibles;
    Button btnFinalizadas;
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    public NotificationFragment() {
        // Required empty public constructor
    }
    /**
     * 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 HomeFragment.
     */
    String name2;
    String e_mail;
    String description;
    // TODO: Rename and change types and number of parameters
    public static NotificationFragment newInstance(String param1, String param2) {
        NotificationFragment fragment = new NotificationFragment();
        Bundle args = new Bundle();
        args.putString(name, param1);
        args.putString(mail2, param2);
        args.putString(des,"");
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            name2 = getArguments().getString("name");
            e_mail = getArguments().getString("email");
            description = getArguments().getString("descripcion");
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_notification, container, false);
        TextView nombre, email, descripcion;
        nombre = (TextView) view.findViewById(R.id.txtNombre);
        email = (TextView) view.findViewById(R.id.txtemail);
        descripcion = (TextView) view.findViewById(R.id.txtdescripcion);
        nombre.setText(name);
        email.setText(e_mail);
        descripcion.setText(description);

        btnedit = (Button) view.findViewById(R.id.btneditar);
        btnedit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editar();
            }
        });    
        return view;
    }

The Activity file

public class editarperfil extends AppCompatActivity {
    ImageView imagen;
    Button btnchange;
    Button btnout;
    EditText editNombre;
    EditText editEmail;
    EditText ediDescripcion;

    String name;
    String e_mail;
    String description;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editarperfil);
        imagen = (ImageView) findViewById(R.id.imagenId);
        btnchange = (Button) findViewById(R.id.btnImagen);
        btnchange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cargarimagen();
            }
        });
        btnout = (Button) findViewById(R.id.btnGuardar);
        btnout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                salir();
            }
        });
    }


    private void cargarimagen(){
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/");
        startActivityForResult(intent.createChooser(intent, "Seleccione la aplicación"), 10);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Uri path=data.getData();
        imagen.setImageURI(path);
    }
    private void salir()
    {
        Bundle bundle = new Bundle();
        bundle.putString("name", editNombre.getText().toString());
        bundle.putString("email", editEmail.getText().toString());
        bundle.putString("descripcion", ediDescripcion.getText().toString()); // Put anything what you want

        NotificationFragment fragment2 = new NotificationFragment();
        fragment2.setArguments(bundle);

    }

This doesn't work...

PD: How can I do the same if there are two Fragments?

I have this error code

05/13 08:41:27: Launching 'app' on Pixel_3a_API_30_x86.
Install successfully finished in 613 ms.
$ adb shell am start -n "com.example.myapplication29/com.example.myapplication29.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 25724 on device 'Pixel_3a_API_30_x86 [emulator-5554]'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/myapplication2: Not late-enabling -Xcheck:jni (already on)
I/myapplication2: Unquickening 12 vdex files!
W/myapplication2: Unexpected CPU variant for X86 using defaults: x86
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
W/myapplication2: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/myapplication2: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
D/HostConnection: HostConnection::get() New Host Connection established 0xefcb0590, tid 25802
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_async_frame_commands ANDROID_EMU_gles_max_version_2 
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/EGL_emulation: eglCreateContext: 0xefcaff70: maj 2 min 0 rcv 2
D/EGL_emulation: eglMakeCurrent: 0xefcaff70: ver 2 0 (tinfo 0xefff5970) (first time)
I/Gralloc4: mapper 4.x is not supported
D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0xefcb2270, tid 25802
D/goldfish-address-space: allocate: Ask for block of size 0x100
D/goldfish-address-space: allocate: ioctl allocate returned offset 0x3fd40d000 size 0x2000
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_async_frame_commands ANDROID_EMU_gles_max_version_2 
I/AssistStructure: Flattened final assist data: 2188 bytes, containing 1 windows, 12 views
W/IInputConnectionWrapper: beginBatchEdit on inactive InputConnection
    endBatchEdit on inactive InputConnection
    setComposingRegion on inactive InputConnection
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication29, PID: 25724
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
        at com.example.myapplication29.editarperfil.salir(editarperfil.java:76)
        at com.example.myapplication29.editarperfil.access$100(editarperfil.java:28)
        at com.example.myapplication29.editarperfil$2.onClick(editarperfil.java:55)
        at android.view.View.performClick(View.java:7448)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
        at android.view.View.performClickInternal(View.java:7425)
        at android.view.View.access$3600(View.java:810)
        at android.view.View$PerformClick.run(View.java:28305)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

Thanks

2 Answers2

0

Update

use EventBus to transfer data:

1 implementation 'org.greenrobot:eventbus:3.2.0'

2 new a class MessageEvent:

public class MessageEvent {

    private Bundle bundle;

    public Bundle getBundle() {
        return bundle;
    }

    public MessageEvent setBundle(Bundle bundle) {
        this.bundle = bundle;
        return this;
    }
}

3 in your Activity method:

private void salir()
{
    Bundle bundle = new Bundle();
    bundle.putString("name", editNombre.getText().toString());
    bundle.putString("email", editEmail.getText().toString());
    bundle.putString("descripcion", ediDescripcion.getText().toString()); // Put anything what you want

    NotificationFragment fragment2 = new NotificationFragment();
    EventBus.getDefault().postSticky(new MessageEvent().setBundle(bundle));// post data 
    loadFragment(fragment2);
}

public void loadFragment(Fragment fragment  ) {
    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.replace(R.id.navigation_notifications, fragment);
    transaction.commitAllowingStateLoss();
}

4 in your NotificationFragment add methods:

public class NotificationFragment extends Fragment {
 
    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void onMessageEvent(MessageEvent event) {
        Bundle bundle = event.getBundle();
        if (bundle != null) {
            name2 = bundle.getString("name");
            e_mail = bundle.getString("email");
            description = bundle.getString("descripcion");
        }
        Log.d(TAG, "onMessageEvent: " + bundle);
    };

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }
}   

One EventBus post can be received by multi @Subscribe .


Change code of your activity:

private void salir()
{
    Bundle bundle = new Bundle();
    bundle.putString("name", editNombre.getText().toString());
    bundle.putString("email", editEmail.getText().toString());
    bundle.putString("descripcion", ediDescripcion.getText().toString()); // Put anything what you want

    NotificationFragment fragment2 = new NotificationFragment();
    fragment2.setArguments(bundle);
    loadFragment(fragment2);
}

public void loadFragment(Fragment fragment  ) {
    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.replace(R.id.navigation_notifications, fragment);
    transaction.commitAllowingStateLoss();
}
zhangxaochen
  • 32,744
  • 15
  • 77
  • 108
  • But here `Bundle bundle = new Bundle(); bundle.putString("message", "From Activity"); ` I can put this? –  May 11 '21 at 09:35
  • `Bundle bundle = new Bundle(); bundle.putString("name", editNombre.getText().toString());` –  May 11 '21 at 09:36
  • I update the code but it's still not working –  May 11 '21 at 10:05
  • It should be 'public View onCreateView(LayoutInflater inflat getArguments() ' . and 'getArgument' should inside 'onCreateView" – zhangxaochen May 11 '21 at 10:52
  • But i have my code like yours and it doesn't work look at the top are the same code. I not following you ar the moment can you explain me in other way please? –  May 11 '21 at 11:10
  • Hi @AlexDeveloper99,i updated my answer,pls kindly refer. – zhangxaochen May 12 '21 at 01:56
  • Hi @shirley this code doesn't work for me, i'm very surprised. The text doesn't appear and i don't know how to do it –  May 12 '21 at 06:43
  • Hi @AlexDeveloper99,`eventbus` and `setArguments` are two different method,[here](https://i.stack.imgur.com/jgUAJ.png) is `setArguments` ,the original method. – zhangxaochen May 12 '21 at 07:15
  • I see but where i put the `eventbus` ? Because you say in the activity, and in there I have the `setArgument` method.... –  May 12 '21 at 07:25
  • And in the step 4 `4 in your NotificationFragment add methods:` with that I print in the TextViews of that fragment? –  May 12 '21 at 07:32
  • That's two different methods. It can be tested independently or at the same time.```NotificationFragment fragment2 = new NotificationFragment(); fragment2.setArguments(bundle); EventBus.getDefault().postSticky(new MessageEvent().setBundle(bundle));// post data loadFragment(fragment2);```This allows you to use tests at the same time. – zhangxaochen May 12 '21 at 07:37
  • I have an error –  May 13 '21 at 06:42
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/232325/discussion-between-alexdeveloper99-and-shirley). –  May 13 '21 at 06:43
-1

You can use Bundle.

For Send Value

Bundle bundle = new Bundle();
bundle.putString("Key", "value");

fragmentObject.setArgument(bundle);
--Start or replace fragment---

For get values

String value = getArgument().getString("key");

you didnt write code for open or replace fragment. Without commit of framgnet your fragment class will enable to execute. and get value

  • what is the code for start or replace fragment? Because I don't know that im very new in this world –  May 11 '21 at 10:42
  • use this link. this will give you brief information about fragment in android https://www.javatpoint.com/android-fragments – Milan Chauhan May 11 '21 at 10:51
  • Thank but my fragment has a OnCreateView, and Oncreate what are you telling me at the moment? Sorry but i'm not following you... –  May 11 '21 at 11:11
  • In your FromFragment: Bundle args = new Bundle(); args.putSerializable(TAG_MY_CLASS, myClass); Fragment toFragment = new ToFragment(); toFragment.setArguments(args); getFragmentManager() .beginTransaction() .replace(R.id.body, toFragment, TAG_TO_FRAGMENT) .addToBackStack(TAG_TO_FRAGMENT).commit(); in your ToFragment: @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Bundle args = getArguments(); – Milan Chauhan May 11 '21 at 11:27
  • Hi @Milan this isn't work for me I have an Activity –  May 12 '21 at 07:22