搜索后接口返回null

时间:2019-05-27 20:30:59

标签: java android interface nullpointerexception

在搜索之后,RecyclerView会更新,并且mCallback返回null,但在搜索正常之前。

enter image description here

AdapterHistorico.java

 package com.beliasdev.cadjobel.adapter;

 import android.content.Context;

 import android.content.DialogInterface;
 import android.support.v7.app.AlertDialog;
 import android.support.v7.widget.RecyclerView;
 import android.text.TextUtils;
 import android.util.Log;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.AdapterView;
 import android.widget.ArrayAdapter;
 import android.widget.EditText;
 import android.widget.ImageView;
 import android.widget.LinearLayout;
 import android.widget.Spinner;
 import android.widget.TextView;
 import android.widget.Toast;


 import com.beliasdev.cadjobel.R;
 import com.beliasdev.cadjobel.utility.DrawableHelper;
 import com.bumptech.glide.Glide;

 import java.text.ParseException;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;

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

    private Spinner spinner1;
    private String dateold;
    private String datenew;
    private String compareValue;
    private String concluido;
    private String em_andamento;
    private String cancelado;
    private String concluido1;
    private String em_andamento1;
    private String cancelado1;
    private String status;
    private Context context;
    private LayoutInflater inflater;
    private IProcessFilter mCallback;
    private ArrayList<DataHistorico> data;
    //List<DataHistorico> data= Collections.emptyList();
    DataHistorico current;
    int currentPos=0;


    public AdapterHistorico(Context context, ArrayList<DataHistorico> data, IProcessFilter callback){
        this.context=context;
        inflater= LayoutInflater.from(context);
        this.data=data;
        mCallback = callback;
    }

    public interface IProcessFilter {
        void onProcessFilter(DataHistorico produtos);
    }

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

        View view=inflater.inflate(R.layout.container_historico, parent,false);



        MyHolder holder=new MyHolder(view);

        return holder;
    }


   @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
       final DataHistorico pedidos = data.get(position);

        values from list
        MyHolder myHolder= (MyHolder) holder;
        final DataHistorico current = data.get(position);

        dateold = current.pData;
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yyyy 'ás' HH:mm:ss");
            datenew = df2.format(format.parse(dateold));

        } catch (ParseException e) {

            e.printStackTrace();
        }

        myHolder.txtPedidoNumero.setText("N° " + current.pNumero);

        myHolder.txtPedidoCliente.setText(current.pCliente);

        myHolder.txtPedidoData.setText(datenew);

        myHolder.txtPedidoTotal.setText("R$ " + current.pTotal);

        myHolder.edtPedido.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                mCallback.onProcessFilter(pedidos); //NullPointerException here
            }
        });


        // load image into imageview using glide
        concluido = "concluido";
        cancelado = "cancelado";
        em_andamento= "em_andamento";
        status = current.pStatus;
        if (status.equals(concluido)) {
            Glide.with(context).load(R.drawable.ic_pedido_concluido).into(myHolder.imgPedidoStatus);
        } else if (status.equals(cancelado)) {
            Glide.with(context).load(R.drawable.ic_pedido_cancelado).into(myHolder.imgPedidoStatus);
        }else if (status.equals(em_andamento)) {
            Glide.with(context).load(R.drawable.ic_pedido_em_andamento).into(myHolder.imgPedidoStatus);
        }


    }

    // return total item from List
    @Override
    public int getItemCount() {
        return data.size();
    }


    class MyHolder extends RecyclerView.ViewHolder{

        TextView txtPedidoNumero;
        TextView txtPedidoCliente;
        ImageView imgPedidoStatus;
        TextView txtPedidoData;
        TextView txtPedidoTotal;
        ImageView edtPedido;


        // create constructor to get widget reference
        public MyHolder(View itemView) {
            super(itemView);
            txtPedidoNumero= (TextView) itemView.findViewById(R.id.txtPedidoNumero);
            txtPedidoCliente= (TextView) itemView.findViewById(R.id.txtPedidoCliente);
            imgPedidoStatus= (ImageView) itemView.findViewById(R.id.imgPedidoStatus);
            txtPedidoData = (TextView) itemView.findViewById(R.id.txtPedidoData);
            txtPedidoTotal = (TextView) itemView.findViewById(R.id.txtPedidoTotal);
            edtPedido = (ImageView) itemView.findViewById(R.id.edtPedido);
        }

    }



    }

FragmentoHistorico.java

public class FragmentoHistorico extends Fragment implements AdapterHistorico.IProcessFilter {

[...]



public void onProcessFilter(DataHistorico pedidos) {

            EditarPedidoDialog(pedidos);

    }

private void EditarPedidoDialog(final DataHistorico pedidos){

        LayoutInflater inflater = LayoutInflater.from(getActivity());
        final View subView = inflater.inflate(R.layout.layout_edt_pedido, null);

[...]

 private class ProcurarPedido extends AsyncTask<String, String, String> {

    ProgressDialog pdLoading = new ProgressDialog(getActivity());
    HttpURLConnection conn;
    URL url = null;
    private String searchQuery;
    private View rootView;

    public ProcurarPedido(String searchQuery, View rootView){
        this.searchQuery=searchQuery;
        this.rootView=rootView;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tAguarde...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected String doInBackground(String... params) {
        try {

            // Enter URL address where your php file resides
            url = new URL(ADMIN_PANEL_URL + "public/procurar-pedido-app.php");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return e.toString();
        }
        try {

            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("POST");

            // setDoInput and setDoOutput to true as we send and recieve data
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // add parameter to our above url
            Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
            String query = builder.build().getEncodedQuery();

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return e1.toString();
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return (result.toString());

            } else {
                return("Erro na conexão!");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return e.toString();
        } finally {
            conn.disconnect();
        }


    }


    @Override
    protected void onPostExecute(String result) {

        //this method will be running on UI thread
        Log.v("result", result);
        pdLoading.dismiss();

        ArrayList<DataHistorico> data=new ArrayList<>();

        if(result.equals("no rows")) {

            mRVHistoricoInfo = (RecyclerView)rootView.findViewById(R.id.ListaHistoricoInfo);
            mAdapter = new AdapterHistorico(getActivity(), data, null);
            mRVHistoricoInfo.setAdapter(mAdapter);
            mRVHistoricoInfo.setLayoutManager(new LinearLayoutManager(getActivity()));
           data.clear();

            Toast.makeText(getActivity(), "Não foram encontrados pedidos pelo nome do cliente informado.", Toast.LENGTH_LONG).show();
        }else{

            try {
                data.clear();
                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList as class objects
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);
                    DataHistorico historicoData = new DataHistorico();
                    historicoData.pNumero= json_data.getString("nid");
                    historicoData.pStatus= json_data.getString("pedido_status");
                    historicoData.pCliente= json_data.getString("pedido_cliente");
                    historicoData.pEndereco= json_data.getString("pedido_endereco");
                    historicoData.pData= json_data.getString("pedido_data");
                    historicoData.pTotal= json_data.getString("pedido_total");
                    data.add(historicoData);
                }

                mRVHistoricoInfo = (RecyclerView)rootView.findViewById(R.id.ListaHistoricoInfo);
                mAdapter = new AdapterHistorico(getActivity(), data, null);
                mRVHistoricoInfo.setAdapter(mAdapter);
                mRVHistoricoInfo.setLayoutManager(new LinearLayoutManager(getActivity()));

            } catch (JSONException e) {
                // You to understand what actually error is and handle it appropriately
                Toast.makeText(getActivity(),"Não foi possível contatar o servidor.", Toast.LENGTH_LONG).show();
            }

        }

    }

}

[...]

这是错误:

  

java.lang.NullPointerException:尝试调用接口方法   '无效   com.beliasdev.cadjobel.adapter.AdapterHistorico $ IProcessFilter.onProcessFilter(com.beliasdev.cadjobel.adapter.DataHistorico)'   在空对象引用上

1 个答案:

答案 0 :(得分:0)

您要发送null而不是侦听器作为参数:

所以改变

 mAdapter = new AdapterHistorico(getActivity(), data, null);

收件人

 mAdapter = new AdapterHistorico(getActivity(), data, this);