Oussama Benzita Oussama Benzita - 3 months ago 20
Java Question

Passing the Context of a Fragment

I have a Navigation Drawer based app , a

Home Class extends AppCompatActivity
in which i switch between the different tabs of the Navigation Drawer and a HomeFragment that represents the " HOME " tab .
In the other hand i made a " ReadRSS " class with a constructor taking Context as parameter .
I want to Instantiate the " ReadRSS " class in my HomeFragment , if i use keywrod this i got an error says :

ReadRSS (android.content.Context) in ReadRSS cannot be applied
to (com.example.essat.essat.HomeFragment)


If i try to pass
getAcitivty()
or
getContext()
i get an error says :

unreachable statement


here is My Code for more details :

public class ReadRSS extends AsyncTask<Void,Void,Void> {

Context context;
ProgressDialog progressDialog;

public ReadRSS (Context context){
this.context=context;
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Loading ...");
}
// Other Methods ...
}


HomeFragment :

public class HomeFragment extends Fragment {


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



@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);

ReadRSS readRSS = new ReadRSS(// I Pass them all Here );
readRSS.execute();

}

}


In My Home Class i call the Fragment using the code below :

fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.Home_Container,new HomeFragment());
fragmentTransaction.commit();


and reuse it again in a Switch Statement with the other tabs , so that when the app launches it show the home fragment and if u ever changed the tab you can come back using the "HOME" tab.

I Hope You can help me Solve this error or suggest an other way of doing it .

Thanks in Advance .

Answer

Oh, sure - that's because you have return statement before ReadRSS initialize.

Change order to:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    ReadRSS readRSS = new ReadRSS(// I Pass them all Here );
    readRSS.execute();

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

And it would be ok.