Search code examples
androidandroid-listviewandroid-arrayadapterlinkify

Using Linkify in ListView's ArrayAdapter causes RuntimeException


I have a TextView in my ArrayAdapter that may contain some hyperlinks. For those links I use Linkify:

public View getView(int position, View convertView, ViewGroup parent) {
    View rowView = convertView;
    if (rowView == null) {
        rowView = inflater.inflate(R.layout.list_item_2, null);
        holder = new ViewHolder();

        holder.content = (TextView) rowView.findViewById(R.id.postContent);
        holder.date = (TextView) rowView.findViewById(R.id.postDate);

        rowView.setTag(holder);
    } else {
        holder = (ViewHolder) rowView.getTag();
    }

    holder.content.setText(contents.get(position));
    holder.date.setText(dates.get(position));

    Linkify.addLinks(holder.content, Linkify.ALL);

    return rowView;
}

But because the Linkify is added in the ArrayAdapter, I get an exception saying this:

08-05 16:42:16.715: E/AndroidRuntime(20598): FATAL EXCEPTION: main
08-05 16:42:16.715: E/AndroidRuntime(20598): android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
08-05 16:42:16.715: E/AndroidRuntime(20598):    at android.app.ContextImpl.startActivity(ContextImpl.java:921)
08-05 16:42:16.715: E/AndroidRuntime(20598):    at android.content.ContextWrapper.startActivity(ContextWrapper.java:283)
08-05 16:42:16.715: E/AndroidRuntime(20598):    at android.text.style.URLSpan.onClick(URLSpan.java:62)

How can I make this work? I can't think of an alternative.


Solution

  • Looking at the exception in the log, it seems that you used the application context when you allocate your ArrayAdapter. For example, if your code looks similar to the following:

        listView.setAdapter(new ArrayAdapter<String>(context,
                android.R.layout.simple_list_item_1,
                data) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                // ...
            }
        });
    

    You must have initialized the context variable above with the application context, like this:

        Context context = getApplicationContext();
    

    To avoid the error, you should have initialized it with your Activity instance instead:

        Context context = this;
    

    Or, if your code is in a Fragment:

        Context context = getActivity();