fazil tm
fazil tm

Reputation: 299

Cannot move to another fragment in recycleview

I am developing an app. I want list the item in the friends fragment and when i click the item then goes to message fragment (another fragment). My code is given below.

FriendsFragment.java

public class FriendsFragment extends android.support.v4.app.Fragment {

CardView cardView;
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;

String GET_JSON_DATA_HTTP_URL = "http://192.168.43.7/work/ecom/2/1.php";
String JSON_IMAGE_TITLE_NAME = "image_title";
String JSON_IMAGE_URL = "image_url";

JsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
public FriendsFragment() {
    // Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_friends, container, false);
    GetDataAdapter1 = new ArrayList<>();
    recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview1);
    recyclerView.setHasFixedSize(true);
    recyclerViewlayoutManager = new LinearLayoutManager(getContext());
    recyclerView.setLayoutManager(recyclerViewlayoutManager);



    cardView = (CardView) rootView.findViewById(R.id.cardview1);


    cardView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Log.d("LOGTAG", "clicked");
            MessagesFragment fragment = new MessagesFragment();
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.container_body, fragment).commit();


        }
    });


    JSON_DATA_WEB_CALL();



    // Inflate the layout for this fragment
    return rootView;
}

public void JSON_DATA_WEB_CALL(){

    jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,

            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {

                    Log.d("LOGTAG", "Response :"+response);

                    JSON_PARSE_DATA_AFTER_WEBCALL(response);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

    requestQueue = Volley.newRequestQueue(getContext());

    requestQueue.add(jsonArrayRequest);
}


public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){

    for(int i = 0; i<array.length(); i++) {

        GetDataAdapter GetDataAdapter2 = new GetDataAdapter();

        JSONObject json = null;
        try {

            json = array.getJSONObject(i);

            GetDataAdapter2.setImageTitleNamee(json.getString(JSON_IMAGE_TITLE_NAME));

            GetDataAdapter2.setImageServerUrl(json.getString(JSON_IMAGE_URL));

        } catch (JSONException e) {

            e.printStackTrace();
        }
        GetDataAdapter1.add(GetDataAdapter2);
    }

    recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, getContext());

    recyclerView.setAdapter(recyclerViewadapter);

}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
}

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

When i add

  cardView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Log.d("LOGTAG", "clicked");
           /* MessagesFragment fragment = new MessagesFragment();
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.container_body, fragment).commit();*/


        }
    });

It shows error

FATAL EXCEPTION: main
                                                                Process: com.ecom.fragment2, PID: 21541
                                                                java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.CardView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                                    at com.ecom.fragment2.FriendsFragment.onCreateView(FriendsFragment.java:77)
                                                                    at android.support.v4.app.Fragment.performCreateView(Fragment.java:2080)
                                                                    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108)
                                                                    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1290)
                                                                    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:801)
                                                                    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1677)
                                                                    at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:536)
                                                                    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:5312)
                                                                    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:901)
                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)

fragment_friends.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.ecom.fragment2.FriendsFragment">

<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerview1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

</RelativeLayout>

recyclerview_items.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/cardview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardElevation="3dp"
card_view:contentPadding="3dp"
card_view:cardCornerRadius="3dp"
card_view:cardMaxElevation="3dp"
>


<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/VollyNetworkImageView1"
        android:layout_width="150dp"
        android:layout_height="100dp"
        android:src="@mipmap/ic_launcher"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Image Name"
        android:id="@+id/textView_item"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/VollyNetworkImageView1"
        android:layout_toEndOf="@+id/VollyNetworkImageView1"
        android:layout_marginLeft="20dp"/>

</RelativeLayout>

</android.support.v7.widget.CardView>

Please help me

Upvotes: 1

Views: 286

Answers (3)

fazil tm
fazil tm

Reputation: 299

Here my answer.

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

Context context;

List<GetDataAdapter> getDataAdapter;

ImageLoader imageLoader1;

private final View.OnClickListener mOnClickListener = new MyOnClickListener();


public RecyclerViewAdapter(List<GetDataAdapter> getDataAdapter, Context context){

    super();
    this.getDataAdapter = getDataAdapter;
    this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_items, parent, false);
    v.setOnClickListener(mOnClickListener);
    ViewHolder viewHolder = new ViewHolder(v);

        return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {

    GetDataAdapter getDataAdapter1 =  getDataAdapter.get(position);

    Viewholder.ImageTitleNameView.setText(getDataAdapter1.getImageTitleName());

    imageLoader1 = ServerImageParseAdapter.getInstance(context).getImageLoader();

    imageLoader1.get(getDataAdapter1.getImageServerUrl(),
            ImageLoader.getImageListener(
                    Viewholder.networkImageView,//Server Image
                    R.mipmap.ic_launcher,//Before loading server image the default showing image.
                    android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
            )
    );

    Viewholder.networkImageView.setImageUrl(getDataAdapter1.getImageServerUrl(), imageLoader1);

    Viewholder.ImageTitleNameView.setText(getDataAdapter1.getImageTitleName());

}

@Override
public int getItemCount() {

    return getDataAdapter.size();
}

class ViewHolder extends RecyclerView.ViewHolder{



    public TextView ImageTitleNameView;
    public NetworkImageView networkImageView ;

    public ViewHolder(View itemView) {

        super(itemView);

        ImageTitleNameView = (TextView) itemView.findViewById(R.id.textView_item) ;

        networkImageView = (NetworkImageView) itemView.findViewById(R.id.VollyNetworkImageView1) ;

    }
}

private class MyOnClickListener implements View.OnClickListener {

    @Override
    public void onClick(View v) {


        //Log.d("LOGTAG", "clicked");

    }
}
}

Upvotes: 0

firegloves
firegloves

Reputation: 5709

The problem is explained in ρяσѕρєя K 's answer, but I want to add an extra.

A good practice for me is to work creating custom views class, so you can set in their constructor all the listeners you want.

Then in your RecyclerView's adapter you can override this method like follows:

@Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = new MyCustomView();
    return new ViewHolder(v);
}

Your listeners are set during MyCustomView instantiation and you can communicate events to your fragment using the event way. There's a lot of libraries doing this work, a good example is Otto

Upvotes: 1

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132972

Problem is from

cardView = (CardView) rootView.findViewById(R.id.cardview1);

line.

Because CardView with R.id.cardview1 id is inside row layout of RecyclerView but using rootView.findViewById trying to access it from wrong layout which is fragment_friends .

To get it fix add setOnClickListener to CardView inside onBindViewHolder method of RecyclerViewAdapter class

Upvotes: 4

Related Questions