Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the Data from DialogFragment to MainActivity in Android?

I create a application using DialogFragment.I want to get the Data from DialogFragment and setText in the MainActivity. In my Code I successfully Created the AlertDialog.But I con't able to get the EditText value to MainActivity.Application is crashed.Please help me to solve the problem.Any Help would be I really Appreciate.

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

Using this Procedure Application is Crashed.

like image 675
reegan29 Avatar asked Feb 10 '23 21:02

reegan29


1 Answers

replace from

MainActivity mainActivity = new MainActivity(); 

to:

Activity mainActivity = (MainActivity)getActivity();
like image 180
NavinRaj Pandey Avatar answered Feb 12 '23 09:02

NavinRaj Pandey