在单个活动的列表视图中显示多个片段数据并将其保存到sqlite数据库

时间:2016-10-13 09:26:41

标签: android android-fragments android-activity

我想在单个活动和第一个Fragment中打开四个片段 - 我正在使用EditText输入数据 第二片段 - 从设备获取联系人并选择所需的联系人 第三片段 - 从日期和时间选择器中选择日期和时间 Forth Fragment - 获取其他数据。

如何从片段中获取所有这些数据并将其显示到其父活动的ListView中,并将它们保存在数据库中。

以下是文件

public class DetailsActivity extends AppCompatActivity实现了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);
}

}

片段1 -

public class NotesFragment extends Fragment实现了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());
}

}

2 个答案:

答案 0 :(得分:0)

你可以试试这个,

  1. 创建界面

    public interface DataParsingInterface {
       void onDoneClicked(String data);
    }
    
  2. 点击一次按钮后设置音符值

    btDone.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
            DataParsingInterface  dataParsingInterface  = (DataParsingInterface ) getActivity();
            dataParsingInterface.onDoneClicked(etNotes.getText().toString());
          }
    });
    
  3. 在您的活动中实施界面

    public class DetailsActivity extends AppCompatActivity implements DataParsingInterface {
    
    @Override
    protected void onDoneClicked(String data) {
    
        // save data
    
     }
    }
    

答案 1 :(得分:0)

使用Interface将数据从/向片段传入/传出片段。

首先,使用一些适当的方法创建一个接口来传递数据,例如:将从Fragment中输入的EditText文本传递给您的Activity,让我们声明一个如下界面:

public interface InputPassingInterface{
    void passInput(String inputStr);
}

让您的DetailsActivity实施界面并覆盖passInput(String inputStr)方法,在您获取输入文字的位置:

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 ...
    }
}

最后,我们告诉你的Fragment存在一个用于监听用户输入的接口,你可以在其中获得相应片段内的接口实例。&amp;来自onClick的{​​{1}}方法的传递数据。

虽然与您的问题无关,但请不要使用Fragment的构造函数,而是按照推荐的做法使用静态btDone方法。
然后覆盖Fragment&#39; s newInstance()方法实例化接口。简而言之,片段的最终骨架可能如下所示:

onAttach