将数据从DialogFragment传递回Activity

时间:2014-01-29 19:35:56

标签: java android android-fragments fragment

我在对话框片段中设置了搜索字段,然后当用户点击最初打开时,允许他们输入标题并点击搜索。我希望这能够与Activity的列表视图进行通信。

不幸的是,我在尝试搜索时遇到了崩溃。我使用监听器进行设置,但我认为它与尝试从MainActivity的布局中读取textView有关,即使它位于DialogFragment'a布局xml中?

我试图通过MainActivity中的R.id.searchField调用它,onCreate的setContent的布局XML与DialogFragment实现的布局XML不同。我试图这样做时没有错误,只是致命的崩溃。不知道为什么我会收到错误,这是代码,下面是堆栈跟踪:

MainActivity:

public class MainActivity extends Activity implements searchListener{
public void searchBooks() 
    {
// Error is in this function, believe it has to do with this textField as it resides in // the DialogFragment's xml? Unless findViewById calls from all XMLS and just not one defined in 
//setContentView for the activity? Not sure though, initially I feel I should have this searchField 
//defined in the fragment class, but then I won't have access to it in this function in MainActivity, 
//or the mResults which is where the data is being used

        EditText searchField = (EditText) findViewById(R.id.searchField);

        if (mResults != null && !searchField.getText().equals(""))
        {

            String inputedText = searchField.getText().toString();
            JSONArray results = new JSONArray();

            for (int i = 0; i < mResults.length(); i++)
            {
                try {
                    JSONObject bookObject = mResults.getJSONObject(i);
                    if (bookObject.get("name").toString().equalsIgnoreCase(inputedText))
                    {
                        results.put(bookObject);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }
    }
public void showDialog() {
    DialogFrag newFragment = DialogFrag.newInstance();
    newFragment.show(getFragmentManager(), "dialog");
}
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Setting the main view
        setContentView(R.layout.activity_main_fragment);
}
}

DialogFragment:

public class DialogFrag extends DialogFragment {
    public static DialogFrag newInstance() {
        return new DialogFrag();
    }
    private searchListener listener;
    public interface searchListener
    {
        public void searchBooks();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            listener = (searchListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + "attaching d fragment failed!");
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.search_dialog_fragment, container, false);

        searchButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                listener.searchBooks();
            }
        });
        return v;
    }
}

栈跟踪

01-29 20:10:21.570: E/AndroidRuntime(11260): FATAL EXCEPTION: main
01-29 20:10:21.570: E/AndroidRuntime(11260): Process: com.brentadams.bookList, PID: 11260
01-29 20:10:21.570: E/AndroidRuntime(11260): java.lang.NullPointerException
01-29 20:10:21.570: E/AndroidRuntime(11260):    at com.brentadams.bookList.MainActivity.searchBooks(MainActivity.java:327)
01-29 20:10:21.570: E/AndroidRuntime(11260):    at com.brentadams.bookList.fragments.SearchFragment$1.onClick(SearchFragment.java:48)
01-29 20:10:21.570: E/AndroidRuntime(11260):    at android.view.View.performClick(View.java:4438)
01-29 20:10:21.570: E/AndroidRuntime(11260):    at android.view.View$PerformClick.run(View.java:18422)
01-29 20:10:21.570: E/AndroidRuntime(11260):    at android.os.Handler.handleCallback(Handler.java:733)
01-29 20:10:21.570: E/AndroidRuntime(11260):    at android.os.Handler.dispatchMessage(Handler.java:95)
01-29 20:10:21.570: E/AndroidRuntime(11260):    at android.os.Looper.loop(Looper.java:136)
01-29 20:10:21.570: E/AndroidRuntime(11260):    at android.app.ActivityThread.main(ActivityThread.java:5017)
01-29 20:10:21.570: E/AndroidRuntime(11260):    at java.lang.reflect.Method.invokeNative(Native Method)
01-29 20:10:21.570: E/AndroidRuntime(11260):    at java.lang.reflect.Method.invoke(Method.java:515)
01-29 20:10:21.570: E/AndroidRuntime(11260):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
01-29 20:10:21.570: E/AndroidRuntime(11260):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
01-29 20:10:21.570: E/AndroidRuntime(11260):    at dalvik.system.NativeStart.main(Native Method)

编辑新代码/错误:

接受你的建议并将字符串传递回方法searchBooks,但现在接受一个愚蠢的nullpointerexception我认为没有任何意义。 textview位于我的activity_main_fragment.xml:

public class MainActivity extends Activity implements searchListener{
public void searchBooks(String searchString) 
    { 


        if (mResults != null && searchString != null && !searchString.equals(""))
        {


            JSONArray results = new JSONArray();

            for (int i = 0; i < mResults.length(); i++)
            {
                try {
                    JSONObject bookObject = mResults.getJSONObject(i);
                    if (bookObject.get("name").toString().equalsIgnoreCase(searchString))
                    {
                        results.put(bookObject);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }
    }
public void showDialog() {
    DialogFrag newFragment = DialogFrag.newInstance();
    newFragment.show(getFragmentManager(), "dialog");
}
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Setting the main view
        setContentView(R.layout.activity_main_fragment);
}
}

DialogFragment

public class DialogFrag extends DialogFragment {
    public static DialogFrag newInstance() {
        return new DialogFrag();
    }
    private searchListener listener;
    public interface searchListener
    {
        public void searchBooks(String text);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            listener = (searchListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + "attaching d fragment failed!");
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.search_dialog_fragment, container, false);

        searchButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                EditText searchField = (EditText) v.findViewById(R.id.searchField);
                String input = searchField.getText().toString();
                listener.searchBooks(input);
            }
        });
        return v;
    }
}

堆栈跟踪

01-29 15:30:31.402: E/AndroidRuntime(777): FATAL EXCEPTION: main
01-29 15:30:31.402: E/AndroidRuntime(777): java.lang.NullPointerException
01-29 15:30:31.402: E/AndroidRuntime(777):  at com.brentadams.bookList.fragments.SearchFragment$1.onClick(SearchFragment.java:51)
01-29 15:30:31.402: E/AndroidRuntime(777):  at android.view.View.performClick(View.java:4084)
01-29 15:30:31.402: E/AndroidRuntime(777):  at android.view.View$PerformClick.run(View.java:16966)
01-29 15:30:31.402: E/AndroidRuntime(777):  at android.os.Handler.handleCallback(Handler.java:615)
01-29 15:30:31.402: E/AndroidRuntime(777):  at android.os.Handler.dispatchMessage(Handler.java:92)
01-29 15:30:31.402: E/AndroidRuntime(777):  at android.os.Looper.loop(Looper.java:137)
01-29 15:30:31.402: E/AndroidRuntime(777):  at android.app.ActivityThread.main(ActivityThread.java:4745)
01-29 15:30:31.402: E/AndroidRuntime(777):  at java.lang.reflect.Method.invokeNative(Native Method)
01-29 15:30:31.402: E/AndroidRuntime(777):  at java.lang.reflect.Method.invoke(Method.java:511)
01-29 15:30:31.402: E/AndroidRuntime(777):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-29 15:30:31.402: E/AndroidRuntime(777):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-29 15:30:31.402: E/AndroidRuntime(777):  at dalvik.system.NativeStart.main(Native Method)

第51行:

        String input = searchField.getText().toString();

2 个答案:

答案 0 :(得分:1)

findViewById()只会找到您在setContentView()中指定的布局文件中的视图。您需要将TextView移至Activity's布局或将此逻辑移至Fragment

答案 1 :(得分:1)

所以是的,问题是R.id.searchfield。它不是您的MainActivity的rootview的子视图,它是对话框片段的子视图。

出现空指针,因为它找不到R.id.searchfield,并且搜索结果为null,当你调用searchField.getText()时,它会在下一行左右崩溃。

只需让您的dialogfrag搜索文本字段并将字符串传回主活动。