填充EditText时出现空指针异常

时间:2015-03-24 08:28:59

标签: java android android-fragments

我正在尝试使用其他应用中收到的文字填充EditText Fragment中的NullPointerException

EditText包含一个值,但我不确定为什么我会得到public class AddTab extends Fragment implements View.OnClickListener { View view; Button mButton; EditText textBox; String url; private OnFragmentInteractionListener mListener; public AddTab() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment view = inflater.inflate(R.layout.fragment_add, container, false); mButton = (Button)view.findViewById(R.id.button); textBox = (EditText) view.findViewById(R.id.editText); mButton.setOnClickListener( new View.OnClickListener() { public void onClick(View view) { //some code } }); return view; } ... // some other methods public void receiveURL(String url) { textBox.setText(url); //this is where I'm getting the exception. Does EditText hold the value it has got in onCreateView()?? } }

这是我的片段类:

03-24 13:30:56.986    7424-7424/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.nikhil.amazon1, PID: 7424
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.nikhil.amazon1/com.example.nikhil.amazon1.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            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:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
            at com.example.nikhil.amazon1.AddTab.receiveURL(AddTab.java:122)
            at com.example.nikhil.amazon1.MainActivity.handleSendText(MainActivity.java:102)
            at com.example.nikhil.amazon1.MainActivity.onCreate(MainActivity.java:82)
            at android.app.Activity.performCreate(Activity.java:5933)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            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:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

如何在此处正确更新片段的UI。 iepopulate我的EditText与传递给receiveURL方法的值?

请帮忙吗?

谢谢!

编辑:

StackTrace:

public class MainActivity extends FragmentActivity implements ListTab.OnFragmentInteractionListener, AddTab.OnFragmentInteractionListener{
PendingIntent pendingIntent;
MyPagerAdapter objAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ViewPager pager = (ViewPager) findViewById(R.id.pager);
    objAdapter = new MyPagerAdapter(getSupportFragmentManager());
    pager.setAdapter(objAdapter);
    // Bind the tabs to the ViewPager
    PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
    pager.setCurrentItem(1);
    tabs.setShouldExpand(true);
    tabs.setViewPager(pager);
    //code for listening to intent from browser or other apps
    // Get intent, action and MIME type
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();
    if (Intent.ACTION_SEND.equals(action) && type != null) {
        if ("text/plain".equals(type)) {
            handleSendText(intent); // Handle text being sent
        }
    }
}

void handleSendText(Intent intent) {
    String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
    if (sharedText != null) {
        Fragment f = objAdapter.getItem(1);
        AddTab t = (AddTab) f;
        t.receiveURL(sharedText); 
      //from here I'm calling
    }
 }
}

MainActivity类:从这个类我正在调用receiveURL()方法。

pagerslidingtabstrip

我正在使用AddTab来创建标签页。我获得了适配器的引用并得到了我的片段receiveURL().的实例。然后调用我的方法{{1}}

只有当用户从其他应用程序共享URL(文本)时,才会发生这一切。

3 个答案:

答案 0 :(得分:0)

在片段中创建一个全局变量,如

String receivedUrl;
在您的receiveURL方法中

进行如下更改:

        public void receiveURL(String url)
{
    receivedUrl = url;
}

在onCreateView中进行以下更改

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    view = inflater.inflate(R.layout.fragment_add, container, false);

    mButton = (Button)view.findViewById(R.id.button);
    textBox = (EditText) view.findViewById(R.id.editText);
    textBox.setText(receivedUrl);

    mButton.setOnClickListener(
            new View.OnClickListener()
            {
                public void onClick(View view)
                {
                 //some code                      
                }
            });

    return view;
}

希望这有效。

编辑:

进行以下更改。在你的onCreate for MainActivity中。

        String url;
Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    if (Intent.ACTION_SEND.equals(action) && type != null) {
        if ("text/plain".equals(type)) {
            url = handleSendText(intent); // Handle text being sent
        }
    }

    ViewPager pager = (ViewPager) findViewById(R.id.pager);
    objAdapter = new MyPagerAdapter(getSupportFragmentManager());
    pager.setAdapter(objAdapter);

    // Bind the tabs to the ViewPager
    PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);

    pager.setCurrentItem(1);

    tabs.setShouldExpand(true);

    tabs.setViewPager(pager);

    //code for listening to intent from browser or other apps

    // Get intent, action and MIME type

}

String handleSendText(Intent intent) {
    String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
    if (sharedText != null) {
        return sharedText;
    }
    return null;
}

在MyPagerAdapter中

getItem(int arg0) {
    Fragment f = null;
    AddTab tab = new AddTab();
    tab.requireUrl(url);
    f = tab;
    return f;
}

答案 1 :(得分:0)

在设置文字之前,请尝试使用以下代码重新初始化您的编辑文字:

 textBox = (EditText) getView().findViewById(R.id.editText);

另外请分享一下,如果它没有用,你如何调用receiveURL方法。

答案 2 :(得分:0)

尝试使用本地广播

BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String g=i.getStringExtra("key")
             textBox.setText(g);

        }
    };

在AddTab的onCreateView中注册接收器..

getActivity().registerReceiver(receiver, new IntentFilter("refresh"));

从您需要更新textview的地方调用广播

Intent refreshIntent = new Intent("refresh");
                refreshIntent.putExtra("key", "valueto be passed");
            getActivity().sendBroadcast(refreshIntent);

不要忘记取消注册onDestroyView

中的广播
@Override
    public void onDestroyView() {
        // TODO Auto-generated method stub
        super.onDestroyView();
        getActivity().unregisterReceiver(receiver);
        ButterKnife.reset(this);
    }