如何从Android中的DialogFragment获取数据到MainActivity?

时间:2015-06-11 10:06:17

标签: java android android-fragments

我使用DialogFragment创建了一个应用程序。我想从DialogFragment中的setTextMainActivity获取数据。在我的代码中,我成功创建了AlertDialog。但是我无法将EditText值提供给MainActivity。应用程序崩溃了。请帮我解决问题。任何帮助都会我真的很感激。

MainActivity.java

public class MainActivity extends ActionBarActivity {
Button showDialog;
TextView showText;
String myNameStr;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    showDialog = (Button)findViewById(R.id.myBtn);
    showText = (TextView)findViewById(R.id.showText);
    showDialog.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showMyAlert(v);
        }
    });
}

public void showMyAlert(View view) {
    MyAlert myAlert = new MyAlert();
    myAlert.show(getFragmentManager(), "My New Alert");
}

public void setMyNameStr(String myNameStr) {
    showText.setText(myNameStr);
}
}

MyAlert.java

public class MyAlert extends DialogFragment implements OnClickListener {
private EditText getEditText;
MainActivity callBackActivity;

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    callBackActivity = new MainActivity();
    getEditText = new EditText(getActivity());
    getEditText.setInputType(InputType.TYPE_CLASS_TEXT);
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("Get UserName :");
    builder.setMessage("Enter Your Name :");
    builder.setPositiveButton("Ok", this);
    builder.setNegativeButton("Cancel", null);
    builder.setView(getEditText);
    return builder.create();
}

@Override
public void onClick(DialogInterface dialog, int which) {
    String value = getEditText.getText().toString();
    Log.d("Name : ", value);
    MainActivity mainActivity = new MainActivity();
    mainActivity.setMyNameStr(value);
    dialog.dismiss();
}
}

使用此程序应用程序已崩溃。

4 个答案:

答案 0 :(得分:2)

替换

MainActivity mainActivity = new MainActivity(); 

到:

Activity mainActivity = (MainActivity)getActivity();

答案 1 :(得分:1)

        you can achieve this using a interface,by sending your data from a fragment to main activity,below i have edited your complete code and its working fine....
       Here is the code with example
        Your Main Activity
        package com.example.dialogfragment;

        import android.annotation.TargetApi;
        import android.app.Activity;
        import android.os.Build;
        import android.os.Bundle;
        import android.view.View;
        import android.widget.Button;
        import android.widget.TextView;

        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        public class MainActivity extends Activity  implements SetName{
            Button showDialog;
            TextView showText;
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                showDialog = (Button)findViewById(R.id.button1);
                showText = (TextView)findViewById(R.id.textView2);
                showDialog.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showMyAlert(v);
                    }
                });
            }

            public void showMyAlert(View view) {
                MyAlert myAlert = new MyAlert();
                myAlert.show(getFragmentManager(), "My New Alert");
            }

            public void setMyNameStr(String myNameStr) {

            }


            @Override
            public void setMyName(String string) {
                // TODO Auto-generated method stub

                showText.setText(string);

            }

        }

    Your Alert
    import android.annotation.TargetApi;
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.Dialog;
    import android.app.DialogFragment;
    import android.content.DialogInterface;
    import android.content.DialogInterface.OnClickListener;
    import android.os.Build;
    import android.os.Bundle;
    import android.text.InputType;
    import android.util.Log;
    import android.widget.EditText;

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public class MyAlert extends DialogFragment implements OnClickListener {

        private EditText getEditText;
        MainActivity callBackActivity;
        SetName setname;

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {

            callBackActivity = new MainActivity();
            getEditText = new EditText(getActivity());
            getEditText.setInputType(InputType.TYPE_CLASS_TEXT);
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle("Get UserName :");
            builder.setMessage("Enter Your Name :");
            builder.setPositiveButton("Ok", this);
            builder.setNegativeButton("Cancel", null);
            builder.setView(getEditText);
            return builder.create();
        }


        @Override
        public void onAttach(Activity a) {
            super.onAttach(a);
            setname = (SetName) a;
        }
        @Override
        public void onClick(DialogInterface dialog, int which) {
            String value = getEditText.getText().toString();
            Log.d("Name : ", value);
            // MainActivity mainActivity = new MainActivity();
            setname .setMyName(value);
            //setname = (SetName)
            // setname = (SetName)getActivity();
            dialog.dismiss();
        }


    }

Create a Interface

public interface SetName {


    void setMyName(String string);

}


Now what you should do is create onAttach in your alertFragment and call your interface..

答案 2 :(得分:1)

创建像

这样的界面

CustomDialogInterface.java

public interface CustomDialogInterface {

        // This is just a regular method so it can return something or
        // take arguments if you like.
    public void okButtonClicked(String  value);


}

并通过 -

修改MyAlert.java
public class MyAlert extends DialogFragment implements OnClickListener {

private EditText getEditText;
MainActivity callBackActivity;
CustomDialogInterface customDI;

public MyAlert(CustomDialogInterface customDI)
{
    this.customDI = customDI;
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    callBackActivity = new MainActivity();
    getEditText = new EditText(getActivity());
    getEditText.setInputType(InputType.TYPE_CLASS_TEXT);
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("Get UserName :");
    builder.setMessage("Enter Your Name :");
    builder.setPositiveButton("Ok", this);
    builder.setNegativeButton("Cancel", null);
    builder.setView(getEditText);
    return builder.create();
}

@Override
public void onClick(DialogInterface dialog, int which) {
    String value = getEditText.getText().toString();
    Log.d("Name : ", value);
    dialog.dismiss();
    customDI.okButtonClicked(value);


}
}

在MainActivity和overover方法中实现CustomDialogInterface okButtonClicked() 当调用onClick时,将调用MainActivity的onButtonClicked。

并将showAlert更改为 -

public void showMyAlert(View view) {
    MyAlert myAlert = new MyAlert(this);
    myAlert.show(getFragmentManager(), "My New Alert");
}

答案 3 :(得分:0)

public void renameFile(){
RenameFileDialog dialog = new RenameFileDialog();
        dialog.show(getSupportFragmentManager(), DIALOG_RENAME_FILE);

}

  public void syncFolders(String value) {
 //some code
        new UpdateFolderAsyncTask().execute();
    }

在DialogFragment类的主要活动类syncFolders()中执行操作后,使用新的更新值更新listview

   CustomDialogFragment extends DialogFragment{
//some logic for performining operation
String updatedValue=edittext.getText();

MainActivity activity=(MainActivity)getActivity();
activity.syncFolders(updatedValue);
}