片段上的空指针异常

时间:2015-12-23 05:55:00

标签: android android-fragments android-studio

我知道这是一个重复的问题,但我无法为我找到正确的答案 我正在尝试将一些数据从我的OrderMadeFragment发送到OrderTakenFragment,但我无法

这是我的课程

OrderMadeFragment

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

/**
 *  on 12/22/2015.
 */
public class OrderMadeFragment extends Fragment
{
    SharedPreferences sh_pref;
    SharedPreferences.Editor toEdit;
    Button b;
    EditText e;
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View rootView = inflater.inflate(R.layout.fragment_order_made, container, false);
        sh_pref=getContext().getSharedPreferences("start", getContext().MODE_PRIVATE);
        toEdit = sh_pref.edit();
        b=(Button)rootView.findViewById(R.id.button);
        e=(EditText)rootView.findViewById(R.id.editText);

        b.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                String qv=e.getText().toString();
                OrderTakenFragment ldf = new OrderTakenFragment();
                Bundle args = new Bundle();
                args.putString("YourKey", qv);
                ldf.setArguments(args);
                Log.e("args", args.toString());

//Inflate the fragment
                getFragmentManager().beginTransaction().add(R.id.container, ldf).commit();
            }
        });
        return rootView;
    }
}

OrderTakenFragment

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Created by on 12/22/2015.
 */
public class OrderTakenFragment extends Fragment
{
    TextView v;
    String bn="abc";
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View rootView = inflater.inflate(R.layout.fragment_order_taken, container, false);
        v=(TextView)rootView.findViewById(R.id.textView);
//        String value = getArguments().getString("YourKey");
       // Log.e("YourKey",value);
        v.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                bn = getArguments().getString("YourKey");
            Toast.makeText(getActivity(),bn,Toast.LENGTH_LONG).show();
            }
        });


        return rootView;
    }
}

Logcat错误

12-23 11:17:11.811 10669-10669/com.example.qualwebs.test E/args: Bundle[{YourKey=Name}]
12-23 11:17:16.212 10669-10669/com.example.qualwebs.test E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.qualwebs.test, PID: 10669
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.qualwebs.test.OrderTakenFragment$1.onClick(OrderTakenFragment.java:31)
   at android.view.View.performClick(View.java:4785)
   at android.view.View$PerformClick.run(View.java:19884)
   at android.os.Handler.handleCallback(Handler.java:746)
   at android.os.Handler.dispatchMessage(Handler.java:95)
   at android.os.Looper.loop(Looper.java:135)
   at android.app.ActivityThread.main(ActivityThread.java:5343)
   at java.lang.reflect.Method.invoke(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:372)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:702)

我关注How to send data from one Fragment to another Fragment?链接

4 个答案:

答案 0 :(得分:2)

您应该在OrderTakenFragment的 onCreate() 中请求参数

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

    if(getArguments()!=null)
       value = getArguments().getString("YourKey");

 }

然后在onCreateView()中,在你的onClick()

v.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
          // Use the variable value in your toast
          if(value!=null)
            Toast.makeText(getActivity(),value,Toast.LENGTH_LONG).show();
        }
    });

答案 1 :(得分:1)

确保您的textview v具有:

android:clickable="true"

在你的片段OrderMadeFragment`中:

FragmentManager fragmentManager = getActivity().getSupportFragmentManager();

最好还是在包含活动中创建一个函数:

public void replaceFragment(Fragment fragment) {
    fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.TheID, fragment);
    fragmentTransaction.commit();
}

然后从片段中使用:

((ContainingActivity) getActivity()).replaceFragment(fragment);

这样您就可以管理后台堆栈并控制您的应用导航。

您需要管理片段args。

static final String YOUR_KEY = "YourKey";

private String key_;

public OrderTakenFragment() {
    // Required empty public constructor
 }


public static OrderTakenFragment newInstance(String key_) {
    OrderTakenFragment fragment = new OrderTakenFragment();
    Bundle args = new Bundle();
    args.putString(YOUR_KEY, key_);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        key_ = getArguments().getString(YOUR_KEY);
    }
}

 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    View rootView = inflater.inflate(R.layout.fragment_order_taken, container, false);
    v=(TextView)rootView.findViewById(R.id.textView);
    v.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            if(key_!=null)
            Toast.makeText(getActivity(),key_,Toast.LENGTH_LONG).show();
        }
    });


    return rootView;
}

答案 2 :(得分:0)

你必须从这样的包中获取来自片段的数据:

Bundle bundle = this.getArguments();
bn = bundle.getString("YourKey", "abc");

答案 3 :(得分:0)

我想把这些帖子写成答案。

首先,我认为您希望在同一活动中将OrderTakenFragment替换为getFragmentManager().beginTransaction().add(R.id.container, ldf).commit();

尝试更改此行:

getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, ldf).commit();

要: {{1}}