user3818576
user3818576

Reputation: 3401

How to pass value in fragment?

I'm new in android. I'm trying to follow the tutorial from these videos link. I know there are a lot of tutorial and the same issue of mine here, but I want to know the exact reason why my app stop when I click the submit button. Sorry I'm not yet familiar with their functions in android studio and how the system work. I try to create 2 fragment, the top and the bottom fragment. In top fragment there is a submit form. When I click the submit button. The value will show to the bottom fragment. It's like passing value to another fragment. I create a fragment class name TopSectionFragment

package com.example.aldrin.fragmenttutorial;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.app.Activity;
import android.widget.Button;
import android.widget.EditText;

public class TopSectionFragment extends Fragment{
    @Nullable
    private static EditText topTextInput;
    private static EditText bottomTextInput;

    TopSectionListener activityCommander;

    public interface TopSectionListener{
        public void createMem(String top, String bottom);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        Activity activity = context instanceof Activity ? (Activity) context : null;

        try{
            activityCommander = (TopSectionListener) activity;
        }catch (ClassCastException e){
            throw new ClassCastException(activity.toString());
        }
    }



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

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

        topTextInput = (EditText)view.findViewById(R.id.topText);
        bottomTextInput = (EditText)view.findViewById(R.id.bottomText);

        final Button button = (Button) view.findViewById(R.id.submitButton);

        button.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        buttonClick(v);
                    }
                }
        );

        return view;
    }

    public void buttonClick(View v){
        activityCommander.createMem(topTextInput.getText().toString(),bottomTextInput.getText().toString());
    }
}

and I create another fragment for bottom. I name it BottomPictureFragment

package com.example.aldrin.fragmenttutorial;

import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class BottomPictureFragment extends Fragment {

    private static TextView t1;
    private static TextView t2;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

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

        t1 = (TextView) view.findViewById(R.id.topText);
        t2 = (TextView) view.findViewById(R.id.bottomText);
        return view;
    }

    public void setMemeText(String top, String bottom){
        t1.setText(top);
        t2.setText(bottom);
    }
}

I use Kitkat for my project. When I follow the video tutorial, the onAttach(Activity activity) is already deprecated. I try the use onAttach(Context context) but same issue. When I run it to my asus phone. It stop the process when I submit. Here are the codes of my MainActity

package com.example.aldrin.fragmenttutorial;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;


public class MainActivity extends AppCompatActivity implements TopSectionFragment.TopSectionListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void createMem(String top, String bottom) {
        BottomPictureFragment bottomFragment = (BottomPictureFragment) getSupportFragmentManager().findFragmentById(R.id.fragment2);
        bottomFragment.setMemeText(top,bottom);
    }

}

But if you provide another solution for passing value to other fragment. It will be more appreciated. It will help me to study more. Hoping for your help. I'm just copying the code from the video.

I got these errors

10-27 13:42:49.436 6176-6176/com.example.users.fragmenttutorial W/IInputConnectionWrapper: beginBatchEdit on inactive InputConnection
10-27 13:42:49.436 6176-6176/com.example.users.fragmenttutorial W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
10-27 13:42:51.636 6176-6176/com.example.users.fragmenttutorial D/AndroidRuntime: Shutting down VM
10-27 13:42:51.636 6176-6176/com.example.users.fragmenttutorial W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x430f2140)
10-27 13:42:51.636 6176-6176/com.example.users.fragmenttutorial E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                   Process: com.example.users.fragmenttutorial, PID: 6176
                                                                                   java.lang.NullPointerException
                                                                                       at com.example.users.fragmenttutorial.BottomPictureFragment.setMemeText(BottomPictureFragment.java:28)
                                                                                       at com.example.users.fragmenttutorial.MainActivity.createMem(MainActivity.java:18)
                                                                                       at com.example.users.fragmenttutorial.TopSectionFragment.buttonClick(TopSectionFragment.java:64)
                                                                                       at com.example.users.fragmenttutorial.TopSectionFragment$1.onClick(TopSectionFragment.java:55)
                                                                                       at android.view.View.performClick(View.java:4478)
                                                                                       at android.view.View$PerformClick.run(View.java:18698)
                                                                                       at android.os.Handler.handleCallback(Handler.java:733)
                                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                       at android.os.Looper.loop(Looper.java:149)
                                                                                       at android.app.ActivityThread.main(ActivityThread.java:5257)
                                                                                       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:793)
                                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
                                                                                       at dalvik.system.NativeStart.main(Native Method)

Upvotes: 1

Views: 1464

Answers (3)

Amit Vaishnava
Amit Vaishnava

Reputation: 306

The proper way to pass the value to fragment from activity or from fragment itself is shown below:

Case 1: Activity launch FragmentA with value as:

getFragmentManager().beginTransaction().add(R.id.container, new FragmentA("your value")).commit();

So on FragmentA use this:

String mString;

public static FragmentA newInstance(String str) {

    Bundle bundle = new Bundle();
    bundle.putString("str", str);
    FragmentA fragment = new FragmentA();
    fragment.setArguments(bundle);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mString = getArguments().getString("str");
    }
}

Now you can use mString variable in FragmentA class.

Case 2: FragmentA calls FragmentB with value, you have to create an interface in FragmentA and implement this listener in your activity like:

FragmentA class create 'FragmentAListener'

public interface FragmentAListener {

    void onFragmentBClick();
}

Initialize this:

FragmentAListener mFragmentBLaunch;

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    mFragmentBLaunch = (FragmentAListener) context;
}

Then onclick call this:

mFragmentBLaunch.onFragmentBClick();

After that implement this listener FragmentAListener in your Activity and launch FragmentB.

Good luck, i hope this might help you.

Upvotes: 3

Umair
Umair

Reputation: 6426

The simple way to pass data from one fragment to another is like this: Use Bundle to send String/int or whatever you want to send:

TopSectionFragment firstFragment = new TopSectionFragment();
Bundle args = new Bundle();
args.putString("YourKey", "YourValue");
firstFragment.setArguments(args);

//Inflate the fragment
getFragmentManager().beginTransaction().add(R.id.container, firstFragment).commit();

and in onCreateView of the BottomPictureFragment:

//Retrieve the value
String value = getArguments().getString("YourKey");

You can find more help in these links about how to communicate or send data from one fragment to another: How to pass values between Fragments

How to send data from one Fragment to another Fragment? (Taken answer from here)

How to pass a value from one Fragment to another in Android?

hope it helps cheers.

Upvotes: 5

Fesco
Fesco

Reputation: 147

From Activity you can send data to Fragment with intent as:

Bundle bundle=new Bundle();
bundle.putString("message", "From Activity");
//set Fragmentclass Arguments
Fragmentclass fragobj=new Fragmentclass();
fragobj.setArguments(bundle);

To receive in fragment in Fragment onCreateView method:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
      String strtext=getArguments().getString("message");

return inflater.inflate(R.layout.fragment, container, false);
}

Upvotes: 1

Related Questions