0

please help with this issue I am facing:

I am trying to call a method from a class which will connect to a php service. It has none errors but when I run it, it is closed with the message sorry, the app was stoped.

this is the Main activity:

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    public String result;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void hhtp(View view) throws Exception {
        result="";
        JavaHttpUrlConnectionReader con = new JavaHttpUrlConnectionReader();
        result = con.doHttpUrlConnectionAction("http://example.com/app.php");
        Toast.makeText(getApplicationContext(),"Button is clicked"+result,Toast.LENGTH_LONG).show();
    }
}

this is the class:

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

public class JavaHttpUrlConnectionReader {

    public static void main(String[] args)
            throws Exception
    {
        new JavaHttpUrlConnectionReader();
    }
   public String doHttpUrlConnectionAction(String desiredUrl)
            throws Exception
    {
        URL url = null;
        BufferedReader reader = null;
        StringBuilder stringBuilder;

        try
        {
            // create the HttpURLConnection
            url = new URL(desiredUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // just want to do an HTTP GET here
            connection.setRequestMethod("GET");

            // uncomment this if you want to write output to this url
            //connection.setDoOutput(true);

            // give it 15 seconds to respond
            connection.setReadTimeout(15*1000);
            connection.connect();

            // read the output from the server
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            stringBuilder = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null)
            {
                stringBuilder.append(line + "\n");
            }
            return stringBuilder.toString();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            throw e;
        }
        finally
        {
            // close the reader; this can throw an exception too, so
            // wrap it in another try/catch block.
            if (reader != null)
            {
                try
                {
                    reader.close();
                }
                catch (IOException ioe)
                {
                    ioe.printStackTrace();
                }
            }
        }
    }
}

this is the main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/http_url_request_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="hhtp"
        android:text="Checa si hay nueva Sol" />

</android.support.constraint.ConstraintLayout>

and finally this is the web service in php:

<?php
$data=$_POST['dato'];
$rsp="1";
echo $rsp;
?>
Milad Bahmanabadi
  • 1,047
  • 11
  • 23
Luis
  • 1

2 Answers2

1

You are doing a network call on UI thread, which has thrown the exception. Try using an AsyncTask class, and do network connections from there.

  • thank you for replay, now, if I use AsyncTask then how can I get the websevice response back into my variable result? I need this one to trigger new tasks depending of the value of it. – Luis Dec 05 '18 at 19:23
1

You are experiencing the "Networking on the Main Thread" exception! Congratulations, you are now a L2 Android developer :D

This is enforced by the Android OS in order to make sure apps are not being non-responsive and to ensure that developers are handling asynchronous work, well... asynchronously!

See the rationale here --> https://developer.android.com/reference/android/os/NetworkOnMainThreadException

There are several ways of approaching a solution here - AsyncTasks, Runnables, Handlers, Java Futures, Kotlin Coroutines, Rx (in approximate order of complexity).

Here are some similar questions that have been answered in the past around this issue:

Good luck, and post back here if you can't find the way forward!

jesses.co.tt
  • 2,628
  • 1
  • 29
  • 48