Reputation: 27
I want to open four fragments from single activity and in First Fragment
- I am using EditText
to enter data
Second Fragment - getting contacts from device and selecting required contacts
Third Fragment - selecting date and time from date and time picker
Forth Fragment - getting other data.
How can I get all these data from fragments and display them into the ListView of their parent activity and save them in database.
Here are the files
public class DetailsActivity extends AppCompatActivity implements View.OnClickListener, DialogListener, DateDialogFragment.EditDialogListener {
private static final int PLACE_PICKER_REQUEST = 1;
private static final int GOOGLE_API_CLIENT_ID = 0;
private static final int PERMISSION_REQUEST_CODE = 100;
private Context mContext = this;
private Button bt_add, bt_notes, bt_invitees, bt_schedule, bt_location;
private EditText et_whatToDo;
private static final int ENTER_DATA_REQUEST_CODE = 1;
private Fragment mCurrentFragment;
private DatabaseHelper db_Helper;
private SQLiteDatabase database;
private CustomDetailsAdapter customAdapter;
private ListView lv_details;
TextView tvSchedule, tvInvitees, tvNotes, tvLocation;
TextView tvFrom, tvTo, tvReminder;
CheckBox cbBlock;
public static boolean blocked;
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.fragment_add_details);
db_Helper = new DatabaseHelper(mContext);
et_whatToDo = (EditText) findViewById(R.id.et_what_todo);
final InputMethodManager imgr = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imgr.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
et_whatToDo.requestFocus();
tvSchedule = (TextView) findViewById(R.id.tv_schedule);
tvInvitees = (TextView) findViewById(R.id.tv_invitees);
bt_add = (Button) findViewById(R.id.bt_add);
bt_notes = (Button) findViewById(R.id.bt_bottom_notes);
bt_invitees = (Button) findViewById(R.id.bt_bottom_invitees);
bt_schedule = (Button) findViewById(R.id.bt_bottom_schedule);
bt_location = (Button) findViewById(R.id.bt_bottom_location);
Bundle bundle = new Bundle();
if (bundle != null) {
}
bt_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final DatabaseHelper db = new DatabaseHelper(mContext);
final String taskName = et_whatToDo.getText().toString();
if (taskName.equalsIgnoreCase("") || taskName.equalsIgnoreCase(" ")) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
alertDialogBuilder.setMessage("Do you want to save your changes ?");
alertDialogBuilder.setCancelable(true);
alertDialogBuilder
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
popFragment();
}
});
alertDialogBuilder
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogYes, int id) {
//db.createTask(taskName);
final AlertDialog.Builder alert = new AlertDialog.Builder(mContext);
alert.setMessage("Please enter the task name!!!");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertYes = alert.create();
alertYes.show();
dialogYes.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
} else {
Log.i("Blocked Value before", Boolean.toString(blocked));
db.createTask(taskName, blocked);
finish();
}
}
});
bt_notes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Fragment notesfragment = new NotesFragment();
pushFragment("notes", notesfragment, true);
}
});
bt_invitees.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Fragment contactFragment = new ContactFragment();
pushFragment("contacts", contactFragment, true);
}
});
bt_schedule.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
/*FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment prev = getFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
DialogFragment newFragment = DateDialogFragment.newInstance();
newFragment.show(ft, "datedialog");*/
// custom dialog and set view
final Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.custom_alert);
tvFrom = (TextView) dialog.findViewById(R.id.tv_from_display);
tvTo = (TextView) dialog.findViewById(R.id.tv_to_display);
SimpleDateFormat dfDate_day = new SimpleDateFormat("EEE, MMM dd, yyyy | hh:mm aaa");
String dtFrom = "";
String dtTo = "";
Calendar c = Calendar.getInstance();
dtFrom = dfDate_day.format(c.getTime());
tvFrom.setText(dtFrom);
c.add(Calendar.MINUTE, 30);
dtTo = dfDate_day.format(c.getTime());
tvTo.setText(dtTo);
tvFrom.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Calendar cal = Calendar.getInstance(Locale.getDefault());
DateTimePickerDialog dp = new DateTimePickerDialog(mContext, cal, DetailsActivity.this, false);
dp.show();
}
});
tvTo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Calendar cal = Calendar.getInstance(Locale.getDefault());
DateTimePickerDialog dp = new DateTimePickerDialog(mContext, cal, DetailsActivity.this, false);
dp.show();
}
});
// Load Control
Button dialogButtonok = (Button) dialog.findViewById(R.id.buttonok);
Button dialogButtonexit = (Button) dialog.findViewById(R.id.buttonexit);
dialogButtonok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle b = new Bundle();
b.putString("fromTime", tvFrom.getText().toString());
b.putString("toTime", tvTo.getText().toString());
dialog.dismiss();
}
});
dialogButtonexit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
cbBlock = (CheckBox) dialog.findViewById(R.id.chb_block);
tvReminder = (TextView) dialog.findViewById(R.id.tv_reminder);
String first = "Remind me ";
String color = "<font color='#ffaa01'>30 minutes </font>";
String last = "before";
tvReminder.setText(Html.fromHtml(first + color + last));
cbBlock.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (cbBlock.isChecked()) {
tvReminder.setVisibility(View.VISIBLE);
} else {
tvReminder.setVisibility(View.GONE);
}
}
});
tvReminder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Reminder ", Toast.LENGTH_LONG).show();
}
});
}
});
MainActivity.mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
.addApi(Places.PLACE_DETECTION_API)
.build();
bt_location.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
PlacePicker.IntentBuilder intentBuilder = new PlacePicker.IntentBuilder();
Intent intent = intentBuilder.build(DetailsActivity.this);
startActivityForResult(intent, PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException
| GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
});
}
@Override
public void onClick(View view) {
}
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
private void AlertDialog() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getApplicationContext());
alertDialogBuilder.setTitle("Coming Soon...");
alertDialogBuilder
.setCancelable(false)
.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PLACE_PICKER_REQUEST
&& resultCode == Activity.RESULT_OK) {
final Place place = PlacePicker.getPlace(getApplicationContext(), data);
final CharSequence name = place.getName();
final CharSequence address = place.getAddress();
final CharSequence latLong = place.getLatLng().toString();
final CharSequence placedetails = place.toString();
String attributions = (String) place.getAttributions();
if (attributions == null) {
attributions = "";
}
tvLocation = (TextView) findViewById(R.id.tv_location);
tvLocation.setText(address);
} else if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
if (data != null) {
String value = data.getStringExtra("notes");
if (value != null) {
tvNotes.setText(value);
}
}
}
else {
super.onActivityResult(requestCode, resultCode, data);
}
}
@Override
public void onDialogResultSuccess(Object result) {
tvFrom.setText((String) result);
tvTo.setText((String) result);
cbBlock.isChecked();
}
@Override
public void onDialogResultFailed() {
}
@Override
public void updateResult(String inputText) {
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onResume() {
super.onResume();
}
public void popFragment() {
android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
if (manager.getBackStackEntryCount() >= 1) {
manager.popBackStack();
}
}
public void pushFragment(String tag, Fragment fragment, boolean addToBackStack) {
mCurrentFragment = fragment;
android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.ll_detail_fragment, fragment, tag);
if (addToBackStack)
transaction.addToBackStack(tag);
transaction.commit();
}
public void getValuesFromNotesFragment(String notes) {
tvNotes.setText(notes);
}
}
Fragment 1-
public class NotesFragment extends Fragment implements View.OnClickListener{
private View mCurView;
private EditText etNotes;
private Button btCancel, btDone;
public NotesFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mCurView = inflater.inflate(R.layout.fragment_notes, container, false);
super.onCreate(savedInstanceState);
etNotes = (EditText) mCurView.findViewById(R.id.et_notes);
etNotes.setSelection(etNotes.getText().length());
InputMethodManager imgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imgr.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
etNotes.requestFocus();
btCancel = (Button) mCurView.findViewById(R.id.bt_note_cancel);
btDone = (Button) mCurView.findViewById(R.id.bt_note_done);
btDone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Bundle bundle = new Bundle();
bundle.putString("notes", etNotes.getText().toString());
NotesFragment fragobj = new NotesFragment();
fragobj.setTargetFragment(fragobj, 1);
Intent intent = new Intent();
intent.putExtras(bundle);
getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, intent);
getFragmentManager().popBackStack();
}
});
return mCurView;
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onClick(View view) {
DetailsActivity detailsActivity = (DetailsActivity)getActivity();
detailsActivity.getValuesFromNotesFragment(etNotes.getText().toString());
}
}
Upvotes: 0
Views: 671
Reputation: 759
Pass your data from/to Fragments to/from your Activity using Interface
.
First of all, create an interface with some appropriate method to pass the data, e.g.: to pass the text entered into an EditText
from your Fragment to your Activity, let's declare an interface like:
public interface InputPassingInterface{
void passInput(String inputStr);
}
Let your DetailsActivity
implement the interface and over-ride the passInput(String inputStr)
method, inside where you'll get the entered text to play with:
public class DetailsActivity extends AppCompatActivity
implements View.OnClickListener, DialogListener, DateDialogFragment.EditDialogListener,
InputPassingInterface {
// all of your necessary codes ...
public void passInput(String inputStr){
// Now that you've got your required input-string, do whatever you wish ...
}
}
Finally, we've to tell your Fragment that there exists an interface to listen to the user-input, for which you've to get an instance of the interface inside the respective fragment & pass-data from the onClick
method for btDone
.
Though irrelevant to your problem, but please don't use constructor for Fragment, rather use static newInstance()
method as per the recommended practice.
Then over-ride the Fragment's onAttach
method to instantiate the interface. In a nutshell, the final skeleton of the Fragment may look like the following:
public NotesFragment extends Fragment{
private InputPassingInterface inpPassInterface;
public static NotesFragment newInstance(){
return new NotesFragment();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.inpPassInterface = (InputPassingInterface) context;
}
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_notes, container, false);
}
@Override
public View onViewCreated(View view, @Nullable Bundle b) {
// Instead of onCreateView,
// do all of your view-updates from this method
// for the sake of efficiency.
// ... all your view initialization codes go here
btDone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(inpPassInterface!=null)
inpPassInterface.passInput(
etNotes.getText().toString()
);
}
});
}
}
Upvotes: 0
Reputation: 3688
You can try this,
Create Interface
public interface DataParsingInterface {
void onDoneClicked(String data);
}
Set note value once button clicked
btDone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DataParsingInterface dataParsingInterface = (DataParsingInterface ) getActivity();
dataParsingInterface.onDoneClicked(etNotes.getText().toString());
}
});
Implement interface in your activity
public class DetailsActivity extends AppCompatActivity implements DataParsingInterface {
@Override
protected void onDoneClicked(String data) {
// save data
}
}
Upvotes: 0