For some reason my android application will not execute when a the ADD button is clicked.
I am using fragments Can you please help me and lead me in the right direction. When I click the
ADD button, nothing happens, not even the first Toast statement when the fields are empty
public class AthleteCreation extends Fragment implements View.OnClickListener{
Communicator communicator;
Button btnAdd;
EditText editFirstName, editLastName, editAge, editTier;
public AthleteCreation() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_athlete_creation, container, false);
final List<String> genderList=new ArrayList<String>();
genderList.add("Male");
genderList.add("Female");
Spinner s = (Spinner) view.findViewById(R.id.spinnerGender);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(), R.layout.support_simple_spinner_dropdown_item, genderList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(dataAdapter);
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
public void initializeVariables(){
btnAdd = (Button) getActivity().findViewById(R.id.btnAdd);
editFirstName = (EditText) getActivity().findViewById(R.id.editFirstName);
editLastName = (EditText) getActivity().findViewById(R.id.editLastName);
editAge = (EditText) getActivity().findViewById(R.id.editAge);
editTier = (EditText) getActivity().findViewById(R.id.editTier);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initializeVariables();
btnAdd.setOnClickListener(this);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnAdd:
Athlete athlete = new Athlete();
if(editFirstName.getText().length() == 0 || editLastName.getText().length() == 0
|| editAge.getText().length() == 0 || editTier.getText().length() == 0) {
Toast.makeText(getActivity(), "Fill in all fields!", Toast.LENGTH_SHORT).show();
}
else{
athlete.setFirstName(editFirstName.getText().toString());
athlete.setLastName(editLastName.getText().toString());
athlete.setAge(Integer.parseInt(editAge.getText().toString()));
athlete.setGender("");
athlete.setEvent("");
athlete.setTier(Integer.parseInt(editTier.getText().toString()));
Toast.makeText(getActivity(), athlete.toString(), Toast.LENGTH_LONG).show();
communicator = (Communicator) getActivity();
communicator.send(athlete);
}
break;
}
}
}
In initializeVariables() you are using getActivity().findViewById(R.id.foo) instead of using the Fragment's root view, that's probably the reason that you don't get a matching case in the switch statement.
Try:
getView().findViewById(R.id.foo);
In your initializeVariables() method, replace getActivity() by getView().
btnAdd = (Button) getView().findViewById(R.id.btnAdd);
Then btnAdd.setOnClickListener(this) will work.
Related
I know there are similar questions but I couldn't find an answer to solve my problem.
I have a DialogUpdateEmail which I want to be opened from ProfileFragment. In the dialog I want to enter my new email and send it to my ProfileFragment in order to change it also in the database.
ProfileFragment.java :
import androidx.fragment.app.Fragment;
public class ProfileFragment extends Fragment implements SendInputEmail {
public static final int PROFILE_FRAGMENT = 1;
private static final String TAG = "ProfileFragment";
private TextView TVHello, TVUsernameMessage, TVusernameinfo, TVemailinfo, TVbirthdate;
public void sendInput(String input) {
Log.d(TAG, "sendInput: found incoming input: " + input);
TVemailinfo.setText(input);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_profile, container, false);
Button Bsignout = (Button) v.findViewById(R.id.signoutbutton);
Button Beditusername = (Button) v.findViewById(R.id.editusernamebutton);
Button Beditemail = (Button) v.findViewById(R.id.editemailbutton);
Beditemail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: opening email dialog");
DialogUpdateEmail dialog = new DialogUpdateEmail();
dialog.setTargetFragment(ProfileFragment.this,PROFILE_FRAGMENT);
dialog.show(getActivity().getFragmentManager(), "DialogUpdateEmail");
}
});
return v;
}
DialogUpdateEmail.java :
public class DialogUpdateEmail extends DialogFragment implements SendInputEmail {
private static final String TAG = "DialogUpdateEmail";
SendInputEmail mHost = (SendInputEmail)getTargetFragment();
public View onCreateView(final LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.popup, container, false);
EditText UpdateEmail = (EditText) view.findViewById(R.id.emailinfoupdate);
Button Beditemail = (Button) view.findViewById(R.id.updatesavebutton);
Button Bcancelemail = (Button) view.findViewById(R.id.updatecancelbutton);
Beditemail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: capturing input.");
String input = UpdateEmail.getText().toString();
Log.d(TAG, "input : "+input);
mHost.sendInput(input);
getDialog().dismiss();
}
});
return view ;
}
public void onAttach(Context context) {
super.onAttach(context);
try{
mHost = (SendInputEmail) getTargetFragment();
}catch (ClassCastException e){
Log.e(TAG, "onAttach: ClassCastException : " + e.getMessage() );
}
}
#Override
public void sendInput(String input) {
}
}
SendInputEmail Interface :
public interface SendInputEmail {
void sendInput(String input);
}
My problem is that I have an error when I try to use setTargetFragment in ProfileFragment. It says that Profile Fragment is not a Fragment, I really don't know why.
From doc in here :
public class DialogUpdateEmail extends DialogFragment {
private DialogEditListener listener;
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = requireActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
View view = inflater.inflate(R.layout.popup, null);
builder.setView(view);
EditText UpdateEmail = (EditText) view.findViewById(R.id.emailinfoupdate);
Button Beditemail = (Button) view.findViewById(R.id.updatesavebutton);
Button Bcancelemail = (Button) view.findViewById(R.id.updatecancelbutton);
Beditemail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
listener.onDialogEditClick(UpdateEmail.getText().toString());
DialogUpdateEmail.this.getDialog().dismiss();
}
}
});
Bcancelemail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogUpdateEmail.this.getDialog().cancel();
}
});
return builder.create();
}
public interface DialogEditListener {
void onDialogEditClick(String email);
}
public void setListener(DialogEditListener listener) {
this.listener = listener;
}
}
We send the email from the dialog to the fragment using the observer/listener pattern.
And in your ProfileFragment just implement DialogEditListener and subscribe it to listen for click button in the dialog like so:
public class ProfileFragment extends Fragment
implements SendInputEmail, DialogUpdateEmail.DialogEditListener {
public static final int PROFILE_FRAGMENT = 1;
private static final String TAG = "ProfileFragment";
private TextView TVHello, TVUsernameMessage, TVusernameinfo, TVemailinfo, TVbirthdate;
public void sendInput(String input) {
Log.d(TAG, "sendInput: found incoming input: " + input);
TVemailinfo.setText(input);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_profile, container, false);
Button Bsignout = (Button) v.findViewById(R.id.signoutbutton);
Button Beditusername = (Button) v.findViewById(R.id.editusernamebutton);
Button Beditemail = (Button) v.findViewById(R.id.editemailbutton);
Beditemail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: opening email dialog");
//show your dialog
DialogUpdateEmail dialogUpdateEmail = new DialogUpdateEmail();
dialogUpdateEmail.setListener(ProfileFragment.this);
dialogUpdateEmail.show(getActivity().getSupportFragmentManager(), "DialogUpdateEmail");
}
});
return v;
}
#Override
public void onDialogEditClick(String email) {
//use your email here
Toast.makeText(getContext(), "My email: " + email, Toast.LENGTH_SHORT).show();
}
}
I'm trying to implent the next code in Android Studio and it does not work.
I want to pass from a Fragment (GalleryFragment) to an Activity (postropa) with a button.
I have linked the botton with the function (BotonPulsado) and I don't know what is wrong (In the design view).
Design View
Code:
import (...)
public class GalleryFragment extends Fragment {
private GalleryViewModel galleryViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
galleryViewModel =
ViewModelProviders.of(this).get(GalleryViewModel.class);
View root = inflater.inflate(R.layout.fragment_gallery, container, false);
final TextView textView = root.findViewById(R.id.text_gallery);
galleryViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}
public void BotonPulsado(View view) {
Intent intent = new Intent(getContext(), postropa.class);
startActivity(intent);
}
}
You should create Button variŠ°ble as a class field.
private GalleryViewModel galleryViewModel;
Button button; <<-------
After that you need to define it in method onCreateView()
button = (Button) findViewById(R.id.button2);
And set onClickListener() on this button to handle the call.
There you must call the method that starts the activity.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BotonPulsado();
}
});
Your final code:
import (...)
public class GalleryFragment extends Fragment {
private GalleryViewModel galleryViewModel;
Button button;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
galleryViewModel =
ViewModelProviders.of(this).get(GalleryViewModel.class);
View root = inflater.inflate(R.layout.fragment_gallery, container, false);
final TextView textView = root.findViewById(R.id.text_gallery);
galleryViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
button = (Button) findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BotonPulsado();
}
});
return root;
}
public void BotonPulsado() {
Intent intent = new Intent(getContext(), postropa.class);
startActivity(intent);
}
}
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.
This is my code:
public class MainActivity extends AppCompatActivity {
ListView listView ;
ArrayList<String> StoreContacts, id;
Bundle bundle;
ArrayAdapter<String> arrayAdapter ;
Cursor cursor;
Intent intent;
String name, phonenumber ;
public static final int RequestPermissionCode = 1 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.listview1);
StoreContacts = new ArrayList<String>();
id = new ArrayList<String>();
EnableRuntimePermission();
GetContactsIntoArrayList();
arrayAdapter = new ArrayAdapter<String>(
MainActivity.this,
R.layout.contact_items_listview,
R.id.textView, StoreContacts
);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
bundle =new Bundle();
/*SharedPreferences.Editor editor=getSharedPreferences("Suyash",MODE_PRIVATE).edit();
editor.putString("ID",id.get(i));
editor.apply();*/
intent = new Intent(MainActivity.this, SingleContact.class);
bundle.putString("ID",id.get(i));
intent.putExtra("ID",id.get(i));
startActivity(intent);
}
});
}
public void GetContactsIntoArrayList(){
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null, null, null);
while (cursor.moveToNext()) {
id.add(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID)));;
name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phonenumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
StoreContacts.add(name + " " + ":" + " " + phonenumber);
}
cursor.close();
}
public void EnableRuntimePermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(
MainActivity.this,
Manifest.permission.READ_CONTACTS))
{
Toast.makeText(MainActivity.this,"CONTACTS permission allows us to Access CONTACTS app", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(MainActivity.this,new String[]{
Manifest.permission.READ_CONTACTS}, RequestPermissionCode);
}
}
#Override
public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {
switch (RC) {
case RequestPermissionCode:
if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this,"Permission Granted, Now your application can access CONTACTS.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this,"Permission Canceled, Now your application cannot access CONTACTS.", Toast.LENGTH_LONG).show();
}
break;
}
}
}
on receiving end:
public class SingleContact extends AppCompatActivity {
Bundle bundle=getIntent().getExtras();
//SharedPreferences preferences=getSharedPreferences("Suyash",MODE_PRIVATE);
0String string = bundle.getString("ID",null);
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
button= (Button) findViewById(R.id.button);
//string= bundle.getString("ID");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(SingleContact.this, string, Toast.LENGTH_SHORT).show();
}
});
}
}
the crashes when I click the item.
i have tried sharedpreference too, it does the same thing. im using android studio 2.3.3.
anyone suggest what i should do.
please help
You can not get the bundle before onCreate(). Write your code something like below and it will resolve your error.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
// Your bundle code.
Bundle bundle=getIntent().getExtras();
String string = bundle.getString("ID",null);
}
Probably wrong initialization of bundle data in SingleContact Activity, you should initialise inside of onCreate method
public class SingleContact extends AppCompatActivity {
Bundle bundle;
String string;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
bundle = getIntent().getExtras()
button= (Button) findViewById(R.id.button);
string= bundle.getString("ID");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(SingleContact.this, string, Toast.LENGTH_SHORT).show();
}
});
}
}
i have created a custom class extending dialog fragment and im using a layout to inflate into this dialog now when i want to set my onclicklistener in main activity but it returns null point exception when im setting my on click listener heres my main activity and my dialog fragment :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button cancelDialog = (Button) findViewById(R.id.cancelDialogButton);
View.OnClickListener listenerDialog = new View.OnClickListener() {
#Override
public void onClick(View v) {
}
};
//this is where i get the null point exception
cancelDialog.setOnClickListener( listenerDialog );
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ViewGroup Addition = (ViewGroup) findViewById(R.id.activity_addition);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fm = getSupportFragmentManager();
DialogCards editNameDialogFragment = DialogCards.newInstance();
editNameDialogFragment.show(fm, "fragment_edit_name");
}
});
and now my costume class extending dialog fragment :
public class DialogCards extends DialogFragment {
public Dialog dialog;
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
// request a window without the title
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return dialog;
}
#Override
public void onResume() {
// Store access variables for window and blank point
Window window = getDialog().getWindow();
Point size = new Point();
// Store dimensions of the screen in `size`
Display display = window.getWindowManager().getDefaultDisplay();
display.getSize(size);
// Set the width of the dialog proportional to 75% of the screen width
window.setLayout((int) (size.x * 0.75), WindowManager.LayoutParams.WRAP_CONTENT + 20);
window.setGravity(Gravity.CENTER);
// Call super onResume after sizing
super.onResume();
}
public DialogCards() {
}
public static DialogCards newInstance() {
DialogCards frag = new DialogCards();
Bundle args = new Bundle();
frag.setArguments(args);
return frag;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.carddialog, container);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getDialog().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
}}
You can replace this method in you DialogCards class
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getDialog().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
final Button cancelDialog = (Button)view.findViewById(R.id.cancelDialogButton);
View.OnClickListener listenerDialog = new View.OnClickListener() {
#Override
public void onClick(View v) {
}
};
cancelDialog.setOnClickListener( listenerDialog );
}}