如何将数据从Activity传递到DialogFragment

时间:2017-02-04 15:44:03

标签: java android android-activity nullpointerexception android-dialogfragment

我知道有一些关于如何将数据从活动传递到对话框(即Bundle或Intent)的示例。但是,我尝试过的所有东西都不起作用。我不断收到NPE和"Unable to find explicit activity class"错误。即使我用对话框构建超级基本活动也不行。我需要在代码中添加什么才能使其正常工作?

MainActivity:

public class MainActivity extends AppCompatActivity {

  Button button;
  String textIWantToSee;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.button);

    textIWantToSee = "If this is the text I want to pass form this activity to the Fragment";

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


        }
    });
  }
}

对话框:

public class Dialog extends DialogFragment {

  TextView textView;

  @Override
  public android.app.Dialog onCreateDialog(Bundle savedInstanceState) {

    LayoutInflater inflater = getActivity().getLayoutInflater();
    View v = inflater.inflate(R.layout.dialog_layout, null);

    textView = (TextView) v.findViewById(R.id.textView);

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setView(v);

    return builder.create();
  }
}

更新

MainActivity:

public class MainActivity extends AppCompatActivity {

TextView tvIntent;
Button button;
String textIWantToSee;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tvIntent = (TextView) findViewById(R.id.tvIntent);
    button = (Button) findViewById(R.id.button);

    textIWantToSee = "If this is the text I want to pass form this activity to the Fragment";
    tvIntent.setText(textIWantToSee);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String intent = String.valueOf(tvIntent);
            Intent intentToDialog = new Intent(MainActivity.this, Dialog.class);
            intentToDialog.putExtra("keyForIntent", intent);
            startActivity(intentToDialog); //Here is the exception

        }
    });
}

} 对话框:

public class Dialog extends DialogFragment {

TextView textView;
String intent;

@Override
public android.app.Dialog onCreateDialog(Bundle savedInstanceState) {

    LayoutInflater inflater = getActivity().getLayoutInflater();
    View v = inflater.inflate(R.layout.dialog_layout, null);

    textView = (TextView) v.findViewById(R.id.textView);
    Intent intentFromDialog = new Intent(getActivity().getApplicationContext(),MainActivity.class);
    intent = intentFromDialog.getStringExtra("keyForIntent");
    textView.setText(intent);

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setView(v);

    return builder.create();
}

}

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: nl.blogvandetoekomst.passdatafromactivitytodialog, PID: 2947
              android.content.ActivityNotFoundException: Unable to find explicit activity class {nl.blogvandetoekomst.passdatafromactivitytodialog/nl.blogvandetoekomst.passdatafromactivitytodialog.Dialog}; have you declared this activity in your AndroidManifest.xml?
                  at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1794)
                  at android.app.Instrumentation.execStartActivity(Instrumentation.java:1512)
                  at android.app.Activity.startActivityForResult(Activity.java:3917)
                  at android.app.Activity.startActivityForResult(Activity.java:3877)
                  at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:842)
                  at android.app.Activity.startActivity(Activity.java:4200)
                  at android.app.Activity.startActivity(Activity.java:4168)
                  at nl.blogvandetoekomst.passdatafromactivitytodialog.MainActivity$1.onClick(MainActivity.java:36)
                  at android.view.View.performClick(View.java:5198)
                  at android.view.View$PerformClick.run(View.java:21147)
                  at android.os.Handler.handleCallback(Handler.java:739)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:148)
                  at android.app.ActivityThread.main(ActivityThread.java:5417)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="nl.blogvandetoekomst.passdatafromactivitytodialog">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

5 个答案:

答案 0 :(得分:2)

这是您将数据从DialogFragment传递给Activity的方式:

<强> MainActivity.java

public class MainActivity extends AppCompatActivity {

Button button;
String textIWantToSee;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.button);

    textIWantToSee = "If this is the text I want to pass form this activity to the Fragment";

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Dialog dialogFragment = new Dialog();
            Bundle bundle = new Bundle();
            bundle.putString("TEXT",textIWantToSee);
            dialogFragment.setArguments(bundle);
            dialogFragment.show((MainActivity.this).getSupportFragmentManager(),"Image Dialog");

        }
    });
}
}

<强> Dialog.java

public class Dialog extends DialogFragment {

TextView textView;

@Override
public android.app.Dialog onCreateDialog(Bundle savedInstanceState) {

    LayoutInflater inflater = getActivity().getLayoutInflater();
    View v = inflater.inflate(R.layout.dialog_layout, null);

    Bundle bundle = getArguments();
    String imageLink = bundle.getString("TEXT","");

    textView = (TextView) v.findViewById(R.id.textView);

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setView(v);

    return builder.create();
}
}

答案 1 :(得分:1)

您的对话框片段需要托管活动,需要在活动内部进行充气。

在MainActivity中使用:

来膨胀/显示DialogFragment
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Bundle bundle = new Bundle(); //Bundle containing data you are passing to the dialog
        bundle.putString("text", textIWantToSee);

        Dialog dialog = new Dialog(); //Create a new Dialog
        dialog.setArguments(bundle);

        dialog.show(getSupportFragmentManager(), "MY_DIALOG_TAG"); //Inflate the dialog
    }
});

答案 2 :(得分:0)

如果您正在使用支持库,则应使用android.support.v4.app.DialogFragment而不是android.app.Dialog。另外,您是否可以发布您用来显示对话框的部分代码?

然后你必须使用DialogFragment的框架版本,正如OBX指出的那样:

<强> MainActivity.java

public class MainActivity extends AppCompatActivity {

    Button button;
    String textIWantToSee;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button); 

        textIWantToSee = "If this is the text I want to pass form this activity to the Fragment";

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Dialog dialogFragment = new Dialog();
                Bundle bundle = new Bundle();
                bundle.putString("TEXT",textIWantToSee);
                dialogFragment.setArguments(bundle);
                dialogFragment.show(getFragmentManager(),"Image Dialog");
            }
        });
    }
}

<强> Dialog.java

public class Dialog extends DialogFragment {

    TextView textView;

    @Override
    public android.app.Dialog onCreateDialog(Bundle savedInstanceState) {

        LayoutInflater inflater = getActivity().getLayoutInflater();
        View v = inflater.inflate(R.layout.dialog_layout, null);

        Bundle bundle = getArguments();
        String imageLink = bundle.getString("TEXT","");

        textView = (TextView) v.findViewById(R.id.textView);

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(v);
        return builder.create();
    }
}

这种方式对我来说非常好。

<强>编辑:

在onClick中执行此操作:

Intent intentToDialog = new Intent(MainActivity.this, Dialog.class);
intentToDialog.putExtra("keyForIntent", intent);
startActivity(intentToDialog); //Here is the exception

您没有启动活动,Dialog.class是一个扩展的DialogFragment,您无法显示启动Activity的对话框。试试我发布的最后一个代码。

答案 3 :(得分:-1)

使用对话框片段的newInstance。 参考:https://developer.android.com/reference/android/app/DialogFragment.html

   static MyDialogFragment newInstance(int num) {
    MyDialogFragment f = new MyDialogFragment();

    // Supply num input as an argument.
    Bundle args = new Bundle();
    args.putInt("num", num);
    f.setArguments(args);

    return f;
}

如果您使用的是kotlin,请尝试在随播对象

中定义newInstance
companion object {
        fun newInstance(num: Int): MyDialogFragment{
            val f = DimensionDialogFragment()
            val args = Bundle()
            args.putInt("num", num)
            f.setArguments(args)

            return f
        }
    }

答案 4 :(得分:-2)

您可以直接在您的活动中创建对话框:

button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        LayoutInflater inflater = MainActivity.this.getLayoutInflater();
        View v = inflater.inflate(R.layout.dialog_layout, null);

        TextView textView = (TextView) v.findViewById(R.id.textView);
        textView.setText(textIWantToSee);

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setView(v);
        builder.show();

        }
    });