Triscus
Triscus

Reputation: 320

Java Android - Call URL when button is pressed without opening browser

I want to make a simple Android App with buttons that calls a URL on an Arduino Device to switch lights on and off. It's not neccesary to open a webbrowser.

I am fairly new to Android and I already searched here and found some suggestions, but they didn't work for me.

Maybe someone can put me in the right direction?

Here is my code so far, when I press the button, nothing happens.

package de.triscus.arduinoweb;


import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.view.View.OnClickListener;


import java.io.IOException;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class HomeLight extends AppCompatActivity implements OnClickListener {
    String msg = "Android : ";
    private Button lichterkette1;

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

        lichterkette1 = (Button) findViewById(R.id.Lichterkette1);
        lichterkette1.setOnClickListener(this);
    }

    public void onClick(View v) {
        URL url = null;
        HttpURLConnection urlConnection = null;
        switch (v.getId())

        {
            case R.id.Lichterkette1:

                try {

                    url = new URL("http://192.168.2.106/?Lichterkette=1");
                    urlConnection = (HttpURLConnection) url.openConnection();
                    // urlConnection = (HttpURLConnection) url.openConnection();
                    Log.d(msg, "Lichterkette1 pressed");
                    //InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                    //  Log.d(msg, InputStream);

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                    Log.d(msg, "URL Malformed");
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.d(msg, "IO exception");
                } finally {
                    urlConnection.disconnect();
                    Log.d(msg, "Disconnected");
                }

        }


    }


}

and here is the logcat output:

03-16 15:19:26.133 9805-9805/? I/art: Late-enabling -Xcheck:jni
03-16 15:19:26.143 9805-9805/? I/art: VMHOOK: rlim_cur : 0 pid:9805
03-16 15:19:26.173 9805-9815/? I/art: Debugger is no longer active
03-16 15:19:26.193 9805-9805/? E/Typeface: SANS_LOC file not found.
03-16 15:19:26.584 9805-9805/? D/Atlas: Validating map...
03-16 15:19:26.684 9805-9835/? I/Adreno-EGL: <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LA.AF.1.1_RB1.05.00.02.006.020 - CR771817 ()
                                             OpenGL ES Shader Compiler Version: E031.25.03.06
                                             Build Date: 03/04/15 Wed
                                             Local Branch: 
                                             Remote Branch: refs/tags/AU_LINUX_ANDROID_LA.AF.1.1_RB1.05.00.02.006.020
                                             Local Patches: NONE
                                             Reconstruct Branch: NOTHING
03-16 15:19:33.481 9805-9805/de.triscus.arduinoweb D/Android :: Lichterkette1 pressed
03-16 15:19:33.481 9805-9805/de.triscus.arduinoweb D/Android :: Disconnected
03-16 15:19:34.832 9805-9805/de.triscus.arduinoweb D/Android :: Lichterkette1 pressed
03-16 15:19:34.832 9805-9805/de.triscus.arduinoweb D/Android :: Disconnected

Thank you in advance

Triscus

P.S.: Internet/Network usage is allowed

Upvotes: 2

Views: 10787

Answers (2)

Andan H M
Andan H M

Reputation: 793

Network oprations/call cannot be done main thread. You need to run it from another thread or asynchronous task or an intent service

Note : All UI opration shoud be done onPostExecute,onPreExecute

The below code may help you to solve.

public void onClick(View v) {
switch (v.getId())
{
   new Lichterkette().execute();
 }
}


    class Lichterkette extends AsyncTask<String,Void,String>{
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected String doInBackground(String... params) {
                StringBuilder sb=null;
                BufferedReader reader=null;
                String serverResponse=null;
                try {

                    URL url = new URL("http://192.168.2.106/?Lichterkette=1");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    connection.setConnectTimeout(5000);
                    connection.setRequestMethod("GET");
                    connection.connect();
                    int statusCode = connection.getResponseCode();
                    //Log.e("statusCode", "" + statusCode);
                    if (statusCode == 200) {
                        sb = new StringBuilder();
                        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        String line;
                        while ((line = reader.readLine()) != null) {
                            sb.append(line + "\n");
                        }
                    }

                    connection.disconnect();
                    if (sb!=null)
                        serverResponse=sb.toString();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                return serverResponse;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
               //All your UI operation can be performed here
                System.out.println(s);
            }
        }

Upvotes: 4

nbroeking
nbroeking

Reputation: 8928

I am going to answer this question as general as possible in the hopes that it helps not just you but others. The class your looking for is called an HttpPost or an HttpGet. Although the URLConnection you are using should work too. HttpPost and HttpGet are not ASYNC so you need probably want to run it from another thread or an intent service.

You can send post requests like the following

HttpPost post = new HttpPost(String.format(<Your URL goes here>));

try {
    //Set the header for the http post
    post.setHeader("Content-type", "application/x-www-form-urlencoded");

    //Set the contents of the http post (JSON FORMAT)  
    post.setEntity(new StringEntity(<JSON STRING>));

    //Send the post and get the response back
    HttpClient client = this.createHttpClient();
    HttpResponse response = client.execute(post);
    //process your response here

} catch (Exception e) {
    Log.e(TAG, "Error", e);
}

Http Gets follow roughly the same format.

This is a really quick straight forward way to send out get and post requests without using a browser. The only issue is that they are not async, like I mentioned before but it is really important. They work with any rest api. So the only catch is that you need to make sure your Arduino is acting like a proper webserver.

Upvotes: 0

Related Questions