Error while extracting fragmented Edittext data using a Helper class

Asked

Viewed 105 times

0

I am trying to get the data of an Edittext that is in a fragment with the help of a Helper class, to later save in the database, but the following error is shown in the Androidstudio Bugger:

Although I have not yet been able to solve the root problem, I have already used the tips that were given me in the first question I had asked, as the use of the ternary operator that I was unaware of.

FATAL EXCEPTION: main
              Process: com.example.cabral.irriga, PID: 28163
              java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
                  at com.example.cabral.irriga.TimerHelper.pegaInfoDaIrrigacaoTimer(TimerHelper.java:38)
                  at com.example.cabral.irriga.TimerFragment$1.onClick(TimerFragment.java:90)
                  at android.view.View.performClick(View.java:5639)
                  at android.view.View$PerformClick.run(View.java:22391)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6095)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

The Helper class is as follows:

package com.example.cabral.irriga;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.widget.EditText;

import com.example.cabral.irriga.model.Timer;

import java.util.Calendar;

import static com.example.cabral.irriga.R.layout.fragment_manual;

public class TimerHelper{

private Timer timer;
private EditText etTempoDeFuncionamento;

public TimerHelper(FragmentActivity timerFragment)
{
    etTempoDeFuncionamento = (EditText) timerFragment.findViewById(R.id.etTempoDeFuncionamento);
    timer = new Timer();
}

public TimerHelper(ManualFragment manualFragment) {

           timer = new Timer();
}
public Timer pegaInfoDaIrrigacaoTimer()
{
    //Timer timer = new Timer();
    timer.setDuracao(etTempoDeFuncionamento.getText().toString());
    timer.setTipo("Regressivo");
    timer.setDataHoraDefinicao(calculaDataHoraAtual());
    return timer;
}

public Timer pegaInfoDaIrrigacaoManual() {
    Timer timer = new Timer();
    timer.setTipo("Manual");
    timer.setDataHoraDefinicao(calculaDataHoraAtual());
    return timer;
}
public void alteraTimer(Timer timer)
{
    timer.setId(timer.getId());
    timer.getDataHoraDefinicao();
    timer.setDataHoraDesligamento(calculaDataHoraAtual());
    timer.setStatus("concluido");
}

public String calculaDataHoraAtual(){
    Calendar c = Calendar.getInstance();
    int dia = c.get(Calendar.DAY_OF_MONTH);
    int mes = c.get(Calendar.MONTH);
    int ano = c.get(Calendar.YEAR);
    int hora = c.get(Calendar.HOUR_OF_DAY);
    int minuto = c.get(Calendar.MINUTE);
    int segundo = c.get(Calendar.SECOND);
    String strDia, strMes, strHora, strAno, strMinuto, strSegundo;

    strDia = (dia < 10 ? "0"+String.valueOf(dia): String.valueOf(dia));

    strMes = (mes < 10 ? "0"+String.valueOf(mes): String.valueOf(mes));

    strHora = (hora < 10 ? "0"+String.valueOf(hora): String.valueOf(hora));

    strMinuto = (minuto < 10 ? "0"+String.valueOf(minuto): String.valueOf(minuto));

    strSegundo = (segundo < 10 ? "0"+String.valueOf(segundo): String.valueOf(segundo));

    strAno = String.valueOf(ano);
    return strDia + "/" + strMes + "/" + strAno + " - " + strHora + ":" + strMinuto + ":" +strSegundo;
}

}

And the fragment that I’m trying to extract the information is as follows::

package com.example.cabral.irriga;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Handler;

import com.example.cabral.irriga.dao.TimerDAO;
import com.example.cabral.irriga.model.Timer;

import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.logging.LogRecord;


/**
 * A simple {@link Fragment} subclass.
 */
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint("NewApi")
public class TimerFragment extends Fragment {

    CounterClass timer = new CounterClass(0,0);
    public TimerHelper helper;

    public TimerFragment() {

        // Required empty public constructor
    }
    Button btnAplicarTempo, btnDesligarTimer;
    EditText etTempoDeFuncionamento;
    TextView txtTempoRestante;
    long minute;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_timer, container, false);
        btnAplicarTempo = (Button)view.findViewById(R.id.btnAplicarTempo);
        btnDesligarTimer = (Button)view.findViewById(R.id.btnDesligarTimer);
        etTempoDeFuncionamento = (EditText)view.findViewById(R.id.etTempoDeFuncionamento);
        txtTempoRestante = (TextView)view.findViewById(R.id.txtTempoRestante);

        helper = new TimerHelper(this.getActivity());

        btnAplicarTempo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                String tempo = etTempoDeFuncionamento.getText().toString();
                if(tempo.isEmpty())
                {
                    Toast.makeText(getActivity(), "Digite o tempo de funcionamento!", Toast.LENGTH_LONG).show();
                }
                else
                {
                    minute = Integer.parseInt(tempo);
                    String strTime;
                    if(minute < 10)
                    {
                        strTime = "00:0"+minute+":00";
                    }
                    else
                    {
                        strTime = "00:"+minute+":00";
                    }
                    txtTempoRestante.setText(strTime);
                    minute = (minute*60)*1000;
                    timer = new CounterClass(minute, 1000);
                    timer.start();

                    tempo = "?Tempo"+tempo;

                    Timer timer = helper.pegaInfoDaIrrigacaoTimer();
                    TimerDAO dao = new TimerDAO(getActivity());
                    dao.salva(timer);

                    ((MainActivity)getActivity()).solicita(tempo);
                    etTempoDeFuncionamento.setText("");
                }

            }
        });


        btnDesligarTimer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                timer.cancel();
                txtTempoRestante.setText("00:00");
                ((MainActivity)getActivity()).solicita("Desligar");
            }
        });
        return view;
    }

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @SuppressLint("NewApi")
    public class CounterClass extends CountDownTimer {
        public CounterClass(long millisInFuture, long countDownInterval){
            super(millisInFuture, countDownInterval);
        }

        @TargetApi(Build.VERSION_CODES.GINGERBREAD)
        @SuppressLint("NewApi")
        @Override
        public void onTick(long millisUntilFinished) {
            long millis = millisUntilFinished;
            String hms = String.format("%02d:%2d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
                    TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
                    TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
            System.out.println(hms);
            Log.e("TAG", hms);
            txtTempoRestante.setText(hms);
        }

        @Override
        public void onFinish() {
            txtTempoRestante.setText("Contador finalizado!");
            ((MainActivity)getActivity()).solicita("Desligar");
        }

    }

}

Emphasizing that the piece of code where the Debugger is signaling the error is as follows in the Helper class:

public Timer pegaInfoDaIrrigacaoTimer()
{
    timer.setDuracao(etTempoDeFuncionamento.getText().toString());
    timer.setTipo("Regressivo");
    timer.setDataHoraDefinicao(calculaDataHoraAtual());
    return timer;
}

I did practically the same thing to extract data from another fragment that does not have Edittext and worked perfectly, but for this one is not working.

I don’t know what to do to fix the problem.

I don’t have much experience in this area, so if you notice anything bizarre please tell me. I’m open to criticism in the code.

Could someone please help me?

  • it would not be easier to send edittext instead of the whole fragment?

1 answer

0

Within your Helper class, you need to instantiate Edittext. That’s why it’s returning Null. And when you try to access the gettext method of something Null, the App pops.

  • 1

    I understood the note but still do not know how to instantiate only Edittext. I should not instantiate the whole fragment?

  • @Rodrigocabral when you start the Helper, instead of going to getActivity, you can pass the View: Instead of being like this: helper = new Timerhelper(this.getActivity()); Be like this: View = Inflater.inflate(R.layout.fragment_timer, container, false); helper = new Timerhelper(view); .

  • If it works, vote yes ai!

  • 1

    Dude, it worked perfectly! Thank you so much! Now I get what you mean. I can work directly with the view.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.