How To open a DialogFragment in activity Android tutorial

Hii everyone in this Android Article we are discussing on DialogFragment. hare we can learn How To open a DialogFragment in activity Android tutorial. We are Create a Dialog fragment in Dialog we can create a user form. This android dialog fragment uses in Activity and opens on button click.

So Let’s Start How To open a DialogFragment in activity Android tutorial.

  • How to Create a Dialog Fragment.
  • How to open a DialogFregent in Activity.
  • How to Paresh value Activity to Fragment.
  • How to get value in a fragment.
  • How to Post Data to server Using Rest API in Fragment.

Step 1: Create an Android Project with empty Activity. 

First of creating an android project with an empty activity. if you have already created a project you can create a fragment and add these codes in your fragment.

Step 2:  Create a Fragment and Open your java and XML file add these codes. 

public class Resourse_Share extends DialogFragment implements View.OnClickListener{
    public static final String KEY_UserEmail = "email";//database key
    public static final String KEY_resourceId= "resourceId";
    public static final String KEY_phoneNumber = "phoneNumber";
    public static final String KEY_Username="name";

    EditText Email,Mobile,UserName;
    Button JoinBtn;
    TextView Close_Popup;
    String Token="" ;
    String EventId;
    private String username;
    private String useremail;
    private  String mobile;

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


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView= inflater.inflate(R.layout.fragment_resourse__share, container, false);
        getDialog().setCanceledOnTouchOutside(false);

        SessionManagement sessionManagement= new SessionManagement();
        Token= sessionManagement.getSavedToken(getActivity());
        EventId = getArguments().getString("id");;

        JoinBtn =(Button)rootView.findViewById(R.id.Share_UpBtn);
        UserName = (EditText)rootView.findViewById(R.id.Share_editName);
        Email=(EditText)rootView.findViewById(R.id.Share_editemail);
        Mobile=(EditText)rootView.findViewById(R.id.Share_Mobile);
        Close_Popup = (TextView)rootView.findViewById(R.id.Close_Popup_Share);
        Close_Popup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        JoinBtn.setOnClickListener(this);

        return rootView;
    }


    public void Share_Resource(){
        final ProgressDialog loading = new ProgressDialog(getActivity());
        loading.setMessage("Please Wait...");
        loading.setCanceledOnTouchOutside(false);
        loading.show();


        HashMap<String, String> params = new HashMap<String, String>();
        params.put(KEY_UserEmail,useremail);
        params.put(KEY_Username,username);
        params.put(KEY_phoneNumber,mobile);
        params.put(KEY_resourceId,EventId);
        JSONObject jsonObject = new JSONObject(params);

        // Enter the correct url for your api service site
        RetryPolicy mRetryPolicy = new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, ConfiURL.Resource_Download_URL, jsonObject,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
//                        Toast.makeText(Login_screen.this,"String Response : "+ response.toString(),Toast.LENGTH_LONG).show();
                        try {
                            Log.d("JSON", String.valueOf(response));
                            loading.dismiss();
                            String Error = response.getString("httpStatus");
                            if (Error.equals("")||Error.equals(null)){

                            }else if(Error.equals("ACCEPTED")){
                                Toast.makeText(getActivity(),"The Post has been shred on the given email Address",Toast.LENGTH_LONG).show();
                                dismiss();
                            }else {

                            }


                        } catch (JSONException e) {
                            e.printStackTrace();
                            loading.dismiss();
                        }
//                        resultTextView.setText("String Response : "+ response.toString());
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                loading.dismiss();
                VolleyLog.d("Error", "Error: " + error.getMessage());
                Toast.makeText(getActivity(), "" + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        })
        {
            @Override
            public String getBodyContentType() {
                return "application/json; charset=utf-8";
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Authorization", Token);
                return headers;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        jsonObjectRequest.setRetryPolicy(mRetryPolicy);
        requestQueue.add(jsonObjectRequest);
    }



    @Override
    public void onClick(View v) {
        String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
        useremail = Email.getText().toString().trim();
        username = UserName.getText().toString().trim();
        mobile =Mobile.getText().toString().trim();
        if(username.equals("") || username.equals(null))
        {
            UserName.setError("Full name can't be empty");
            return;

        }
        else if (useremail.equals("") || useremail.equals(null)||!useremail.matches(emailPattern))
        {
            Email.setError("Email address can't be empty");
            return;
        }
        else{
            if (AppStatus.getInstance(getActivity()).isOnline()) {
                Share_Resource();

                //           Toast.makeText(this,"You are online!!!!",Toast.LENGTH_LONG).show();

            } else {

                ContextThemeWrapper ctw = new ContextThemeWrapper( getActivity(), R.style.Theme_AlertDialog);
                final android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(ctw);
                alertDialogBuilder.setTitle("No internet connection");
                alertDialogBuilder.setMessage("Check your  internet connection or try again");
                alertDialogBuilder.setNegativeButton("Setting", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
                    }
                });
                alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                    }
                });
                alertDialogBuilder.show();
            }
        }
    }

}

Step 3:  Add this code to your Fragment XML file Source Code.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_gravity="center"
    android:minHeight="350dp"
    android:minWidth="320dp"
    android:padding="10dp"
    android:gravity="center"
    tools:context=".Fragments.Resourse_Share">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:padding="10dp"
        android:orientation="vertical">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:padding="10dp"
                android:layout_weight="1"
                android:textStyle="bold"
                android:textAppearance="@style/heading"
                android:text="SHARE"/>

            <TextView
                android:id="@+id/Close_Popup_Share"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:padding="10dp"
                android:drawableTint="@color/Black"
                android:layout_gravity="right"
                android:drawableLeft="@drawable/baseline_clear_24"
                android:textStyle="bold"
                android:textAppearance="@style/heading"
                android:text=""/>

        </LinearLayout>

        <EditText
            android:id="@+id/Share_editName"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:singleLine="true"
            android:paddingLeft="15dp"
            android:layout_marginTop="20dp"
            android:textColorHint="@color/Black"
            android:hint="Name (Required)"
            android:background="@drawable/edit_text"
            android:inputType="textEmailAddress"
            android:textColor="@color/BlueDark" />


        <EditText
            android:id="@+id/Share_editemail"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:singleLine="true"
            android:paddingLeft="10dp"
            android:layout_marginTop="20dp"
            android:textColorHint="@color/Black"
            android:background="@drawable/edit_text"
            android:hint="Email Address (Required)"
            android:inputType="textEmailAddress"
            android:textColor="@color/Black" />


        <EditText
            android:id="@+id/Share_Mobile"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:singleLine="true"
            android:layout_marginTop="20dp"
            android:background="@drawable/edit_text"
            android:paddingLeft="10dp"
            android:textColorHint="@color/Black"
            android:hint="Phone Number (optional)"
            android:inputType="number"
            android:maxLength="10"
            android:textColor="@color/Black" />


        <Button
            android:id="@+id/Share_UpBtn"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:gravity="center"
            android:layout_marginTop="20dp"
            android:layout_gravity="center"
            android:background="@drawable/button"
            android:text="Send"
            android:textAppearance="?android:textAppearanceMedium"
            android:textStyle="bold"
            android:textColor="@color/White"/>

    </LinearLayout>>

</LinearLayout>

Step 4:  Add these code In your activity button click whare open DialogFragment. 

public class Blog_Details extends AppCompatActivity {

    Button Share_BlogBtn;
    FragmentManager fm = getSupportFragmentManager();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
        setContentView(R.layout.activity_blog__details);

        Share_BlogBtn = (Button)findViewById(R.id.Share_BlogBtn);
        Share_BlogBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("id",Blog_Id);
                Resourse_Share resourse_share=new Resourse_Share();
                resourse_share.show(fm, "Dialog Fragment");
                resourse_share.setArguments(bundle);
            }
        });
    }

Facebooktwitterredditpinterestlinkedinmail
Recommended
Hiii developer in this android solution we are discussing the …