使用bundle或intent将数据从活动传输到片段

时间:2017-12-16 15:57:57

标签: android fragment bundle

我想将数据从活动传输到片段,它总是打印此错误。我尝试使用不同的技术来克服这种想法,但仍然卡住了。我在活动或片段中的代码中遗漏了什么?

 E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.junaida.project1, PID: 14447
              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.junaida.project1/com.example.junaida.project1.Year}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3018)
                  at android.app.ActivityThread.-wrap14(ActivityThread.java)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1653)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6724)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
                  at com.example.junaida.project1.fragments.CardFragment.onCreateView(CardFragment.java:89)
                  at android.support.v4.app.Fragment.performCreateView(Fragment.java:2354)
                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1419)
                  at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740)
                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809)
                  at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:799)
                  at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2580)
                  at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)
                  at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
                  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2229)
                  at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3221)
                  at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3171)
                  at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:192)
                  at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:560)
                  at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
                  at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1256)
                  at android.app.Activity.performStart(Activity.java:6959)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2920)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3018) 
                  at android.app.ActivityThread.-wrap14(ActivityThread.java) 
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1653) 
                  at android.os.Handler.dispatchMessage(Handler.java:102) 
                  at android.os.Looper.loop(Looper.java:154) 
                  at android.app.ActivityThread.main(ActivityThread.java:6724) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520) 
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410) 

此错误指向

       String id = bundle.getString("id");

我将列出从

传输数据的类
 public class Year extends AppCompatActivity {
ImageView back;
GridView grid;

String id;
String type;
String year;

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

    Intent data = getIntent();
    year = data.getStringExtra("year");
    id = data.getStringExtra("id");
    type = data.getStringExtra("type");
    BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
    //show the original color of icons
    bottomNavigationView.setItemIconTintList(null);

    bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            Fragment selectedFragment = null;
           final Bundle bundle = new Bundle() ;
            Intent intent;
            switch (item.getItemId()) {
                case R.id.action_item1:

                    bundle.putString("year",year);
                    bundle.putString("id",id);
                    bundle.putString("type",type);

                    //selectedFragment.setArguments(bundle);
                    selectedFragment = new CardFragment();
                    selectedFragment.setArguments(bundle);
                    break;
                case R.id.action_item2:
                    bundle.putString("year",year);
                    bundle.putString("id",id);
                    bundle.putString("type",type);

                    //selectedFragment.setArguments(bundle);
                    selectedFragment = new AudioFragment();
                    selectedFragment.setArguments(bundle);
                    break;
                case R.id.action_item3:

                    bundle.putString("year",year);
                    bundle.putString("id",id);
                    bundle.putString("type",type);

                    //selectedFragment.setArguments(bundle);
                    selectedFragment = new VideoFragment();
                    selectedFragment.setArguments(bundle);
                    break;
            }
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.content_frame2, selectedFragment);
            transaction.commit();

            return true;
        }
    });

    //Manually displaying the first fragment - one time only
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.content_frame2, new CardFragment());
    transaction.commit();


    back = (ImageView)findViewById(R.id.back_year);
    back.setOnClickListener(new AdapterView.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(intent);
        }
    });
}
}

我的片段是

public class CardFragment extends Fragment {

//    String id;
//    String type;
//    String year;
private ListAdapter adapter;
TextView textView;
private ListView lv;
private List<ListItemsData> list = new ArrayList<ListItemsData>();
private static final String url = "http://10.94.0.204/WebApplication7/api/subjects";


public CardFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle bundle = this.getArguments();


}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View rootView = inflater.inflate(R.layout.fragment_card, container, false);
    //final ArrayList<ListItemsData> listItem = GetlistItems();


    Bundle bundle = this.getArguments();
    String id = bundle.getString("id");
    String year = bundle.getString("year");
    String type = bundle.getString("type");

    final Activity mActivity = this.getActivity();
    // lv.setAdapter(new ListAdapter(getActivity(), listItem));
    adapter = new ListAdapter(getContext(), list);
    lv.setAdapter(adapter);


    try {
        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        String URL = "http://10.94.0.204/WebApplication7/api/subjects";
        JSONObject jsonBody = new JSONObject();
        // jsonBody.put("tblRegisteredUsers_nickName", username.getText().toString().trim());
        jsonBody.put("id", id.toString());
        jsonBody.put("Type", type.toString());
        jsonBody.put("Year", year.toString());


        final String requestBody = jsonBody.toString();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                if (response.equals("success")) {
                    //login authenticated. Start the next activity of your app
                    Toast.makeText(getActivity(), response.toString(), Toast.LENGTH_LONG).show();
                    // Toast.makeText(getApplicationContext(), "registered successfully ", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(getActivity(), MainActivity.class);
//                        intent.putExtra("id", Id);
//                        intent.putExtra("year", year);
                    startActivity(intent);
                } else {
                    //login failed. prompt to re-enter the credentials
                    Toast.makeText(mActivity.getApplicationContext(), "Failed to log In", Toast.LENGTH_SHORT).show();

                    Log.i("VOLLEY", response);
                    Toast.makeText(mActivity.getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("VOLLEY", error.toString());
            }
        })

        {
            @Override
            public String getBodyContentType() {
                return "application/json; charset=utf-8";
            }

            @Override
            public byte[] getBody() throws AuthFailureError {
                try {
                    return requestBody == null ? null : requestBody.getBytes("utf-8");
                } catch (UnsupportedEncodingException uee) {
                    VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                    return null;
                }
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String responseString;
                String json = null;

                try {
                    json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                responseString = String.valueOf(json).trim();
                ArrayList<Response4> list_response = new ArrayList<Response4>();
                Type listType = new TypeToken<List<Response4>>() {
                }.getType();
                list_response = new Gson().fromJson(responseString, listType);
                //String check = list.get(0).getMessagesName();

                for (int i = 0; i < list_response.size(); i++) {

//                        JSONObject obj = response.getJSONObject(i);
                          ListItemsData listItemData = new ListItemsData();
                    listItemData.setItem(list_response.get(i).getMessagesName());
                    listItemData.setUrl(list_response.get(i).getMessageURLNew());

                    //listItemData.setUrl((obj.getString("url")));
                    list.add(listItemData);


                    //Id = list.get(0).getId();
                    // year = list.get(0).getYear();
                    //Response2 yourModel = new Gson().fromJson(responseString, Response2.class);
                }

                // i should have this peice of code for methods that are in the background
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyDataSetChanged();
                    }
                });

                //  String Check =  yourModel.getMessagetitle();
                return Response.success(list_response.toString(), HttpHeaderParser.parseCacheHeaders(response));
            }
        };

        requestQueue.add(stringRequest);
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return rootView;
}
我正以正确的方式发送数据吗? 任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

从片段中获取捆绑包时,您应该使用 getArguments()。 得到像这样的包

 public View onCreateView(LayoutInflater inflater, ViewGroup containerObject,Bundle savedInstanceState){
     //here is your arguments
     Bundle bundle=getArguments(); 
     //get string like this
     String year = bundle.getString("year");
 }

编辑:创建一个这样的函数,并从导航菜单中添加到默认片段以及其他片段。

private Bundle getBundle(Intent data){
Bundle bundle = new Bundle();
bundle.putString("year",data.getStringExtra("year"));
bundle.putString("id",data.getStringExtra("id"));
bundle.putString("type",data.getStringExtra("type"));
}

这是最终代码

    public class Year extends AppCompatActivity {
    ImageView back;
    GridView grid;

    String id;
    String type;
    String year;

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

        Intent data = getIntent();
        //get a bundle set and ready to use anytime
        Bundle myBundle= getBundle(data);

        BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
        //show the original color of icons
        bottomNavigationView.setItemIconTintList(null);

        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                Fragment selectedFragment = null;

                switch (item.getItemId()) {
                    case R.id.action_item1:
                        selectedFragment = new CardFragment();
                        selectedFragment.setArguments(myBundle);
                        break;
                    case R.id.action_item2:
                        selectedFragment = new AudioFragment();
                        selectedFragment.setArguments(myBundle);
                        break;
                    case R.id.action_item3:
                        selectedFragment = new VideoFragment();
                        selectedFragment.setArguments(myBundle);
                        break;
                }
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.replace(R.id.content_frame2, selectedFragment);
                transaction.commit();

                return true;
            }
        });

        //Manually displaying the first fragment - one time only
        CardFragment myCardFragment = new CardFragment();
        myCardFragment.setArguments(myBundle);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.content_frame2, myCardFragment);
        transaction.commit();


        back = (ImageView)findViewById(R.id.back_year);
        back.setOnClickListener(new AdapterView.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(intent);
            }
        });
    }

 private Bundle getBundle(Intent data){
    Bundle bundle = new Bundle();
    bundle.putString("year",data.getStringExtra("year"));
    bundle.putString("id",data.getStringExtra("id"));
    bundle.putString("type",data.getStringExtra("type"));
    }

    }