关于Fragment的Adapter调用方法

时间:2017-09-14 12:10:17

标签: android android-fragments android-adapter

这个Fragment位于ViewPager上,它使用json响应执行okhttp get。 json在RecyclerView上进行了改编,当我点击该recyclerview上的记录时,它必须调用Fragment的putPasta()方法,但是当我执行此操作时,我得到NullPointerException。

片段:

public class PersonalizzataTab extends Fragment{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.personalizzata_layout, container, 

    PastaAdapter adapter = new PastaAdapter(getContext(), new PastaAdapter.AdapterInterface() {
        @Override
        public void putPasta() {
            // the action called from adapter
        }
    });

    fab1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SyncPasta syncPasta = new SyncPasta();
            syncPasta.execute();
        }
    });

    return view;
}

class SyncPasta extends AsyncTask {

    @Override
    protected Object doInBackground(Object[] params) {

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url("link of php file")
                .get()
                .addHeader("cache-control", "no-cache")
                .addHeader("postman-token", "4681c54c-3bd9-3d92-42f6-d7f9a68b4044")
                .build();

        try {
            Response response = client.newCall(request).execute();
            setPasta(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}

public void setPasta(final String aResult) {
    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {


            final JSONArray[] jsonArray = {null};
            try {
                jsonArray[0] = new JSONArray(aResult);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            Pasta pasta;
            ArrayList<Pasta> arrayListPasta = new ArrayList<Pasta>();
            if (jsonArray[0] != null) {
                for (int i = 0; i < jsonArray[0].length(); i++) {

                    JSONObject json = null;
                    try {

                        json = jsonArray[0].getJSONObject(i);
                        pasta = new Pasta(json.getString("pasta"), json.getDouble("prezzo"), json.getString("miniatura"), json.getString("miniature"));
                        arrayListPasta.add(pasta);
                        // Assign adapter to ListView


                        pastaAdapter = new PastaAdapter(getActivity(), arrayListPasta);
                        listViewBanner.setAdapter(pastaAdapter);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

            }
        }
    });
}

适配器:

public class PastaAdapter extends RecyclerView.Adapter<PastaAdapter.MyViewHolder> {

private Context mContext;
private List<Pasta> listaPasta;

AdapterInterface buttonListener;

public PastaAdapter (Context context, AdapterInterface buttonListener)
{
    this.mContext = context;
    this.buttonListener = buttonListener;
}

public interface AdapterInterface {
    void putPasta();
}

public class MyViewHolder extends RecyclerView.ViewHolder {
    public RelativeLayout layoutPasta;


    public MyViewHolder(View view) {
        super(view);
        layoutPasta = (RelativeLayout) view.findViewById(R.id.layoutIngrediente);
    }
}

public PastaAdapter(Context mContext, List<Pasta> listaPasta) {
    this.mContext = mContext;
    this.listaPasta = listaPasta;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.cell_ingredienti_layout, parent, false);
    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
    final Pasta pasta = listaPasta.get(position);
    holder.layoutPasta.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                buttonListener.putPasta();

            }
        }
    });

}

@Override
public int getItemCount() {
    return listaPasta.size();
}
}

例外:

java.lang.NullPointerException: Attempt to invoke interface method 'void sgware.easyfood.PastaAdapter$AdapterInterface.buttonPressed()' on a null object reference
at sgware.easyfood.PastaAdapter$1.onClick(PastaAdapter.java:97)
at android.view.View.performClick(View.java:5226)
at android.view.View$PerformClick.run(View.java:21266)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5845)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)

1 个答案:

答案 0 :(得分:0)

像这样添加适配器构造函数

    public PastaAdapter(Context mContext, List<Pasta> listaPasta, AdapterInterface buttonListener) {
        this.mContext = mContext;
        this.listaPasta = listaPasta;
    this.buttonListener=buttonListener;
    } 

并调用片段

 pastaAdapter = new PastaAdapter(getActivity(), arrayListPasta, new PastaAdapter.AdapterInterface() {
        @Override
        public void putPasta() {
            // the action called from adapter
        }
    });
    listViewBanner.setAdapter(pastaAdapter);