This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am building a signUp page in which i want a date picker but whenever i click on User Fragment to open Sign up Page then the app crashes, and the error is nullPointerException in EditText. Please Help me to solve it.
Here is the Code of UserFragment.java
public class UserFragment extends Fragment {
public EditText et_Date;
public static final int REQUEST_CODE = 11;
String selectedDate;
private OnFragmentInteractionListener mListener;
public DatePickerDialog.OnDateSetListener setListener;
View view;
public UserFragment() {
}
public static UserFragment newInstance() {
UserFragment fragment = new UserFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.adduser_fragment, container, false);
et_Date = (EditText) view.findViewById(R.id.etdate);
final FragmentManager fm = ((AppCompatActivity)getActivity()).getSupportFragmentManager();
et_Date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AppCompatDialogFragment newFragment = new DatePickerFragment();
newFragment.setTargetFragment(UserFragment.this,REQUEST_CODE);
newFragment.show(fm, "DatePicker");
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK){
selectedDate = data.getStringExtra("SelectedDate");
et_Date.setText(selectedDate);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if(context instanceof OnFragmentInteractionListener){
mListener= (OnFragmentInteractionListener) context;
}else{
throw new RuntimeException(context.toString()+"must implement OnFragmentInterationListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
public void onFragmentInteraction(Uri uri);
}
}
Your editText with id etdate is actually in layout adduser_fragment? This error may be because of view is in another layout(and you forgot that). Sorry for answer, I don't have enough reputation to post comment.
Related
I have two EditText. First, use to open DatePicker, and the second use to open TimePicker.
I have created DialogFragment for two-component. Both works.All in the Fragment.
This is my Fragment. When select DatePicker the value of Time disappears and When I select TimePicker Date also disappear. I have already saveInstance. Pls, help!! Thx
DialogFragment datePicker;
TimePickerFragment timePicker;
EditText departureEdt;
EditText departureTimeEdt;
String selectedDate;
String selectedTime;
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
if (outState != null) {
outState.putString("selectedDate", selectedDate);
outState.putString("selectedTime", selectedTime);
}
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
selectedDate = savedInstanceState.getString("selectedDate");
selectedTime = savedInstanceState.getString("selectedTime");
departureEdt.setText(selectedDate);
departureTimeEdt.setText(selectedTime);
}
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final FragmentManager fm = ((AppCompatActivity) getActivity()).getSupportFragmentManager();
View view = inflater.inflate(R.layout.transportation_fragment, container, false);
departureEdt = view.findViewById(R.id.departure_date);
departureEdt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
datePicker = new DatePickerFragment();
datePicker.setTargetFragment(TransportationFragment.this, 1);
datePicker.show(fm, "datePicker");
}
});
departureTimeEdt = view.findViewById(R.id.departure_time);
departureTimeEdt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
timePicker = new TimePickerFragment();
timePicker.setTargetFragment(TransportationFragment.this, 1);
timePicker.show(fm, "timePicker");
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
// get date from string
selectedDate = data.getStringExtra("selectedDate");
selectedTime = data.getStringExtra("selectedTime");
// set the value of the editText
departureEdt.setText(selectedDate);
departureTimeEdt.setText(selectedTime);
}
}
}
I am trying to pass information from my alert dialog to my second fragment (I am using tabbed activity layout).
I want to pass information from alert dialog to fragment when I click on my ImageView, but my app keep crashing until I implement my interface inside MainActivity.java. My main mission here is to open alert dialog which contains several buttons. When I click first button I want to print "Test br 3" but it does not work inside my Fragment, it only works inside my MainActivity.java where method prints "Test br 2".
My Main Activity
public class MainActivity extends AppCompatActivity implements ExercisesAlertDialog.DataTransfer {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
#Override
public void ApplyData() {
System.out.println("Test br 2");
}
My Fragment
public class Frag2 extends Fragment implements ExercisesAlertDialog.DataTransfer {
ImageView plusbtn;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag2, container, false);
plusbtn = (ImageView) v.findViewById(R.id.plusbtn);
plusbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ExercisesDialog();
}
});
return v;
}
public void ExercisesDialog()
{
ExercisesAlertDialog exercisesAlertDialog = new ExercisesAlertDialog();
exercisesAlertDialog.show(getFragmentManager(), "Exercises Dialog");
}
#Override
public void ApplyData() {
System.out.println("Test br 3");
}
My Alert Dialog
public class ExercisesAlertDialog extends AppCompatDialogFragment {
ImageButton one, two;
private DataTransfer listener;
public int first;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.workout_custom_menu, null);
builder.setView(v);
builder.setTitle("Choose your Workout");
builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dismiss();
}
});
one = (ImageButton) v.findViewById(R.id.first);
two = (ImageButton) v.findViewById(R.id.second);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
first = 1;
if(first ==1)
{
listener.ApplyData();
}
}
});
return builder.create();
}
public interface DataTransfer
{
void ApplyData();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
listener = (DataTransfer) context;
}
catch (ClassCastException e)
{
throw new ClassCastException(toString() + "Must implement DataTransfer");
}
}
}
I changed getChildFragmentManager() instead of getFragmentManager() in the show() call. Second thing is onAttach() to listener = (DataTransfer) getParentFragment(); instead of context.
I created my test project where i code to communicate between two fragments but actully I want to access activity from fragment.
Here is code to connect fragment to fragment, its working absolutely right without any error but now i want to change this code to connect activity from fragment instead of fragment to fragment communication.
So Please change this code to access activities from fragment. I stuck on this issue for than a week.So Guys please resolve this.
here is my mainaactivity:
public class MainActivity extends AppCompatActivity implements FragmentA.FragmentAListener, FragmentB.FragmentBListener {
private FragmentA fragmentA;
private FragmentB fragmentB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentA = new FragmentA();
fragmentB = new FragmentB();
getSupportFragmentManager().beginTransaction()
.replace(R.id.container_a, fragmentA)
.replace(R.id.container_b, fragmentB)
.commit();
}
#Override
public void onInputASent(CharSequence input) {
fragmentB.updateEditText(input);
}
#Override
public void onInputBSent(CharSequence input) {
fragmentA.updateEditText(input);
}
Here is my FragmentA.java:
public class FragmentA extends Fragment {
private FragmentAListener listener;
private EditText editText;
private Button buttonOk;
public interface FragmentAListener {
void onInputASent(CharSequence input);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_a, container, false);
editText = v.findViewById(R.id.edit_text);
buttonOk = v.findViewById(R.id.button_ok);
buttonOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CharSequence input = editText.getText();
listener.onInputASent(input);
}
});
return v;
}
public void updateEditText(CharSequence newText) {
editText.setText(newText);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof FragmentAListener) {
listener = (FragmentAListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement FragmentAListener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
}
Here is my FragmentB.java:
public class FragmentB extends Fragment {
private FragmentBListener listener;
private EditText editText;
private Button buttonOk;
public interface FragmentBListener {
void onInputBSent(CharSequence input);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_b, container, false);
editText = v.findViewById(R.id.edit_text);
buttonOk = v.findViewById(R.id.button_ok);
buttonOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CharSequence input = editText.getText();
listener.onInputBSent(input);
}
});
return v;
}
public void updateEditText(CharSequence newText) {
editText.setText(newText);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof FragmentBListener) {
listener = (FragmentBListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement FragmentBListener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
}
Here is my Fertilizers.java file which i want to access from FragmentA.:
public class Fertilizers extends AppCompatActivity {
RecyclerView mRecyclerView;
List<FertilizerData> myFertilizersList;
FertilizerData mFertilizersData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fertilizers);
mRecyclerView = (RecyclerView)findViewById(R.id.recyclerView);
GridLayoutManager gridLayoutManager;
gridLayoutManager = new GridLayoutManager(Fertilizers.this, 1);
mRecyclerView.setLayoutManager(gridLayoutManager);
myFertilizersList = new ArrayList<>();
mFertilizersData = new FertilizerData("Urea Fertilizer","Urea is a concent","Rs.1900",R.drawable.urea);
myFertilizersList.add(mFertilizersData);
myFertilizersList.add(mFertilizersData); }
}
please write here a block of code to call Fertilzers Activity from FragmentA, I,ll be very thankful to you.
Calling getActivity() in your fragment gives you the calling activity so if MainActivity started your fragment then you would do
(MainActivity(getActivity())).something_from_your_main_activity
Solution found by itself regarding this issue.
FragmentHome.java class should look like this:
public class FragmentHome extends Fragment {
private Button button;
public FragmentHome(){
}
public interface OnMessageReadListener
{
public void onMessageRead(String message);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home, container, false);
button = (Button)v.findViewById(R.id.bn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), Fertilizers.class);
intent.putExtra("some"," some data");
startActivity(intent);
}
});
return v;
}
}
FertilizersActivity.java should look like this:
public class Fertilizers extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fertilizers);
Bundle bundle = getIntent().getExtras();
if (bundle != null){
if(bundle.getStringArrayList("some") !=null){
Toast.makeText(getApplicationContext(),"data:" + bundle.getStringArrayList("some"),Toast.LENGTH_LONG).show();
}
}
}
}
I want to pass data from Activity to DialogFragment using interface. I have succeeded when pass data from Adapter to Fragment with code some like bellow
But i have a error java.lang.NullPointerException with code bellow when i pass data from Activity to DialogFragment
I have a Activity
public class TheLoaiActivity extends AppCompatActivity {
RecyclerView recyclerView, recyclerView1;
AdapterTruyen adapterTruyen;
List<modelTruyen> listTruyen;
List<modelKinds> listKinds;
LinearLayout lnTheloai;
private OnClickIntent mListener;
int id;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.kinds_layout);
addControl();
id = getIntent().getIntExtra(AdapterKinds.KEY_INTENT_DATA_KINDS,0);
Toast.makeText(this, ""+id, Toast.LENGTH_SHORT).show();
loadData();
loadView(id);
addEvents();
}
private void addEvents() {
final FragmentManager fragmentManager = getFragmentManager();
final TheLoaiDialogFragment dialogFragment = new TheLoaiDialogFragment();
lnTheloai.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.onClick(listKinds); //ERROR at here
dialogFragment.show(fragmentManager,"list_kind");
}
});
}
public interface OnClickIntent {
void onClick(List<modelKinds> list);
}
// set the listener. Must be called from the fragment
public void setListener(OnClickIntent listener) {
this.mListener = listener;
}
and DialogFragment
public class TheLoaiDialogFragment extends DialogFragment {
RecyclerView recyclerView;
AdapterKinds adapterKinds;
List<modelKinds> listKinds;
TextView txtCancel;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.kinds_fragment_layout,container,false);
recyclerView = view.findViewById(R.id.rv_diaglogFragmentKinds);
txtCancel = view.findViewById(R.id.txt_camcelKindsFragment);
TheLoaiActivity theLoaiActivity = new TheLoaiActivity();
theLoaiActivity.setListener(new TheLoaiActivity.OnClickIntent() {
#Override
public void onClick(List<modelKinds> list) {
Log.d(TAG, "onClick: "+ list.size());
}
});
When i pass data from Activity to DiaglogFragment i have a problem this is
FATAL EXCEPTION: main
Process: com.abba.story, PID: 18048
java.lang.NullPointerException: Attempt to invoke interface method 'void com.abba.kinds.TheLoaiActivity$OnClickIntent.onClick(java.util.List)' on a null object reference
What should i do?
Can you explain for me about this error ?
In the fragment, replace:
TheLoaiActivity theLoaiActivity = new TheLoaiActivity();
with:
TheLoaiActivity theLoaiActivity=(TheLoaiActivity)getActivity();
To get a reference to the parent activity inside a Fragment you need to make the calls inside the onActivityCreated method. Before it, for example in onCreateView, the Activity does not exist and that's why you're getting the null pointer exception. Plus you're creating a NEW activity not getting a reference to the already existing Activity where the fragment is contained
Something like this:
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
TheLoaiActivity theLoaiActivity = (TheLoaiActivity)getActivity();
}
Try this it will work for sure
private void addEvents() {
final FragmentManager fragmentManager = getFragmentManager();
final TheLoaiDialogFragment dialogFragment = new TheLoaiDialogFragment();
lnTheloai.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//ERROR at here
dialogFragment.show(fragmentManager,"list_kind");
}
});
}
public interface OnClickIntent {
void onClick(List<modelKinds> list);
}
// set the listener. Must be called from the fragment
public void setListener(OnClickIntent listener) {
this.mListener = listener;
if(mListener !=null){
mListener.onClick(listKinds);
}
}
How con I get text from TextView in DialogFragment to MainActivity or how i make event in MainActivity when Button in DialogFragment clicked. pleas help me i tried like this in below:but it dose not work what is the problem.
public class MainActivity extends AppCompatActivity {
Button b; Button b2; String name;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
name = data.getStringExtra("name").toString();
Toast.makeText(MainActivity.this,name+ "", Toast.LENGTH_LONG).show();}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b=(Button)findViewById(R.id.b);
b=(Button)findViewById(R.id.b);
b2=(Button)findViewById(R.id.b2);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
b2.setText(name);}});}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mainmenu, menu);
return true;}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
FragmentManager manager = getFragmentManager();
fragment afr = new fragment();
afr.setTargetFragment(afr, 1);
afr.show(manager, "dialog");
return true;}}
class fragment extends DialogFragment {
View v; Intent intent; EditText t1; Button b1; String name;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment, container, false);
t1=(EditText) v.findViewById(R.id.t1);
b1=(Button) v.findViewById(R.id.b1);
intent = new Intent();
int resultCode = 1;
getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, intent);
getDialog().dismiss();
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name=t1.getText().toString();
intent.putExtra("name", name);
fragment.this.dismiss();
}}); return v;}}
You can use interfaces.
Declare interface in fragment and implement it in MainActivity.
https://developer.android.com/training/basics/fragments/communicating.html
In DialogFragment declare
public IDialogCallback {
void onTextWritted(String text);
void onDialogBtnClick()
}
Then declare field in Dialog:
OnDialogCallback mCallback
Later:
#Override
public void onAttach(Context context) {
super.onAttach(context);
mCallback = (ITailLiftCallback) context;
}
Now you can call mCallback.onTextWritted() or mCallback.onDialogBtnClick in DialogFragment. In first case you may put text from TextView and second - put it in OnClickListener of a button.
Then make MainActivity implements IDialogCallback and it is all! :)