Using Linkify in ListView's ArrayAdapter causes RuntimeException

送分小仙女□ 提交于 2019-12-01 12:39:14

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();

If you are interested to open a link, you can use

String text = "<a href=\"http://www.google.co.in/\">Google</a>";
holder.content.setText(Html.fromHtml(text));
holder.content.setMovementMethod(LinkMovementMethod.getInstance());

this would would work fine for you inside a ListView.

In your Activity.Java while binding your list with adapter

YourAdapter yourAdapter = new YourAdapter(YourCurrentActivityName.this, YourArrayList);
yourListView.setAdapter(yourAdapter); 

In YourAdapter.java in Constructor make sure it's Activity not Context

public YourAdapter(Activity context, YourArrayList list){
    this.context = context;
    this.list = list;
}

And, use this code for your textview in your adapter for Linkify.

holder.yourTextView.setLinksClickable(true);
holder.yourTextView.setMovementMethod(LinkMovementMethod.getInstance());
Linkify.addLinks(holder.yourTextView, Linkify.ALL);
holder.yourTextView.setAutoLinkMask(Linkify.ALL);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!