Nabeel Ahmed
Nabeel Ahmed

Reputation: 242

Send data from activity to different fragments

I have a MainActivity in which I have a spinner which have three items. Those items are used to inflate three different fragments in MainActivity framelayout.

Now I've another FilterActivity which I get by clicking on menuItem in MainActivity. So my FilterActivity is attached with MainActivity.

In FilterActivity I've three radio buttons. When I check any of the radio button and click on OK button, it get me to the MainActivity.

What I want is to get the value from FilterActivity to my all three fragments. As if I check any radio button in FilterActivty, its related data should be available in all three fragments.

I've tried to do it with Bundle but its not working.

In my FilterActivity, and ReportType is my fragment where I want to send this data.

else if (item.getItemId() == R.id.btn_check_filter)
        {
            Bundle bundle = new Bundle();
            bundle.putString("Expense", EXPENSE_TYPE);
            ReportType reportType = new ReportType();
            reportType.setArguments(bundle);

            finish();
        }

And in the same fragment, I tried to get that value by doing this.

Bundle bundle = this.getArguments();
        String expenseType1 = bundle.getString("Expense");

But this gives me NullPointerException, which mean the bundle have no value.

Here is my FilterActivity

    public class Filter extends AppCompatActivity implements View.OnClickListener {


    private LinearLayout allTypeWrapper, incomeTypeWrapper, expenseTypeWrapper;
    private ImageView imgAllType, imgIncome, imgExpense;

    private String EXPENSE_TYPE;

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

    //Expense Type wrappers
        allTypeWrapper = findViewById(R.id.all_type_wrapper);
        incomeTypeWrapper = findViewById(R.id.income_type_wrapper);
        expenseTypeWrapper = findViewById(R.id.expense_type_wrapper);

        allTypeWrapper.setOnClickListener(this);
        incomeTypeWrapper.setOnClickListener(this);
        expenseTypeWrapper.setOnClickListener(this);

    //Expense type images
        imgAllType = findViewById(R.id.img_all_type);
        imgIncome = findViewById(R.id.img_income);
        imgExpense = findViewById(R.id.img_expense);

    ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setTitle("Filter");
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_check_reset, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {

        if (item.getItemId() == R.id.btn_restore_filter)
        {

        }
        else if (item.getItemId() == R.id.btn_check_filter)
        {
            Intent intent  = new Intent();
            intent.putExtra("Expense", EXPENSE_TYPE);
            setResult(Activity.RESULT_OK, intent);
            finish();
        }
        else if (item.getItemId() == android.R.id.home)
        {
            onBackPressed();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();

        //Expense type
        if (id == R.id.all_type_wrapper)
        {
            EXPENSE_TYPE = "ALL";
            imgAllType.setImageResource(R.drawable.ic_rb_checked);
            imgIncome.setImageResource(R.drawable.ic_rb_unchecked);
            imgExpense.setImageResource(R.drawable.ic_rb_unchecked);
        }

        else if (id == R.id.income_type_wrapper)
        {
            EXPENSE_TYPE = "INCOME";
            imgAllType.setImageResource(R.drawable.ic_rb_unchecked);
            imgIncome.setImageResource(R.drawable.ic_rb_checked);
            imgExpense.setImageResource(R.drawable.ic_rb_unchecked);
        }

        else if (id == R.id.expense_type_wrapper)
        {
            EXPENSE_TYPE = "EXPENSE";
            imgAllType.setImageResource(R.drawable.ic_rb_unchecked);
            imgIncome.setImageResource(R.drawable.ic_rb_unchecked);
            imgExpense.setImageResource(R.drawable.ic_rb_checked);
        }
    }
}

I want someone to explain me how can I get a value from an Activity and pass it to different fragments.

Upvotes: 0

Views: 142

Answers (6)

Jakir Hossain
Jakir Hossain

Reputation: 3930

So when you press on the OK button on your FilterActivity it gets you to the MainActivity.

You can call your FilterActivity using startActivityForResult and pass your data to main activity using setResult.

call your FilterActivity from MainActivity

Intent i = new Intent(this, FilterActivity.class);
startActivityForResult(i, 1);

In FilterActivity pass data to main activity

else if (item.getItemId() == R.id.btn_check_filter){

   Intent returnIntent = new Intent();
   returnIntent.putExtra("Expense",EXPENSE_TYPE);
   setResult(Activity.RESULT_OK,returnIntent);
   finish();
}

In your MainActivity

public class MainActivity extends Activity {

    private String result = "initial value";

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

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

      if (requestCode == 1) {
          if(resultCode == Activity.RESULT_OK){
              result = data.getStringExtra("Expense");
          }
          if (resultCode == Activity.RESULT_CANCELED) {
              //Write your code if there's no result
          }
      }
   }
   // to access your data from fragements
    public String getMyData() {
        return result;
    }
}

From your fragment you can access your value like

public class YourFragment extends Fragment {

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

        MainActivity activity = (MainActivity) getActivity();
        String dataFromActivity = activity.getMyData();
        Log.d("TAG", "Your data from activity "+dataFromActivity);
    }
}

UPDATE

In your FilterActivity you can check is EXPENSE_TYPE set or not

 else if (item.getItemId() == R.id.btn_check_filter){
    if(TextUtils.isEmpty(EXPENSE_TYPE)){
       // show toast or log that you have to select an expense type
       return false;
    }
    // EXPENSE_TYPE is not null or empty
    Intent intent  = new Intent();
    intent.putExtra("Expense", EXPENSE_TYPE);
    setResult(Activity.RESULT_OK, intent);
    finish();
}

Upvotes: 1

dani3264
dani3264

Reputation: 11

There are few ways to do this

  1. Get the type from filtered activity to main activity, then on loading the fragment in main activity send it via ARG (bundle that you are using).

  2. Second option is a hack, where you can skip these steps. In filtered activity save a string value to shared pref according to Expense type And then use it anywhere in fragment.

Goodluck

Upvotes: 0

Harish Reddy
Harish Reddy

Reputation: 992

There is so many ways to send Data from you Activity to diffarent fragments present in the same Activity

Method 1:- Use EventBus such as Otto Event Bus or GreenRobert

in my case GreenRobert is vary easy to learn and implement

Method 2:- Use BroadcastReceiver which is simple to learn

Method 3:- Use Bundle to send Data to your fragments

Upvotes: 0

Gourav Uniyal
Gourav Uniyal

Reputation: 16

In your FilterActivity onRadio button click listener add following code:

    Intent intent=new Intent();
    intent.putExtra( "key1", values);// add values to intent you want to send to MainActivity.
    intent.putExtra( "key2", values);
    setResult(2,intent);
    finish();

In your MainActivity add following code to start FilterActivity :

     @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId( );
        if (id == R.id.your_Id) 
            Intent intent = new Intent( getApplicationContext( ),FilterActivity.class);
            startActivityForResult( intent, 2);
        }
        return super.onOptionsItemSelected( item );
    }

Here startActivityForResult will bring back the data from FilterActivity after selecting the radio options. Add this function to your MainActivity

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult( requestCode, resultCode, data );
        if (requestCode == 2) {
            String yourValues = data.getIntExtra( "key1", 0 );
        //create the bundle here to send data to the fragment
        }
    }

Now add yourValues to the bundle (hope you can do it yourself) and then send these bundle to your fragment. And let me know if it is helpful :)

Upvotes: 0

Sorwar Hossain Mostafa
Sorwar Hossain Mostafa

Reputation: 255

You said the Fragments you are using are hosted on you MainActivity, that means you already created those fragment instances with your MainActivty. But you are tring to create a new instance and set arguments on FitlerActivity which is not the Host of the Fragments. In the way you are approaching its not gonna work.

You can try getting the EXPENSE_TYPE from your FilterActivity to Your MainActivity, then recreating the fragments in the MainActivity with EXPENSE_TYPE in their arguments.

Upvotes: 1

Ankit Tale
Ankit Tale

Reputation: 2004

You can send data using setArguements in Android

Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

And retrieve them using

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    String strtext = getArguments().getString("edttext");    
    return inflater.inflate(R.layout.fragment, container, false);
}

Use Add Fragment Method.

Upvotes: 0

Related Questions