在FragmentActivity和Fragment之间发送数据

时间:2014-10-16 06:23:55

标签: java android android-fragments

我的MainActivity中有一个SearchView。我想将我输入的文本传递给我的片段(包含ListView)并能够使用适配器过滤列表。

问题是使用下面的代码我能够传入输入到片段的文本,但后来我得到了一个nullpointer异常。

注意:适配器工作正常。我也尝试在我的片段中将TextView设置为传递的字符串,但应用程序崩溃。

MainActivity中的

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.activity_main_actions, menu);
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    MenuItem searchItem = menu.findItem(R.id.action_search);
    searchView = (SearchView) searchItem.getActionView();  
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setIconifiedByDefault(false); 

    SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener()
    {

      @Override
        public boolean onQueryTextSubmit(String query)
        {
            TopRatedFragment newFragment = new TopRatedFragment();  //FOR PASSING TEXT
            Bundle args = new Bundle();
            args.putString("hii", query);
            newFragment.setArguments(args);
            newFragment.kl();
            android.support.v4.app.FragmentTransaction transaction =                
             getSupportFragmentManager().beginTransaction();
              transaction.addToBackStack(null);

            // Commit the transaction
            transaction.commit();

            System.out.println("on query submit: "+query);
            return true;
        }
    };
    searchView.setOnQueryTextListener(textChangeListener);

     return super.onCreateOptionsMenu(menu);

在片段中:

    public void kl(){
    String menu = getArguments().getString("hii");
    adapter.getFilter().filter("hii");
}

logcat的:

 10-16 09:26:23.234: E/AndroidRuntime(19960): FATAL EXCEPTION: main
 10-16 09:26:23.234: E/AndroidRuntime(19960): java.lang.NullPointerException
 10-16 09:26:23.234: E/AndroidRuntime(19960):   at  com.example.tab.TopRatedFragment.kl(TopRatedFragment.java:51)
  10-16 09:26:23.234: E/AndroidRuntime(19960):  at     com.example.tab.MainActivity$3.onQueryTextSubmit(MainActivity.java:160)
   10-16 09:26:23.234: E/AndroidRuntime(19960):     at   android.widget.SearchView.onSubmitQuery(SearchView.java:1203)
   10-16 09:26:23.234: E/AndroidRuntime(19960):     at android.widget.SearchView.access$900(SearchView.java:93)
   10-16 09:26:23.234: E/AndroidRuntime(19960):     at android.widget.SearchView$8.onEditorAction(SearchView.java:1178)
   10-16 09:26:23.234: E/AndroidRuntime(19960):     at android.widget.TextView.onEditorAction(TextView.java:4973)
   10-16 09:26:23.234: E/AndroidRuntime(19960):     at com.android.internal.widget.EditableInputConnection.performEditorAction(EditableInputConnection.java:138)
  10-16 09:26:23.234: E/AndroidRuntime(19960):  at    com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:297)
  10-16 09:26:23.234: E/AndroidRuntime(19960):  at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:77)
 10-16 09:26:23.234: E/AndroidRuntime(19960):   at android.os.Handler.dispatchMessage(Handler.java:99)
  10-16 09:26:23.234: E/AndroidRuntime(19960):  at android.os.Looper.loop(Looper.java:176)
  10-16 09:26:23.234: E/AndroidRuntime(19960):  at android.app.ActivityThread.main(ActivityThread.java:5419)
 10-16 09:26:23.234: E/AndroidRuntime(19960):   at java.lang.reflect.Method.invokeNative(Native Method)
  10-16 09:26:23.234: E/AndroidRuntime(19960):  at java.lang.reflect.Method.invoke(Method.java:525)
  10-16 09:26:23.234: E/AndroidRuntime(19960):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
 10-16 09:26:23.234: E/AndroidRuntime(19960):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
  10-16 09:26:23.234: E/AndroidRuntime(19960):  at dalvik.system.NativeStart.main(Native Method)

好的,所以我发现问题是在Fragment类中,在onCreateView之外,View为null,因此任何属性(TextView,adapter ...)都为null。这就是为什么我得到nullpointer异常。但似乎无法找到解决方法,因为我想在onc​​reateview

之外设置适配器

4 个答案:

答案 0 :(得分:0)

请参阅Android Shared preferences example

请使用共享偏好设置:

SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
 editor.putString("name", "Elena");
 editor.putInt("idName", 12);
 editor.commit();


// MY_PREFS_NAME - a static String variable like: 
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
  String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
  int idName = prefs.getInt("idName", 0); //0 is the default value.
}

答案 1 :(得分:0)

在您的片段中,您可以调用getActivity()。这将使您可以访问创建片段的活动。从那里你可以明显地调用活动中的任何类型的访问器方法。

例如 来自FragmentActivity:

Bundle bundle = new Bundle();
bundle.putString("message", "Alo Elena!");
FragmentClass fragInfo = new FragmentClass();
fragInfo.setArguments(bundle);
transaction.replace(R.id.fragment_single, fragInfo);
transaction.commit();

在Fragment中获取价值

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        String myValue = this.getArguments().getString("message");
        ...
        ...
        ...
}

答案 2 :(得分:0)

 class myClass extends FragmentActivity {
   public static String dataToPass="Test";

 //Call Class fragment 
 //In this way you can share String , integers , object , arralist and can be share between     all fragment. you just need to define all in that activity as public static .
 } 

答案 3 :(得分:0)

您可以通过定义接口在片段之间进行通信。 在这里描述http://developer.android.com/training/basics/fragments/communicating.html

在Fragment中定义一个inerface

 public interface OnManufacturerSelectedListener {
            public void onManufacturerSelected(String Manufacturer);
        }

in fragment方法kl():

 public void kl(){
    String menu = getArguments().getString("hii");
    OnManufacturerSelectedListener.onManufacturerSelected("hii");
}

然后在MainActivity中实现OnManufacturerSelectedListener

@Override
        public void onManufacturerSelected(String Manufacturer) {
            String hi=Manufacturer;
        }