Search code examples
androidexceptionhttpconnectionnetworkonmainthread

Error : When Connecting To WebService


I have written a program and connected it to mysql. I have written a web service class and using http client , but I have runtime error , please check my code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class WebService {
    public static String readUrl(String url) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        try {
            HttpResponse httpResponse = httpClient.execute(httpPost);
            InputStream inputStream = httpResponse.getEntity().getContent();
            String result = convertInputStreamToString(inputStream);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String convertInputStreamToString(InputStream inputStream) {
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuilder = new StringBuilder();

            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            return stringBuilder.toString();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });


    String result = WebService.readUrl("http://localhost/note-server/");
    if (result != null) {
        try {
            JSONArray tasks = new JSONArray(result);
            for(int i=0;i<tasks.length();i++){
                JSONObject task=tasks.getJSONObject(i);
                Log.i("L",task.getString("task tilte"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

and here is the error code that I have:

at com.example.parisa.noteapplication.WebService.read Url(WebService.java:26)


at com.example.parisa.noteapplication.MainActivity.on Create(MainActivity.java:47)


    FATAL EXCEPTION: main
    Process: com.example.parisa.noteapplication, PID: 29346
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.parisa.noteapplication/com.example.parisa.noteapplication.MainActivity}: android.os.NetworkOnMainThreadException
    at android.app.ActivityThread.performLaunchActivity(A ctivityThread.java:2462)

and here

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });


    String result = WebService.readUrl("http://localhost/note-server/");
    if (result != null) {
        try {
            JSONArray tasks = new JSONArray(result);
            for(int i=0;i<tasks.length();i++){
                JSONObject task=tasks.getJSONObject(i);
                Log.i("L",task.getString("task tilte"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

Solution

  • You have to run this readurl method on the thread separately ,

    You are not able to use urlthread for the things that are related to webservices.

    Thanks in advance