Good night, in my application I made a DialogFragment put a function of closing current activity and return to previous, the call put in onBackPressed()
and the code that does that function is in the onclick of "OK" ... only that You are introducing an error in LogCat
Could anyone help me?
DialogFragment:
package com.gif.popupsair;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
public class MyDialog extends DialogFragment {
private Activity getActivity;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builderr = new AlertDialog.Builder(getActivity());
builderr.setMessage("Isso e um dialogFragment").setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
getActivity.finish();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builderr.setTitle("Hello Mundo");
AlertDialog dialog = builderr.create();
return dialog;
}
}
Second Activity:
package com.gif.popupsair;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
public void AbrirDialog(View view){
Toast.makeText(getApplicationContext(), "Aperte o botao para voltar", Toast.LENGTH_SHORT).show();
}
@Override
public void onBackPressed()
{
MyDialog di = new MyDialog();
di.show(getSupportFragmentManager(), "my_dialog_tag");
}
}
LogCat:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.gif.popupsair, PID: 1370
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.Activity.finish()' on a null object reference
at com.gif.popupsair.MyDialog$2.onClick(MyDialog.java:24)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Name of the first Activity: MainActivity
Thank you ...