0

I need to make a simple app with button that will call some URL. I got an apache server at my Rpi which I use to control GPIO by sending GET URL like this

http://192.168.0.105/index.php?pin=2&status=0.

In android studio I have only made a onclick button.

Problem is that I'm noob at java and android, so here's my question - what's the easiest way to make this button send URL? I found some tutorials about sending or receiving data from server but that's not what I want to do.

androidstudio

kiner_shah
  • 3,939
  • 7
  • 23
  • 37

4 Answers4

1

You can use this code inside of buttons on click event. To open URL on click.

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("<your URL>"));
startActivity(browserIntent);

Also if you want to connect as a web client, but not want to open in browser - you can use:

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.someplace.com");

ResponseHandler<String> resHandler = new BasicResponseHandler();
String page = httpClient.execute(httpGet, resHandler);
iluu
  • 406
  • 3
  • 13
  • 1
    Also add the fact that you need to add permission to the manifest (``) and you can not work with the network in the UI thread. The code must be run in another thread or wrap it in AsyncTask – congard Nov 17 '18 at 16:41
1
  1. Add permission to manifest: <uses-permission android:name="android.permission.INTERNET" />

  2. Create a class:

    class RequestTask extends AsyncTask<String, String, String> {
        String response;
        ProgressDialog dialog;
    
        @Override
        protected String doInBackground(String... params) {
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(params[0]); // or HttpPost if you need
    
                ResponseHandler<String> resHandler = new BasicResponseHandler();
                response = httpClient.execute(httpGet, resHandler);
           } catch (Exception e) {
               System.out.println("E: " + e);
           }
    
           return null;
        }
    
        @Override
        protected void onPreExecute() {
            dialog = new ProgressDialog(MainActivity.this);
            dialog.setMessage("Loading...");
            dialog.setIndeterminate(true);
            dialog.setCancelable(true);
            dialog.show();
            super.onPreExecute();
        }
    
        @Override
        protected void onPostExecute(String result) {
            dialog.dismiss();
            super.onPostExecute(result);
        }
    }
    
  3. To call use: new RequestTask().execute("http://192.168.0.105/index.php?pin=2&status=0")
congard
  • 945
  • 2
  • 10
  • 28
  • Thanks for your great reply! But i'm getting some errors, any idea which libraries im missing ? [photo](https://imgur.com/a/jZlaWH2) – Slippin Jimmy Nov 17 '18 at 18:31
  • @SlippinJimmy I updated the answer, and this class needs to be inserted into `MainActivity.java`. Automatic placement of imports is described here: https://stackoverflow.com/a/16616085/9200394 – congard Nov 17 '18 at 20:31
  • thanks, i also needed to implement 'org.apache.httpcomponents:httpcore:4.4.5' and 'org.apache.httpcomponents:httpclient:4.5'. But im still getting one more error [photo](https://imgur.com/a/gcCPT7S) – Slippin Jimmy Nov 18 '18 at 09:40
  • @SlippinJimmy paste your code here, I will make all the necessary corrections: https://codeshare.io/5oX99r – congard Nov 18 '18 at 11:54
  • I pasted my code in that link you gave me. Now im getting some other error [photo](https://imgur.com/a/0udrhbC) – Slippin Jimmy Nov 18 '18 at 12:29
  • @SlippinJimmy With your java code now everything is ok, the problem is now in build.gradle. The solution to this problem is described [here](https://stackoverflow.com/questions/48958884/error-more-than-one-file-was-found-with-os-independent-path-meta-inf-dependenc). – congard Nov 18 '18 at 12:36
  • It's working now. Thanks a lot for helping me with this! God bless you kind man. – Slippin Jimmy Nov 18 '18 at 14:52
0

The easiest way is to use volley library.

In manifest declare internet permission outside application tag : <uses-permission android:name="android.permission.INTERNET" />

In build.gradle file add this line inside dependencies: implementation 'com.android.volley:volley:1.0.0'

Create a java file named VolleySingleton and copy the file contents from the file in github just don't copy the package name.

Inside the button click add these lines:

url = "http://192.168.0.105/index.php";
StringRequest postRequest = new StringRequest(Request.Method.POST, url, 
    new Response.Listener<String>() 
    {
        @Override
        public void onResponse(String response) {
            // response
            Log.d("Response", response);
            //Do what ever you need to do with the response here.
            //If you don't need to return any response just echo OK from the php so that you become sure that the thing is working fine.
        }
    }, 
    new Response.ErrorListener() 
    {
         @Override
         public void onErrorResponse(VolleyError error) {
             // error
             Log.d("Error.Response", response);
       }
    }
) {     
    @Override
    protected Map<String, String> getParams() 
    {  
            Map<String, String>  params = new HashMap<String, String>();  
            params.put("pin", "2");  
            params.put("status", "0");

            return params;  
    }
};

VolleySingleton.getmInstance(getApplicationContext()).addToRequestQue(postRequest);
Sayok Majumder
  • 1,012
  • 13
  • 28
  • Thanks a lot for replay! Do i need some extra implementation for my MainActivity to run it ? [photo](https://imgur.com/a/XLD9xaK) – Slippin Jimmy Nov 17 '18 at 19:23
0

I have created a similar functionality

See if you find it helpful

You need to get the permission to use Internet. In manifest file, declare internet permission outside application tag : <uses-permission android:name="android.permission.INTERNET" />

Create an activity (WebViewActivity.java)

public class WebViewActivity extends AppCompatActivity {

private static final String TAG = "WebViewActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_web_view);

    Log.d(TAG, "onCreate: Started");

    Bundle extras = getIntent().getExtras();
    assert extras != null;
    String pin = extras.getString("pin"); //you can use getInt("pin") also, but afterwards in the url, it will be converted to String back, so it is not needed
    String status = extras.getString("status"); //you can use getInt("status") also, but afterwards in the url, it will be converted to String back, so it is not needed

    WebView webView = new WebView(this);
    setContentView(webView);
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true); //This is required to enable javascript that is required by some pages
    String url = "http://192.168.0.105/index.php?pin" + pin + "&status=" + status;

    webView.loadUrl(url);

    Log.d(TAG, "url accessed: " + url);

    finish();//If you need to see the output after accessing the http page, then remove this line. Otherwise just copy as it is 
}

}

In MainActivity, just start the above created activity.

public class MainActivity extends AppCompatActivity{
    int pin = 0, status = 2;// You can modify the values according to your requirements
    //....
    //....
    button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getApplicationContext(), WebViewActivity.class);
                    intent.putExtra("pin", pin);
                    intent.putExtra("status", status);
                    startActivity(intent);
                    Toast.makeText(MainActivity.this, "URL Opened and pin, status values are successfully updated", Toast.LENGTH_SHORT).show();

                }
            });
    //....
    //....
}

If you are wondering what to put in the xml file(activity_web_view.xml) Just leave as it is, I used the below code to send values just as you are trying to send.

activity_web_view.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".WebViewActivity" />
Kiran
  • 402
  • 1
  • 4
  • 11