Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call method of one fragment from another fragment class in android

I want to call a method of FragmentB (Class) from a fragmentA I tried by making a object of fragmentb in fragmentA (class) but it's not working here is the code of fragmentA in this class I have a method through which I will call the method of FragmentB class

adddata.setOnClickListener(
        new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            boolean isInserted = myDb.addalldata(monthly_income.getText().toString(),
                room_rent.getText().toString(),
                mess_rent.getText().toString());
            if (isInserted = true)
                Toast.makeText(getActivity().getBaseContext(), "Data Inserted", Toast.LENGTH_LONG).show();
            else
            Toast.makeText(getActivity().getBaseContext(), "Data not Inserted", Toast.LENGTH_LONG).show();
        }
    }
);

I want to call this method of fragmentB

public void show() {
    Cursor res = myDb.getAllData();
    StringBuffer buffer = new StringBuffer();
    while (res.moveToNext()) {
        displayresult.setText( buffer.append( res.getString(1)));
    }
}

I tried by writing this code in method of fragmentA but am getting error

FragmentA fragment=          
    (FragmentA)getSupportFragmentManager().findFragmentById(R.id.pageview2);
    ((FragmentA)fragment).show();
like image 732
robinHood013 Avatar asked Nov 30 '22 17:11

robinHood013


2 Answers

Try this solution:

((FragmentA) getActivity()
    .getSupportFragmentManager()
    .findFragmentById(R.id.pageview2)
).show();
like image 144
Vindhya Pratap Singh Avatar answered Dec 03 '22 06:12

Vindhya Pratap Singh


You can create static varibales like this

static  FragmentB f;

public static FragmentB newInstance(String title) {
        FragmentB f = new FragmentB();
        Bundle b = new Bundle();
        b.putString(ARG_STATION_TITLE, title);
        f.setArguments(b);
        return f;
    }

You can use the getInstance() method to get the instance of fragmentB

public static FragmentB getInstance(){
    return f;
}

Call like this FragmentB.getInstance().methodinFragmentB();

like image 29
sunil sunny Avatar answered Dec 03 '22 06:12

sunil sunny