我正在开发一款应用。我想列出朋友片段中的项目,当我点击该项目然后转到消息片段(另一个片段)。我的代码如下。
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();
}
}
当我添加
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();*/
}
});
显示错误
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>
请帮帮我
答案 0 :(得分:4)
问题来自
cardView = (CardView) rootView.findViewById(R.id.cardview1);
线。
因为带有CardView
id的R.id.cardview1
位于RecyclerView
的行布局内,但使用rootView.findViewById
尝试从错误的布局fragment_friends
访问它。
要解决此问题,请在setOnClickListener
类
onBindViewHolder
方法内向CardView添加RecyclerViewAdapter
答案 1 :(得分:1)
问题在ρяσѕρєяK的答案中有所解释,但我想补充一点。
对我来说,一个好习惯是创建自定义视图类,这样就可以在构造函数中设置所需的所有侦听器。
然后在您的RecyclerView适配器中,您可以覆盖此方法,如下所示:
@Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = new MyCustomView();
return new ViewHolder(v);
}
您的侦听器在MyCustomView实例化期间设置,您可以使用事件方式将事件传递给您的片段。有很多图书馆在做这项工作,一个很好的例子是Otto
答案 2 :(得分:0)
我的回答。
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");
}
}
}