Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send data from an activity to its parent fragment? [duplicate]

I have a main activity, inside which there is a fragment with an image view. When this image view is clicked, a new activity starts which contains a list view. I want to return the position(index) the user clicks on this list view, back to the fragment.

Fragment Code

package com.example.kedee.testgradle;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


/**
 * A simple {@link Fragment} subclass.
 */
public class ASKFragment extends Fragment implements View.OnClickListener{
    private Context context;
    private View rootView;
    private int pos;

    public ASKFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        rootView= inflater.inflate(R.layout.fragment_ask, container, false);
        context=inflater.getContext();
        setListeners();
        return  rootView;
    }

    void setListeners(){
        ImageView catIcon=(ImageView)rootView.findViewById(R.id.cat_icon);
        catIcon.setOnClickListener(this);



    }

    @Override
    public void onClick(View v) {
        int vID=v.getId();
        if(vID==R.id.cat_icon){
            Intent intent=new Intent(getActivity(),ASK.class);
            getActivity().startActivity(intent);
        }

    }
}    

Code of Activity which is getting called from this fragment. (ASK activity)

package com.example.kedee.testgradle;

import android.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class ASK extends AppCompatActivity {
    private int index;
    private String[] catNames= {"Acad","Emer","Tech","Exam","Station","Finance","Medical","Place","Sports" ,
            "Others" };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ask);
        ListView listView=(ListView)findViewById(R.id.ask_cat_listView);
        listView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,catNames));
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            public void onItemClick(AdapterView<?> listView, View v, int pos, long id){
                index=pos;
                //code to return back this index to the parent fragment?
            }
        });
    }


}
like image 883
Sumit Sagar Avatar asked Mar 05 '16 10:03

Sumit Sagar


People also ask

How do you share data between multiple fragments?

When working with child fragments, your parent fragment and its child fragments might need to share data with each other. To share data between these fragments, use the parent fragment as the ViewModel scope.

Can we navigate from activity to fragment?

Move activity logic into a fragment With the fragment definition in place, the next step is to move the UI logic for this screen from the activity into this new fragment. If you are coming from an activity-based architecture, you likely have a lot of view creation logic happening in your activity's onCreate() function.

Can a fragment reuse in multiple activities?

Yes you can, but you have to add more logic to your fragments and add some interfaces for each activity.


1 Answers

use startActivityForResult

1. in ASKFragment

Intent intent=new Intent(getActivity(),ASK.class);
getActivity().startActivityForResult(intent, 22 /* any other request code you want */);

2. Pass position with intent.

listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            public void onItemClick(AdapterView<?> listView, View v, int pos, long id){
                index=pos;
                Intent i = new Intent();
                i.putExtra("position", index);
                setResult(RESULT_OK, i);
                finish();
            }
        });

3. The activity from where you are adding or replacing fragment.

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 22 && resultCode == RESULT_OK) {
            // get the position from intent
            if(data.getExtras()!=null && data.hasExtra("position")){
               int position = data.getExtras().getInt("position");
               // pass this position to fragment.
            }
        }
    }

EDIT
Send the value from Activity to fragment.
1) create function in fragment

public void getPositionOfList(int position){
   // here is the position
}

2) from Activity calling the fragment method.

if (requestCode == 22 && resultCode == RESULT_OK) {
                // get the position from intent
                if(data.getExtras()!=null && data.hasExtra("position")){
                   int position = data.getExtras().getInt("position");
                   // pass this position to fragment.
                   ((ASKFragment)fragmentManager.findFragmentById(/*id of your container*/)).getPositionOfList(position);
                }
            }
like image 116
Deepak Goyal Avatar answered Oct 18 '22 06:10

Deepak Goyal