1

I am trying to get strings from the text file from server and show it on ListView. I am calling getTextListFromUrl() from pull to refresh, by overriding the method onRefersh(). But I am stuck somewhere. Here is my code

public class ScreenTwoActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {

    private static final String CLASS_TAG = ScreenTwoActivity.class.getSimpleName();

    private ListView mLvData;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private ArrayAdapter<String> mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_screen_2);

        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_referesh_layout);
        mLvData = (ListView) findViewById(R.id.lv_screen_2);
        mSwipeRefreshLayout.setOnRefreshListener(this);
    }

    @Override
    public void onRefresh() {
        getRefreshContent();
    }

    /**
     * On swipe refresh new data will being fetched from list
     */
    private void getRefreshContent() {

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mAdapter = new ArrayAdapter<String>(ScreenTwoActivity.this, android.R.layout.simple_list_item_1, getTextListFromUrl());
                mLvData.setAdapter(mAdapter);
                mSwipeRefreshLayout.setRefreshing(false);
            }
        }, 1000);
    }

    private List<String> getTextListFromUrl() {

        List<String> listTextData = new ArrayList<>();
        try {
            URL textUrl = new URL("http://thehealthybillion.com/assignment/q3.txt");
            BufferedReader bufferReader = new BufferedReader(new InputStreamReader(textUrl.openStream()));
            String stringBuffer;
            while ((stringBuffer = bufferReader.readLine()) != null) {
                Log.i(CLASS_TAG, stringBuffer);
                listTextData.add(stringBuffer);
            }
            bufferReader.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  listTextData;
    }
}

This is the error I am getting on log

android.os.NetworkOnMainThreadException
            at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
            at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
            at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
            at java.net.InetAddress.getAllByName(InetAddress.java:214)
            at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
            at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
            at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
            at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)
            at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
            at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:179)
            at java.net.URL.openStream(URL.java:470)
            at com.thb.vidyanand.assignmentthb.ScreenTwoActivity.getTextListFromUrl(ScreenTwoActivity.java:86)
            at com.thb.vidyanand.assignmentthb.ScreenTwoActivity.access$100(ScreenTwoActivity.java:22)
            at com.thb.vidyanand.assignmentthb.ScreenTwoActivity$1.run(ScreenTwoActivity.java:66)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:149)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)
            at dalvik.system.NativeStart.main(Native Method)

Can anyone tell me what is going wrong with this?

Prudhvi
  • 2,276
  • 7
  • 34
  • 54
Vid
  • 1,012
  • 1
  • 14
  • 29

3 Answers3

1

You're doing network related task on your main thread (UI thread) so it's throwing NetworkOnMainThreadException. Move all the heavy network related work to a worker thread by using AyncTask or Handler.

Even after using Handler if you're still getting the exception, add the below code in your Activity's onCreate().

if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy); 
}

Source: Error StrictMode$AndroidBlockGuardPolicy.onNetwork

Refer: StrictMode for more info.

Community
  • 1
  • 1
Prudhvi
  • 2,276
  • 7
  • 34
  • 54
0

When you are connecting to internet you need use AsyncTask and call it from doInBackground method.

Your error can be solve use StrictMode.enableDefaults() in your onCreate, but use this only for debug.

Santiago
  • 1,744
  • 15
  • 23
0

Use async task to fetch the data from the server, Dont do network related stuffs in main thread. Please refer this links:

How to fix android.os.NetworkOnMainThreadException?

android.os.NetworkOnMainThreadException with android 4.2

Community
  • 1
  • 1
Rubanraj Ravichandran
  • 1,213
  • 2
  • 17
  • 26