android.widget.TextView.setText (java.lang.CharSequence) on a null object reference

0

I have a very strange error in android (api 25), I tried many things and still could not, help! please I try the application, calculator type to make payment calculations, in which you select year, months and situation, and with these parameters you calculate your payment that seems in a TextView, but I get this strange error "Attempt to invoke virtual method void android.widget.TextView.setText (java.lang.CharSequence) on a null object reference " The code is as follows, it is a fragment:

public class FragmentCalculadora extends Fragment implements View.OnClickListener, AdapterView.OnItemSelectedListener {


    Spinner Sptarifa, SpSituacion, SpMeses;
    Button calcular;

    ArrayList<String> datos = new ArrayList<String>();
    ArrayList<String> datos2 = new ArrayList<String>();
    ArrayList<String> datos3 = new ArrayList<String>();

    float cf, tar, infra, rec;
    int descue;
    float n1, n2, n3, n4, n5;


    @Override
    public void onClick(View v) {

        switch (v.getId())
        {
            case R.id.btnCalcular:

                TextView cfija = (TextView) v.findViewById(R.id.txtCFCalculadora);
                TextView tarifa = (TextView) v.findViewById(R.id.txtTarifaCalculadora);
                TextView inf = (TextView) v.findViewById(R.id.txtInfraCalculadora);
                TextView recargo = (TextView) v.findViewById(R.id.txtRecargoCalculadora);
                TextView total = (TextView) v.findViewById(R.id.txtTotalCalculadora);


                 System.out.println(n1); //tenia esto para ver si realmente estaba calculando los datos, que si lo hacia

                try {

                        System.out.println("Aqui genera el error");

                        cfija.setText(String.valueOf(n1));
                        tarifa.setText(String.valueOf(n2));
                        inf.setText(String.valueOf(n3));
                        recargo.setText(String.valueOf(n4));
                        total.setText(String.valueOf(n5));


                }catch (Exception e) {
                    Toast.makeText(getContext(), "hey onclick! " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

                break;
        }
    }


    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
    {
        int idT = 0;
        String situa = SpSituacion.getSelectedItem().toString();
        System.out.println(situa);

        String tari = Sptarifa.getSelectedItem().toString();
        System.out.println(tari);

        String mes = SpMeses.getSelectedItem().toString();
        System.out.println(mes);


        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy);
        Connection connection;
        String url;
        //mi conexion a una bd
        try
        {

            Class.forName("net.sourceforge.jtds.jdbc.Driver");
            url = "jdbc:jtds:sqlserver://SERVIDOR;databaseName=BdCalculadora;user=sa;password=1234"; 
            connection = DriverManager.getConnection(url);
            Statement estatuto = connection.createStatement();


            //cargar la situacion
            String query ="SELECT * FROM Situacion WHERE descripcion = '" + situa + "'";
            ResultSet resultado = estatuto.executeQuery(query);
            if (resultado.next())
            {
                descue = resultado.getInt("descuento");
                idT = resultado.getInt("idSituacion");
            }
            resultado.close();


            //cargar la tarifas
            String query2 ="SELECT * FROM Tarifas WHERE año = " + tari;
            ResultSet resultado2 = estatuto.executeQuery(query2);
            if (resultado2.next())
            {
                cf = resultado2.getFloat("cf");
                tar = resultado2.getFloat("tar");
                infra = resultado2.getFloat("infra");
                rec = resultado2.getFloat("recargos");

                n1= (cf / 12) *  Integer.parseInt(mes);
                n2 = (tar / 12) *  Integer.parseInt(mes);
                n3 = (infra / 12) *  Integer.parseInt(mes);
                n4 = (rec / 12) *  Integer.parseInt(mes);

            }
            resultado2.close();

            float n = n1 + n2 + n3 + n4;


            if (idT != 6)
            {
                n5 = (n * descue) / 100;
            }
            else {
                n5 = n;
            }
            System.out.println(n5 + " total");


            connection.close();

        }catch (SQLException E){
            E.printStackTrace();
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }


    //omiti los métodos que son creados por android 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View v =  inflater.inflate(R.layout.fragment_fragment_calculadora, container, false);

        SpMeses = (Spinner) v.findViewById(R.id.spinnerMes);
        SpSituacion = (Spinner) v.findViewById(R.id.spinnerSituacion);
        Sptarifa = (Spinner) v.findViewById(R.id.spinnerTarifa);
        calcular = (Button) v.findViewById(R.id.btnCalcular);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy);
        Connection connection;
        String url;

        try
        {
            Class.forName("net.sourceforge.jtds.jdbc.Driver");
            url = "jdbc:jtds:sqlserver://SERVIDOR;databaseName=BdCalculadora;user=sa;password=1234";
            connection = DriverManager.getConnection(url);
            Statement estatuto = connection.createStatement();


            //cargar la situacion
            String query ="SELECT * FROM Situacion";
            ResultSet resultado = estatuto.executeQuery(query);
            while (resultado.next())
            {
                String descripcion = resultado.getString("descripcion");
                datos.add(descripcion);
            }
            resultado.close();

            //cargar la tarifas
            String query2 ="SELECT * FROM Tarifas";
            ResultSet resultado2 = estatuto.executeQuery(query2);
            while (resultado2.next())
            {
                String fech = resultado2.getString("año");
                datos2.add(fech);
            }
            resultado2.close();

            for (int x=1; x<=12; x++)
            {
                datos3.add(String.valueOf(x));
            }


            //spinner situacion
            ArrayAdapter adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, datos);
            SpSituacion.setAdapter(adapter);

            //spinner tarifas
            ArrayAdapter adapter2 = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, datos2);
            Sptarifa.setAdapter(adapter2);

            //spinner meses
            ArrayAdapter adapter3 = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, datos3);
            SpMeses.setAdapter(adapter3);

            connection.close();

        }catch (SQLException E)
        {
            E.printStackTrace();
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }

        SpSituacion.setOnItemSelectedListener(this);
        SpMeses.setOnItemSelectedListener(this);
        Sptarifa.setOnItemSelectedListener(this);

        calcular.setOnClickListener(this);

        return v;
    }
}
    
asked by Monse 03.01.2018 в 06:16
source

2 answers

0

Try this. If you have a Fragment, that Fragment will have an onCreateView method that is where you have to "identify" the TextView and create them as global variables.

public class FragmentCalculadora extends Fragment implements View.OnClickListener, AdapterView.OnItemSelectedListener {


Spinner Sptarifa, SpSituacion, SpMeses;
Button calcular;

ArrayList<String> datos = new ArrayList<String>();
ArrayList<String> datos2 = new ArrayList<String>();
ArrayList<String> datos3 = new ArrayList<String>();

float cf, tar, infra, rec;
int descue;
float n1, n2, n3, n4, n5;

//Declaramos aquí los TextView
TextView cfija;
TextView tarifa;
TextView inf;
TextView recargo;
TextView total;

@Override
public void onClick(View v) {

    switch (v.getId())
    {
        case R.id.btnCalcular:




             System.out.println(n1); //tenia esto para ver si realmente estaba calculando los datos, que si lo hacia

            try {

                    System.out.println("Aqui genera el error");

                    cfija.setText(String.valueOf(n1));
                    tarifa.setText(String.valueOf(n2));
                    inf.setText(String.valueOf(n3));
                    recargo.setText(String.valueOf(n4));
                    total.setText(String.valueOf(n5));


            }catch (Exception e) {
                Toast.makeText(getContext(), "hey onclick! " + e.getMessage(), Toast.LENGTH_LONG).show();
            }

            break;
    }
}


@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
    int idT = 0;
    String situa = SpSituacion.getSelectedItem().toString();
    System.out.println(situa);

    String tari = Sptarifa.getSelectedItem().toString();
    System.out.println(tari);

    String mes = SpMeses.getSelectedItem().toString();
    System.out.println(mes);


    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

    StrictMode.setThreadPolicy(policy);
    Connection connection;
    String url;
    //mi conexion a una bd
    try
    {

        Class.forName("net.sourceforge.jtds.jdbc.Driver");
        url = "jdbc:jtds:sqlserver://SERVIDOR;databaseName=BdCalculadora;user=sa;password=1234"; 
        connection = DriverManager.getConnection(url);
        Statement estatuto = connection.createStatement();


        //cargar la situacion
        String query ="SELECT * FROM Situacion WHERE descripcion = '" + situa + "'";
        ResultSet resultado = estatuto.executeQuery(query);
        if (resultado.next())
        {
            descue = resultado.getInt("descuento");
            idT = resultado.getInt("idSituacion");
        }
        resultado.close();


        //cargar la tarifas
        String query2 ="SELECT * FROM Tarifas WHERE año = " + tari;
        ResultSet resultado2 = estatuto.executeQuery(query2);
        if (resultado2.next())
        {
            cf = resultado2.getFloat("cf");
            tar = resultado2.getFloat("tar");
            infra = resultado2.getFloat("infra");
            rec = resultado2.getFloat("recargos");

            n1= (cf / 12) *  Integer.parseInt(mes);
            n2 = (tar / 12) *  Integer.parseInt(mes);
            n3 = (infra / 12) *  Integer.parseInt(mes);
            n4 = (rec / 12) *  Integer.parseInt(mes);

        }
        resultado2.close();

        float n = n1 + n2 + n3 + n4;


        if (idT != 6)
        {
            n5 = (n * descue) / 100;
        }
        else {
            n5 = n;
        }
        System.out.println(n5 + " total");


        connection.close();

    }catch (SQLException E){
        E.printStackTrace();
    }catch (ClassNotFoundException e){
        e.printStackTrace();
    }catch (Exception e) {
        e.printStackTrace();
    }

}

@Override
public void onNothingSelected(AdapterView<?> parent) {

}


//omiti los métodos que son creados por android 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    View v =  inflater.inflate(R.layout.fragment_fragment_calculadora, container, false);

    SpMeses = (Spinner) v.findViewById(R.id.spinnerMes);
    SpSituacion = (Spinner) v.findViewById(R.id.spinnerSituacion);
    Sptarifa = (Spinner) v.findViewById(R.id.spinnerTarifa);
    calcular = (Button) v.findViewById(R.id.btnCalcular);

    //Instanciamos los objetos de los TextView
    cfija = (TextView) v.findViewById(R.id.txtCFCalculadora);
    tarifa = (TextView) v.findViewById(R.id.txtTarifaCalculadora);
    inf = (TextView) v.findViewById(R.id.txtInfraCalculadora);
    recargo = (TextView) v.findViewById(R.id.txtRecargoCalculadora);
    total = (TextView) v.findViewById(R.id.txtTotalCalculadora);

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

    StrictMode.setThreadPolicy(policy);
    Connection connection;
    String url;

    try
    {
        Class.forName("net.sourceforge.jtds.jdbc.Driver");
        url = "jdbc:jtds:sqlserver://SERVIDOR;databaseName=BdCalculadora;user=sa;password=1234";
        connection = DriverManager.getConnection(url);
        Statement estatuto = connection.createStatement();


        //cargar la situacion
        String query ="SELECT * FROM Situacion";
        ResultSet resultado = estatuto.executeQuery(query);
        while (resultado.next())
        {
            String descripcion = resultado.getString("descripcion");
            datos.add(descripcion);
        }
        resultado.close();

        //cargar la tarifas
        String query2 ="SELECT * FROM Tarifas";
        ResultSet resultado2 = estatuto.executeQuery(query2);
        while (resultado2.next())
        {
            String fech = resultado2.getString("año");
            datos2.add(fech);
        }
        resultado2.close();

        for (int x=1; x<=12; x++)
        {
            datos3.add(String.valueOf(x));
        }


        //spinner situacion
        ArrayAdapter adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, datos);
        SpSituacion.setAdapter(adapter);

        //spinner tarifas
        ArrayAdapter adapter2 = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, datos2);
        Sptarifa.setAdapter(adapter2);

        //spinner meses
        ArrayAdapter adapter3 = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, datos3);
        SpMeses.setAdapter(adapter3);

        connection.close();

    }catch (SQLException E)
    {
        E.printStackTrace();
    }catch (ClassNotFoundException e){
        e.printStackTrace();
    }catch (Exception e) {
        e.printStackTrace();
    }

    SpSituacion.setOnItemSelectedListener(this);
    SpMeses.setOnItemSelectedListener(this);
    Sptarifa.setOnItemSelectedListener(this);

    calcular.setOnClickListener(this);

    return v;
}
}
    
answered by 03.01.2018 / 10:33
source
0

Your error is that you are trying to reference your TextViews with the wrong view. In a fragment these should be referenced within one of the following methods

onCreateView()
onActivityCreated()


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    TextView textView = (TextView) getView().findViewById(R.id.textView);


    return inflater.inflate(R.layout.fragment_blank, container, false);


}


@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);


    TextView textView = (TextView) getActivity().findViewById(R.id.textView);

}

I recommend checking the life cycle of a Fragment

    
answered by 03.01.2018 в 18:48