我需要将一个String传递给同一个Activity中的一个片段,我试过这个但是它给出了一个错误

时间:2017-05-02 13:43:38

标签: android

我是Android Tv开发的新手,我需要将一个字符串从它所属的相同活动传递给MainFragment。 这是我的MainActivity代码:

public class MainActivity extends Activity {
    EditText search_query;
    private static String user_query = "";
    Bundle query_data;
    ImageView action_search, action_delete;



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("TAG", "Main-act-created");
        setContentView(R.layout.activity_main);
        query_data = new Bundle();
        query_data.putString("SEARCHQUERY",user_query);
        search_query = (EditText)findViewById(R.id.search_query);
        action_search = (ImageView)findViewById(R.id.action_search);
        action_delete = (ImageView)findViewById(R.id.action_delete);
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment fragment = new MainFragment();
        fragment.setArguments(query_data);
        fragmentTransaction.add(fragment,"MainFragment");
        fragmentTransaction.commit();
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                SharedPreferences getPrefs = PreferenceManager
                        .getDefaultSharedPreferences(getBaseContext());
                boolean isFirstStart = getPrefs.getBoolean("firstStart", true);
                if (isFirstStart) {
                    Intent i = new Intent(MainActivity.this, BoardingActivity.class);
                    startActivity(i);
                    SharedPreferences.Editor e = getPrefs.edit();
                    e.putBoolean("firstStart", false);
                    e.apply();
                }
            }
        });
        // Start the thread
        t.start();
        action_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                respondToSearch();
            }
        });
        action_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

    }
    public void respondToSearch(){
        user_query = search_query.getText().toString();
        //pass the query to MainFragment
        query_data.putString("SEARCHQUERY",user_query);
        Fragment fragment =  new MainFragment();
        fragment.setArguments(query_data);
    }
}

这是活动的布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:id="@+id/main_frame"
    android:background="#ffffff"
    android:layout_margin="2dp"
    android:padding="2dp"
    android:orientation="vertical">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="7.5"
    android:background="#B71C1C"
    android:alpha="0.9"
    android:layout_marginBottom="3dp"
    android:orientation="horizontal">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:hint="Search"
        android:id="@+id/search_query"
        android:textSize="25sp"
        android:layout_weight="1"
        android:layout_marginLeft="2dp"
        android:layout_marginTop="2dp"
        android:layout_marginBottom="2dp"/>
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#B71C1C"
        android:src="@drawable/close"
        android:layout_marginTop="15dp"
        android:layout_marginBottom="15dp"
        android:layout_marginRight="15dp"
        android:id="@+id/action_delete"
        android:layout_weight="5"/>
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/search"
        android:background="#ffffff"
        android:id="@+id/action_search"
        android:layout_weight="5"/>
</LinearLayout>




    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1">
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <ImageView
                android:layout_width="250dp"
                android:layout_height="120dp"
                android:src="@drawable/banner"
                android:layout_gravity="right"
                android:gravity="right"
                android:layout_margin="3dp"
                android:padding="0dp" />


            <fragment xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:id="@+id/main_browse_fragment"
                android:name="in.silive.mytvapplication.Fragments.MainFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:context=".Activities.MainActivity"
                tools:deviceIds="tv"
                tools:ignore="MergeRootFrame" />
        </FrameLayout>
    </LinearLayout>


</LinearLayout>

以下是我在MainFragment中检索字符串的方法:

@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        Log.d(TAG, "onCreate-MainFragment");
        super.onActivityCreated(savedInstanceState);
        context = getActivity();
        prepareBackgroundManager();
        Log.d(TAG, "onCreate-MainFragment_background prepared");
        sbundle = getArguments().getBundle("SEARCHQUERY");
        if(sbundle!=null){
            user_search = this.getArguments().getString("SEARCHQUERY");
            Log.d("TAG","user search : "+user_search);
        }

        setupUIElements();
        Log.d(TAG, "onCreate-MainFragment_ui elements placed");
        mRowsAdapter = new ArrayObjectAdapter(new ListRowPresenter());
        for (int j = 0; j < 5; j++) {
            if (j == 0) {
                sprogressDialog = new ProgressDialog(context);
                sprogressDialog.setMessage("Loading");
                sprogressDialog.show();
            }
            final int finalJ = j;
            new FetchData(j, context, api_url[j], new OnTaskComplete() {
                @Override
                public void OnTaskComplete() {
                    loadRows(i);
                    if (finalJ == 4 && sprogressDialog.isShowing())
                        sprogressDialog.dismiss();
                }
            }).execute();
        }
        dataLoaded = true;


        //loadRows();
        Log.d(TAG, "onCreate-MainFragment_row adapter implemented");
        setupEventListeners();
        Log.d(TAG, "onCreate-MainFragment_event listeners applied");

    }

我收到此错误:

Process: in.silive.mytvapplication, PID: 6417
                                                                         java.lang.RuntimeException: Unable to start activity ComponentInfo{in.silive.mytvapplication/in.silive.mytvapplication.Activities.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.os.Bundle.getBundle(java.lang.String)' on a null object reference
                                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
                                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                                             at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                             at android.os.Looper.loop(Looper.java:154)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                          Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.os.Bundle.getBundle(java.lang.String)' on a null object reference
                                                                             at in.silive.mytvapplication.Fragments.MainFragment.onActivityCreated(MainFragment.java:99)
                                                                             at android.app.Fragment.performActivityCreated(Fragment.java:2362)
                                                                             at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1014)
                                                                             at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1171)
                                                                             at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1153)
                                                                             at android.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:2039)
                                                                             at android.app.FragmentController.dispatchActivityCreated(FragmentController.java:176)
                                                                             at android.app.Activity.performCreateCommon(Activity.java:6673)
                                                                             at android.app.Activity.performCreate(Activity.java:6681)
                                                                             at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
                                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
                                                                             at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
                                                                             at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                             at android.os.Looper.loop(Looper.java:154) 
                                                                             at android.app.ActivityThread.main(ActivityThread.java:6119) 
                                                                             at java.lang.reflect.Method.invoke(Native Method) 
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

这是行号:99。(sbundle = getArguments().getBundle("QUERYSEARCH");

1 个答案:

答案 0 :(得分:0)

使用Bundle传递值

public void respondToSearch(){
        user_query = search_query.getText().toString();
        Fragment fragment =  new MainFragment();
        Bundle bundle = new Bundle();
        bundle.putString("QUERYSEARCH", user_query);
        fragment.setArguments(bundle);
    }

并从Bundle中读取值

Bundle bundle = getArguments();
String sbundle = bundle.getString("QUERYSEARCH");

在您的代码中,您将密钥值作为SEARCHQUERY发送​​,并使用QUERYSEARCH键读取值。