Nullpointer Exception error when bringing Fragment data

Asked

Viewed 90 times

1

I have a Nullpointerexception error when trying to return data from a Fragment. NPE error is right on this line:

String comentarioFoto = fragment_obj.campoComentarioFoto.getText().toString();

Check my Activity code:

public class LayoutActivity extends SherlockFragmentActivity {

     Fragment1 fragment_obj;

    private static final int SELECT_PICTURE = 1;
    private String selectedImagePath;

    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;

    private WrapData wd;
    private String answer;

    File caminhoFoto;
    File caminhoVideo;
    VideoView videoview;
    Spinner campoDepartamento;

    Button btnenviaVideo;
    Button btnenviaFoto;

    private String[] departamentoNome = new String[]{"Assistência Social", "Administração", "Agricultura", "Educação", "Finanças", 
            "Indústria Comércio e Turismo", "Planejamento e Urbanismo", "Transportes", "Obras e Serviços Públicos e Urbanos"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ActionBar ab = getSupportActionBar();
        ab.setDisplayHomeAsUpEnabled(true);

        /* Variáveis dos botões do campo foto e Video */

        btnenviaFoto = (Button) findViewById(R.id.btn_salvarFoto);
        btnenviaVideo = (Button) findViewById(R.id.btn_salvarVideo);

        /* Recupera os dados do Fragment */

        Fragment1 fragment_obj = (Fragment1)getSupportFragmentManager().findFragmentById(R.id.containerFragment);
        String comentarioFoto = fragment_obj.campoComentarioFoto.getText().toString();
        System.out.println(comentarioFoto);


    }
}

Fragment code:

package br.com.example.souprogresso;

// FRAGMENTO RESPONSAVEL PELO LAYOUT DE FOTO

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.support.v4.app.Fragment;


public class Fragment1 extends Fragment {

    EditText campoComentarioFoto;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.layout_fragment_1, container, false);

        campoComentarioFoto = (EditText) rootView.findViewById(R.id.edt_comentarioFoto);
        //String comentarioFoto = campoComentarioFoto.getText().toString();

        return rootView;
    }

}

XML of Fragment:

<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:id="@+id/containerFragment"
     >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            >

            <ImageView
                android:id="@+id/img_camera"
                android:layout_width="match_parent"
                android:layout_height="120dp"
                android:background="#000"
                android:src="@drawable/bg"/>

            <Button
                android:id="@+id/btn_tirarFoto"
                android:layout_width="match_parent"
                android:layout_height="45dp"
                android:onClick="tirarFoto"
                android:text="Tirar Foto" />

            <Button
                android:id="@+id/btn_capturaFoto"
                android:layout_width="match_parent"
                android:layout_height="45dp"
                android:onClick="selecionarFoto"
                android:text="Capturar Foto do Celular" />

            <Button
                android:id="@+id/btn_abrirMapa"
                android:layout_width="match_parent"
                android:layout_height="45dp"
                android:text="Buscar Localização" />


            <TextView
                android:text="Digite um Comentário"
                android:textSize="15sp"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:paddingLeft="15dp"
                android:textColor="#000"
                />

            <EditText
                android:id="@+id/edt_comentarioFoto"
                android:layout_width="match_parent"
                android:layout_height="72dp"
                android:background="#FFF"
                android:ems="10"
                android:inputType="textMultiLine"
                android:hint="Digite um comentário"
                 />


            <Button
                android:id="@+id/btn_salvarFoto"
                android:layout_width="match_parent"
                android:layout_height="65dp"
                android:onClick="salvarBDFoto"
                android:text="Enviar Foto"
                />

        </LinearLayout>

</ScrollView>
  • guy is really weird this mistake. I can’t fix it. He just doesn’t get the values I try to pass

1 answer

1

We’re assuming you declared Fragment in the Activity xml, okay? Because if you haven’t, Fragment is not yet added to Activity.

The second point is that Fragment may not be added to Activity where you are trying to get the value of the field.

So, you can override this method to know the right time to do this operation:

 @Override
    public void onAttachFragment(Fragment fragment) {
        super.onAttachFragment(fragment);

        if(fragment instanceof Fragment1){
            ((Fragment1)fragment).campoComentarioFoto.getText().toString();
        }
    }

This code doesn’t make much sense to me, but only for you to understand what might be going on in your case.

Browser other questions tagged

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