Home > Software design >  add to recycler view if URL is valid
add to recycler view if URL is valid

Time:11-27

I want to check the URL in the edittext and if it was valid, add an item in recycler view. So for this purpose, I started a thread to check the HTTP connection.

 thread = new Thread(new Runnable() {
                    @Override
                    public void run() {

                        String link = edt.getText().toString();
                        URL url = null;
                        try {
                            url = new URL(link);
                            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                            int code = connection.getResponseCode();

                            if(code == 200) {
                                Log.d(TAG, "reachable");
                                InsertItem(url,adapter);
                            } else {
                                Log.d(TAG, "in catch: not reachable");
                            }
                        }  catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
                thread.start();

the problem is the error I get when try to add an item

 private void InsertItem(URL url, MyAdapter adapter) {
        thread.currentThread().interrupt();
        arrayList.add(0,new file(url.toString()));
        adapter.notifyItemChanged(0);
};

and the error is:

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

CodePudding user response:

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

Looks like inside your new thread, you are calling InsertItem(url,adapter)(should begin with a lower case 'I') which is trying to perform some work on a UI element.

As the error states you cannot touch the views outside of the UI thread. You can try adding runOnUiThread(() -> insertItems(url,adapter) inside your thread to post the action to the UI thread.

  • Related