从片段导航到活动

时间:2018-03-08 12:57:36

标签: java android android-fragments android-fragmentactivity

我知道这是一个经常被问到的问题,但在阅读了关于堆栈溢出的许多问题和解决方案之后,我无法找到解决问题的好方法。 我有一个片段,当用户按下AlertDialog的确定按钮但我的应用程序崩溃时,我想导航到主要活动。我无法找到我的代码有什么问题。 感谢您对先进的帮助。

我看不出我在这里做错了什么

 private void buildConfirmDialog() {

    AlertDialog.Builder confirmBuilder = new AlertDialog.Builder(getActivity());
    confirmBuilder.setTitle("Are you sure");
    confirmBuilder.setMessage("Are you sure you want to save the note");

    confirmBuilder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

            Log.d("Save Note", "Note title:" + title.getText() + "Note message:"
                    + message.getText() + "Note category:" + savedButtonCategory);

           Intent intent = new Intent(getActivity(), MainActivity.class);
           startActivity(intent);
        }
    });

    confirmBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

        }
    });

    confirmDialogObject = confirmBuilder.create();


}

这是我的片段

public class NoteEditFragment extends android.app.Fragment {

private ImageButton noteCatButton;
private EditText title, message;
private Note.Category savedButtonCategory;
private AlertDialog categoryDialogObject,confirmDialogObject;

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


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {


    View fragmentLayout = inflater.inflate(R.layout.fragment_note_edit, container, false);

    EditText title = fragmentLayout.findViewById(R.id.editNoteTitle);
    EditText message = (EditText) fragmentLayout.findViewById(R.id.editNoteMessage);
    noteCatButton = (ImageButton) fragmentLayout.findViewById(R.id.editNoteButton);
    Button savedButton = (Button) fragmentLayout.findViewById(R.id.saveNote);

    //populate widgets with note data
    Intent intent = getActivity().getIntent();
    title.setText(intent.getExtras().getString(MainActivity.title, ""));
    message.setText(intent.getExtras().getString(MainActivity.MESSAGE, ""));

    Note.Category notCat = (Note.Category) intent.getSerializableExtra(MainActivity.CATEGORY);
    noteCatButton.setImageResource(Note.categoryToDrawble(notCat));

    buildCategoryDialog();
    buildConfirmDialog();

    noteCatButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            categoryDialogObject.show();

        }
    });

    savedButton.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
            confirmDialogObject.show();

         }
    });

    return fragmentLayout;
}

private void buildCategoryDialog() {
    final String[] categories = new String[]
            {"Personal", "Technical", "Quote", "Financial"};
    AlertDialog.Builder categoryBuilder = new AlertDialog.Builder(getActivity());
    categoryBuilder.setTitle("Choose Note Type");

    categoryBuilder.setSingleChoiceItems(categories, 0, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int item) {
            categoryDialogObject.cancel();

            switch (item) {
                case 0:
                    savedButtonCategory = Note.Category.PERSONAL;
                    noteCatButton.setImageResource(R.drawable.images);
                    break;
                case 1:
                    savedButtonCategory = Note.Category.TECHNICHAL;
                    noteCatButton.setImageResource(R.drawable.t);
                    break;
                case 2:
                    savedButtonCategory = Note.Category.QUOTE;
                    noteCatButton.setImageResource(R.drawable.q);
                    break;
                case 3:
                    savedButtonCategory = Note.Category.FENANCE;
                    noteCatButton.setImageResource(R.drawable.f);
                    break;
            }

        }
    });

    categoryDialogObject = categoryBuilder.create();
}

private void buildConfirmDialog() {

    AlertDialog.Builder confirmBuilder = new AlertDialog.Builder(getActivity());
    confirmBuilder.setTitle("Are you sure");
    confirmBuilder.setMessage("Are you sure you want to save the note");

    confirmBuilder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

            Log.d("Save Note", "Note title:" + title.getText() + "Note message:"
                    + message.getText() + "Note category:" + savedButtonCategory);

           Intent intent = new Intent(getActivity(), MainActivity.class);
           startActivity(intent);
        }
    });

    confirmBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

        }
    });

    confirmDialogObject = confirmBuilder.create();


}


}

这是我的 MainActivity

public class MainActivity extends AppCompatActivity {

public static final String id = "ricom.gmail.com.notebook3.Identifier";
public static final String title = "ricom.gmail.com.notebook3.Title";
public static final String MESSAGE = "ricom.gmail.com.notebook3.Message";
public static final String CATEGORY = "ricom.gmail.com.notebook3.Category";
public static final String NOTE_FRAGMENT_TO_LOAD_EXTRA = "ricom.gmail.com.notebook3.Fragment_To_Load";

public enum FragmentToLaunch {VIEW, EDIT, CREATE}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    } else if (id == R.id.action_add_note) {
        Intent intent = new Intent(this, NoteDetailActivity.class);
        intent.putExtra(MainActivity.NOTE_FRAGMENT_TO_LOAD_EXTRA, FragmentToLaunch.CREATE);
        startActivity(intent);
        return true;


    }
    return super.onOptionsItemSelected(item);
}
}

崩溃报告

03-09 08:14:33.816 31586-31586 / ricom.gmail.com.myapplication12 E / AndroidRuntime:FATAL EXCEPTION:main                                                                                  过程:ricom.gmail.com.myapplication12,PID:31586                                                                                  java.lang.NullPointerException:尝试在空对象引用上调用虚方法'android.text.Editable android.widget.EditText.getText()'                                                                                      at ricom.gmail.com.myapplication12.NoteEditFragment $ 4.onClick(NoteEditFragment.java:121)                                                                                      在com.android.internal.app.AlertController $ ButtonHandler.handleMessage(AlertController.java:166)                                                                                      在android.os.Handler.dispatchMessage(Handler.java:106)                                                                                      在android.os.Looper.loop(Looper.java:164)                                                                                      在android.app.ActivityThread.main(ActivityThread.java:6494)                                                                                      at java.lang.reflect.Method.invoke(Native Method)                                                                                      在com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run(RuntimeInit.java:438)                                                                                      在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

它告诉我这里有错误

Log.d("Save Note", "Note title:" + title.getText() + "Note message:"
                        + message.getText() + "Note category:" + savedButtonCategory);

2 个答案:

答案 0 :(得分:0)

你只需要使用简单的意图..

 Intent i = new Intent(getActivity(), DetailActivity.class);
 getActivity().startActivity(i);

其实你用

  

getActivity()

获取附加片段的活动。(这是Intent()的第一个参数)

答案 1 :(得分:0)

public class NoteEditFragment extends android.app.Fragment {

private ImageButton noteCatButton;
private EditText title, message;
private Note.Category savedButtonCategory;
private AlertDialog categoryDialogObject,confirmDialogObject;

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


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {


    View fragmentLayout = inflater.inflate(R.layout.fragment_note_edit, container, false);
    //i replaced this one 
    /*
    EditText title = fragmentLayout.findViewById(R.id.editNoteTitle);
    EditText message = (EditText) fragmentLayout.findViewById(R.id.editNoteMessage);
    */
    // with that one
    title = fragmentLayout.findViewById(R.id.editNoteTitle);
    message = (EditText) fragmentLayout.findViewById(R.id.editNoteMessage);

    noteCatButton = (ImageButton) fragmentLayout.findViewById(R.id.editNoteButton);
    Button savedButton = (Button) fragmentLayout.findViewById(R.id.saveNote);

    //populate widgets with note data
    Intent intent = getActivity().getIntent();
    title.setText(intent.getExtras().getString(MainActivity.title, ""));
    message.setText(intent.getExtras().getString(MainActivity.MESSAGE, ""));

    Note.Category notCat = (Note.Category) intent.getSerializableExtra(MainActivity.CATEGORY);
    noteCatButton.setImageResource(Note.categoryToDrawble(notCat));

    buildCategoryDialog();
    buildConfirmDialog();

    noteCatButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            categoryDialogObject.show();

        }
    });

    savedButton.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
            confirmDialogObject.show();

         }
    });

    return fragmentLayout;
}

private void buildCategoryDialog() {
    final String[] categories = new String[]
            {"Personal", "Technical", "Quote", "Financial"};
    AlertDialog.Builder categoryBuilder = new AlertDialog.Builder(getActivity());
    categoryBuilder.setTitle("Choose Note Type");

    categoryBuilder.setSingleChoiceItems(categories, 0, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int item) {
            categoryDialogObject.cancel();

            switch (item) {
                case 0:
                    savedButtonCategory = Note.Category.PERSONAL;
                    noteCatButton.setImageResource(R.drawable.images);
                    break;
                case 1:
                    savedButtonCategory = Note.Category.TECHNICHAL;
                    noteCatButton.setImageResource(R.drawable.t);
                    break;
                case 2:
                    savedButtonCategory = Note.Category.QUOTE;
                    noteCatButton.setImageResource(R.drawable.q);
                    break;
                case 3:
                    savedButtonCategory = Note.Category.FENANCE;
                    noteCatButton.setImageResource(R.drawable.f);
                    break;
            }

        }
    });

    categoryDialogObject = categoryBuilder.create();
}

private void buildConfirmDialog() {

    AlertDialog.Builder confirmBuilder = new AlertDialog.Builder(getActivity());
    confirmBuilder.setTitle("Are you sure");
    confirmBuilder.setMessage("Are you sure you want to save the note");

    confirmBuilder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

            Log.d("Save Note", "Note title:" + title.getText() + "Note message:"
                    + message.getText() + "Note category:" + savedButtonCategory);

           Intent intent = new Intent(getActivity(), MainActivity.class);
           startActivity(intent);
        }
    });

    confirmBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

        }
    });

    confirmDialogObject = confirmBuilder.create();


}


}