简体   繁体   中英

Navigate from fragment to activity

I know this is a question frequently asked, but after reading the many questions and solutions on stack overflow I am could not find a good solution to my problem. i have a fragment and i would like to navigate to the main activity when a user does press the OK button of the AlertDialog but my application crashes. i can't find what is wrong with my code. thanks for your help in advanced.

i can't see what i did wrong here

 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();


}

Here is my fragment

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();


}


}

Here is my 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);
}
}

Crash report

03-09 08:14:33.816 31586-31586/ricom.gmail.com.myapplication12 E/AndroidRuntime: FATAL EXCEPTION: main Process: ricom.gmail.com.myapplication12, PID: 31586 java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference at ricom.gmail.com.myapplication12.NoteEditFragment$4.onClick(NoteEditFragment.java:121) at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6494) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

it is telling that there is an error here

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

You just have to use simple intents..

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

Actually you use

getActivity()

to get activity to which a fragment is attached.(that is the first parameter of Intent())

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();


}


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM