Capie Capie - 28 days ago 18
Android Question

Activity crash (android fragments)

Im started today wth fragments on android(till now i only used activities) and I get a crash after running the app(actually it doesnt even launch).

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


/**
* A simple {@link Fragment} subclass.
*/
public class MainFragment extends Fragment {


public MainFragment() {
// Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
init();//----> PROBLEM HERE
return inflater.inflate(R.layout.fragment_main, container, false);

}


public TextView login;
/** Called when the user clicks link for Login/Register on right corner of the app*/
public void init() {
login=(TextView) getView().findViewById(R.id.textView11_linkRegister);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//intent means what i want to do'
Intent openLoginForm = new Intent(getActivity(),Login.class);
startActivity(openLoginForm);
}
});
}


}


I made the
Init()
function andeverything worked good till i tried to call it on
onCreateView()
I know the problem must be the way I call that function.
I would appreciate any help.

THanks.

Answer

You can't access a view that does not yet exist, rewrite your code like this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_main,container,false);
    init(v);//----> PROBLEM HERE
    return v;

}


public TextView login;
/** Called when the user clicks link for Login/Register on right corner of the app*/
public void init(View v) {
    login=(TextView) v.findViewById(R.id.textView11_linkRegister);
    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //intent means what i want to do'
            Intent openLoginForm = new Intent(getActivity(),Login.class);
            startActivity(openLoginForm);
        }
    });
}