0

I'm trying to populate an EditText in my Fragment with received text from other app.

EditText holds a value, but I'm not sure why I'm getting a NullPointerException.

Here is my Fragment Class :

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()??
    }
}

How can I correctly update the fragment's UI here. i.e.populate my EditText with the value passed to receiveURL method?

Any help please?

Thanks!

EDIT :

StackTrace :

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)

MainActivity class : From this class I'm calling receiveURL() method.

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
    }
 }
}

I'm using pagerslidingtabstrip to create tabs. I obtained the adapter's reference and got the instance of my fragment AddTab. Then called my method receiveURL().

All this happens only when user shares a URL (text) from other app.

ceph3us
  • 7,326
  • 3
  • 36
  • 43
Nikhil
  • 6,493
  • 10
  • 31
  • 68

3 Answers3

0

Make a global variable in your fragment like

String receivedUrl;

in your receiveURL method make changes as follows:

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

make following changes in your 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;
}

Hope this works.

EDIT:

Make the following changes. In your 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;
}

In MyPagerAdapter

getItem(int arg0) {
    Fragment f = null;
    AddTab tab = new AddTab();
    tab.requireUrl(url);
    f = tab;
    return f;
}
Roadblock
  • 2,041
  • 2
  • 24
  • 38
  • I tried ur suggestion. I'm not getting any exception. But, theEditText is not updated to reflect the change. I think onCreateView() is not called again. The fragment's UI might be created before call to receiveURl(). – Nikhil Mar 24 '15 at 08:56
  • EditText extends TextView. You can also try using textBox.setText(receivedUrl, TextView.BufferType.EDITABLE); – Roadblock Mar 24 '15 at 09:03
  • A few more suggestions, try handling the intent (handleSendText) in MainActivity immediately after setContentView. – Roadblock Mar 24 '15 at 09:15
  • Thanks @Roadblock for your time. Unfortunately, it didn't work. But I'll take your suggestions. Thanks.:) – Nikhil Mar 24 '15 at 09:23
  • 1
    did you try to check if receivedUrl is blank string? Otherwise it should give a null pointer when you do setText – Roadblock Mar 24 '15 at 09:24
  • Yes, @Roadblock .I think we're getting close. receivedUrl is holding NULL when onResume() is called. I'm able to set another text in textBox now. I think onResume() is getting called before receivedURL(). Any thoughts mate ? :) – Nikhil Mar 24 '15 at 09:34
  • Can you try extracting the intent immediately after setContentView in MainActivity – Roadblock Mar 24 '15 at 09:43
  • 1
    I had faced something similar. I was loading the fragments dynamically in ViewPager. What I did was in getItem(), when I was loading the fragment, I created an object of the fragment class (in your case AddTab). Then on that object call the method receiveUrl and then return that fragment object from getItem(). This worked for me. – Roadblock Mar 24 '15 at 09:49
0

Try initializing again your edit text using below code before you set text :

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

Also please share how are you calling receiveURL method if it didn't worked.

Arun Kumar
  • 194
  • 8
0

Try using local broadcast

BroadcastReceiver receiver = new BroadcastReceiver() {

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

        }
    };

Inside your onCreateView of AddTab register the receiver..

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

call the broadcast from where you need to update the textview

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

And dont forget to unregister the broadcast in onDestroyView

@Override
    public void onDestroyView() {
        // TODO Auto-generated method stub
        super.onDestroyView();
        getActivity().unregisterReceiver(receiver);
        ButterKnife.reset(this);
    }
George Thomas
  • 4,566
  • 5
  • 30
  • 65