0

Before posting I have tried several things one of them was following this stackoverflow: How to change fragments using Android navigation drawer

However when I try some of the solutions posted there I get errors, even when the fragment was created by android studio. It says something about fragment.v4, while that is used throughout the fragment created by android studio.

Here's my code:

@Override
public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    FragmentManager fragmentManager = getSupportFragmentManager();
    Fragment fragment = new Fragment();
    switch(position) {
        case 1:
            fragment = new WeatherFragment();
            break;
        case 2:
            fragment = new WeatherFragment();
            break;
    }
    fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
}

The weather fragment I'm trying to change to when clicking on the second item does not show.

Any tips?

Here's my current error:

06-10 05:28:23.247 24328-24328/nl.shacklez.mijnrecepten E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: nl.shacklez.mijnrecepten, PID: 24328 java.lang.ClassCastException: nl.shacklez.mijnrecepten.MainActivity@2c5b3c99 must implement OnFragmentInteractionListener at nl.shacklez.mijnrecepten.WeatherFragment.onAttach(WeatherFragment.java:83) at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:853) at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067) at android.app.BackStackRecord.run(BackStackRecord.java:833) at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1452) at android.app.FragmentManagerImpl$1.run(FragmentManager.java:447) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5221) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Here's my weatherFrag class:

package nl.shacklez.mijnrecepten;

import android.app.Activity;
import android.app.Fragment;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class WeatherFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment WeatherFragment.
 */
// TODO: Rename and change types and number of parameters
public static WeatherFragment newInstance(String param1, String param2) {
    WeatherFragment fragment = new WeatherFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

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

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

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

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnFragmentInteractionListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * <p/>
 * See the Android Training lesson <a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * >Communicating with Other Fragments</a> for more information.
 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    public void onFragmentInteraction(Uri uri);
}

}

Community
  • 1
  • 1
Nick Audenaerde
  • 967
  • 2
  • 14
  • 33

2 Answers2

0

first make sure that your fragment does extends Fragment then use this code instead:

@SuppressLint("NewApi")
 void displayView(int position) {
        // update the main content by replacing fragments
        Fragment fragment = null;
        switch (position) {
        case 0:
            fragment = new firstFragment();
            break;
        case 2:
        fragment = new secondFragment();
        break;
    default:
            break;
        }
    if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frame_container, fragment).commit();

            // update selected item and title, then close the drawer

            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
    }

if you inseast on using support fragment instead of android.app.Fragment;

try to import V4 fragment if it still displays the error make sure you have installed Android Support Library from SDK manager you can also check you dependencies and re-sync the project.

hope this will help

Ahmad Sanie
  • 3,678
  • 2
  • 21
  • 56
0

look at following code,

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnFragmentInteractionListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

in your fragment. You have to implement this

public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    public void onFragmentInteraction(Uri uri);
}

interface from your fragment in your activity. That means your activity should implement WeatherFragment.OnFragmentInteractionListener. This think is a feature of fragments created by Android Studio. It creates this interface to communicate between fragments and activity. Normally I remove the code after super.onAttach(activity) in onAttach function.

sabbir
  • 438
  • 3
  • 11