• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps [PHP] HelloWorld.php

simhamed

Lurker
Hi!
I'm trying to show my DB's records on my emulator/android (Samsung GSII).
But first I want to test my HTTP connexion, so I first start with a simple HelloWorld.php (a PHP script) that should show 'Hello World'.
So here's where I'm stuck:
Code:
package sim.projet;
 
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
 
public class Projet1Activity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        // Creating HTTP client
        HttpClient httpClient = new DefaultHttpClient();
        // Creating HTTP Post
        HttpPost httpPost = new HttpPost("http://192.168.1.10/android_connect/test.php");
 
        // Making HTTP Request
        try {
            HttpResponse response = httpClient.execute(httpPost); 
            // writing response to log
            Log.i("Http Response:", response.toString());
        } catch (ClientProtocolException e) {
            // writing exception to log
            e.printStackTrace();
        } catch (IOException e) {
            // writing exception to log
            e.printStackTrace();
        }
    }
}
http://192.168.1.10/android_connect/test.php works awesome on my Mozilla browser (it's showing the 'Hello World').
But when I build the projet, it says on my emulator : "The application projet1 stopped".
Anyone to help me please? Thanks in advance! :(

PS : I already added this on my manifest:
Code:
<uses-permission android:name="[COLOR=#8B0000]android.permission.INTERNET[/COLOR]" />
 
The IP you are usinv is a private IP. It can only be accessed by devices on your LAN. I recommend googling what is my IP and clicking the first result. This will give you your networks public IP. Use this instead for making the connection.
 
Thanks for your fast reply!

I've replaced the 192.168 IP with the network public IP (81.xx.xx.xx)
But still, same problem : "The application has stopped".

Code:
05-07 14:45:59.552: I/dalvikvm(613): threadid=3: reacting to signal 3
05-07 14:45:59.851: I/dalvikvm(613): Wrote stack traces to '/data/anr/traces.txt'
05-07 14:46:00.001: I/dalvikvm(613): threadid=3: reacting to signal 3
05-07 14:46:00.063: I/dalvikvm(613): Wrote stack traces to '/data/anr/traces.txt'
05-07 14:46:00.351: D/AndroidRuntime(613): Shutting down VM
05-07 14:46:00.351: W/dalvikvm(613): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
[B]05-07 14:46:00.401: E/AndroidRuntime(613): FATAL EXCEPTION: main[/B]
05-07 14:46:00.401: E/AndroidRuntime(613): java.lang.RuntimeException: Unable to start activity ComponentInfo{sim.projet/sim.projet.Projet1Activity}: android.os.NetworkOnMainThreadException
05-07 14:46:00.401: E/AndroidRuntime(613):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
05-07 14:46:00.401: E/AndroidRuntime(613):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
05-07 14:46:00.401: E/AndroidRuntime(613):     at android.app.ActivityThread.access$600(ActivityThread.java:123)
05-07 14:46:00.401: E/AndroidRuntime(613):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
05-07 14:46:00.401: E/AndroidRuntime(613):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-07 14:46:00.401: E/AndroidRuntime(613):     at android.os.Looper.loop(Looper.java:137)
05-07 14:46:00.401: E/AndroidRuntime(613):     at android.app.ActivityThread.main(ActivityThread.java:4424)
05-07 14:46:00.401: E/AndroidRuntime(613):     at java.lang.reflect.Method.invokeNative(Native Method)
05-07 14:46:00.401: E/AndroidRuntime(613):     at java.lang.reflect.Method.invoke(Method.java:511)
05-07 14:46:00.401: E/AndroidRuntime(613):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-07 14:46:00.401: E/AndroidRuntime(613):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-07 14:46:00.401: E/AndroidRuntime(613):     at dalvik.system.NativeStart.main(Native Method)
05-07 14:46:00.401: E/AndroidRuntime(613): Caused by: android.os.NetworkOnMainThreadException
05-07 14:46:00.401: E/AndroidRuntime(613):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
05-07 14:46:00.401: E/AndroidRuntime(613):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
05-07 14:46:00.401: E/AndroidRuntime(613):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
05-07 14:46:00.401: E/AndroidRuntime(613):     at libcore.io.IoBridge.connect(IoBridge.java:112)
05-07 14:46:00.401: E/AndroidRuntime(613):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
05-07 14:46:00.401: E/AndroidRuntime(613):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
05-07 14:46:00.401: E/AndroidRuntime(613):     at java.net.Socket.connect(Socket.java:842)
05-07 14:46:00.401: E/AndroidRuntime(613):     at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
05-07 14:46:00.401: E/AndroidRuntime(613):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
05-07 14:46:00.401: E/AndroidRuntime(613):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
05-07 14:46:00.401: E/AndroidRuntime(613):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
05-07 14:46:00.401: E/AndroidRuntime(613):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
05-07 14:46:00.401: E/AndroidRuntime(613):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-07 14:46:00.401: E/AndroidRuntime(613):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-07 14:46:00.401: E/AndroidRuntime(613):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
05-07 14:46:00.401: E/AndroidRuntime(613):     at sim.projet.Projet1Activity.onCreate(Projet1Activity.java:26)
05-07 14:46:00.401: E/AndroidRuntime(613):     at android.app.Activity.performCreate(Activity.java:4465)
05-07 14:46:00.401: E/AndroidRuntime(613):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
05-07 14:46:00.401: E/AndroidRuntime(613):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
05-07 14:46:00.401: E/AndroidRuntime(613):     ... 11 more
05-07 14:46:00.671: I/dalvikvm(613): threadid=3: reacting to signal 3
05-07 14:46:00.701: I/dalvikvm(613): Wrote stack traces to '/data/anr/traces.txt'
05-07 14:46:00.981: I/dalvikvm(613): threadid=3: reacting to signal 3
05-07 14:46:01.062: I/dalvikvm(613): Wrote stack traces to '/data/anr/traces.txt'
05-07 14:46:24.162: I/Process(613): Sending signal. PID: 613 SIG: 9
Also, the http://81.xx.xx.xx/android_connect/test.php doesn't work on the browser anymore.
Is there anything wrong? Thanks in advance~
 
You will need to log into your router and forward port 80 to 192.168.1.10. That should solve your problem. Sorry that I forgot to mention that in my last post.
 
Ok, the script works again now on the browser, but there's still the same problem on the emulator.
It doesn't like this line :
Code:
HttpResponse response = httpClient.execute(httpPost);
"Unfortunately, projet1 has stopped"
Code:
05-07 16:00:33.212: I/dalvikvm(940): threadid=3: reacting to signal 3
05-07 16:00:33.382: I/dalvikvm(940): Wrote stack traces to '/data/anr/traces.txt'
05-07 16:00:33.602: D/AndroidRuntime(940): Shutting down VM
05-07 16:00:33.602: W/dalvikvm(940): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
05-07 16:00:33.622: E/AndroidRuntime(940): FATAL EXCEPTION: main
05-07 16:00:33.622: E/AndroidRuntime(940): java.lang.RuntimeException: Unable to start activity ComponentInfo{sim.projet/sim.projet.Projet1Activity}: android.os.NetworkOnMainThreadException
05-07 16:00:33.622: E/AndroidRuntime(940):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
05-07 16:00:33.622: E/AndroidRuntime(940):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
05-07 16:00:33.622: E/AndroidRuntime(940):     at android.app.ActivityThread.access$600(ActivityThread.java:123)
05-07 16:00:33.622: E/AndroidRuntime(940):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
05-07 16:00:33.622: E/AndroidRuntime(940):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-07 16:00:33.622: E/AndroidRuntime(940):     at android.os.Looper.loop(Looper.java:137)
05-07 16:00:33.622: E/AndroidRuntime(940):     at android.app.ActivityThread.main(ActivityThread.java:4424)
05-07 16:00:33.622: E/AndroidRuntime(940):     at java.lang.reflect.Method.invokeNative(Native Method)
05-07 16:00:33.622: E/AndroidRuntime(940):     at java.lang.reflect.Method.invoke(Method.java:511)
05-07 16:00:33.622: E/AndroidRuntime(940):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-07 16:00:33.622: E/AndroidRuntime(940):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-07 16:00:33.622: E/AndroidRuntime(940):     at dalvik.system.NativeStart.main(Native Method)
05-07 16:00:33.622: E/AndroidRuntime(940): Caused by: android.os.NetworkOnMainThreadException
05-07 16:00:33.622: E/AndroidRuntime(940):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
05-07 16:00:33.622: E/AndroidRuntime(940):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
05-07 16:00:33.622: E/AndroidRuntime(940):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
05-07 16:00:33.622: E/AndroidRuntime(940):     at libcore.io.IoBridge.connect(IoBridge.java:112)
05-07 16:00:33.622: E/AndroidRuntime(940):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
05-07 16:00:33.622: E/AndroidRuntime(940):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
05-07 16:00:33.622: E/AndroidRuntime(940):     at java.net.Socket.connect(Socket.java:842)
05-07 16:00:33.622: E/AndroidRuntime(940):     at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
05-07 16:00:33.622: E/AndroidRuntime(940):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
05-07 16:00:33.622: E/AndroidRuntime(940):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
05-07 16:00:33.622: E/AndroidRuntime(940):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
05-07 16:00:33.622: E/AndroidRuntime(940):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
05-07 16:00:33.622: E/AndroidRuntime(940):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-07 16:00:33.622: E/AndroidRuntime(940):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-07 16:00:33.622: E/AndroidRuntime(940):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
05-07 16:00:33.622: E/AndroidRuntime(940):     at sim.projet.Projet1Activity.onCreate(Projet1Activity.java:25)
05-07 16:00:33.622: E/AndroidRuntime(940):     at android.app.Activity.performCreate(Activity.java:4465)
05-07 16:00:33.622: E/AndroidRuntime(940):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
05-07 16:00:33.622: E/AndroidRuntime(940):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
05-07 16:00:33.622: E/AndroidRuntime(940):     ... 11 more
05-07 16:00:33.793: I/dalvikvm(940): threadid=3: reacting to signal 3
05-07 16:00:33.812: I/dalvikvm(940): Wrote stack traces to '/data/anr/traces.txt'
05-07 16:00:34.203: I/dalvikvm(940): threadid=3: reacting to signal 3
05-07 16:00:34.272: I/dalvikvm(940): Wrote stack traces to '/data/anr/traces.txt'
 
This is because you're trying to run your HTTP on main UI thread. HTTP or any network operations tend to block leading to bad UI experience. What android is trying to tell you is to move the operation to a background thread where it won't block.

This only happens if you're API level is >= 11 ( i.e. >= Honeycomb). What it means that you need to spawn off HTTP on different thread by means like AsyncTask Painless Threading | Android Developers. Alternatively you can downgrade your API level to < 11.

If you don't want to change & just want to see if your stuff works you can temporarily disable strict mode settings StrictMode | Android Developers

Hope this helps.
 
OMG it worked! Thank you so much, so that was it!

I changed my android:minSdkVersion="10" to "8", and no more errors.
I didn't know it was from the API level since I was using the 10th.

Now the app opens but it's empty, my 'Hello World' still doesn't show.
So I changed some things (in bold) in my class :

Code:
    [B]TextView txt;[/B]
    [B]InputStream is = null;
     String result = "";[/B]


    [B]txt=((TextView)this.findViewById(R.id.textView));[/B]
 
    
    [B]HttpEntity entity = response.getEntity();
     is = entity.getContent();[/B]
    
//convert to string
    [B]try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();
        }
        catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
        }


        txt.setText(result);[/B]
And it works just as expected! ;)
Just tried it on my Galaxy SII... Awesome!!!

Can you tell me if there's a better solution to show the 'Hello world' message please? Beside putting it in an existing TextView ?
Is there anything else I should modify to make it better ?

Yay, so happy my first android application worked! :D
Now I'll try more difficult things like databases and others! =)
 
I should have read the log cat before posting. Apologies. :x

Glad you got it sorted. =)

Edit: I highly recommend that you take Android's advice and place your network code in a separate thread. the AsyncTask class makes this incredibly easy, so there is really no excuse not to. The way you have it now, if your network operation hangs, then your UI will become entirely unresponsive.
 
Here is how you can convert your code to use AsyncTask:

Code:
public class Projet1Activity extends Activity {
    @Override
    final TextView tv;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        tv = (TextView) findViewById(R.id.textview);

        new AsyncTask<Void, Void, String>() {

              @Override
              protected String doInBackground(Void... params) {
                   // Creating HTTP client
                   HttpClient httpClient = new DefaultHttpClient();
                   // Creating HTTP Post
                   HttpPost httpPost = new HttpPost("http://192.168.1.10/android_connect/test.php");
 
                   // Making HTTP Request
                   try {
                       HttpResponse response = httpClient.execute(httpPost); 
            
                        // writing response to log
                        Log.i("Http Response:", response.toString());

                        HttpEntity entity = response.getEntity();
                        is = entity.getContent();
            
                        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                        StringBuilder sb = new StringBuilder();
                        String line = null;
                        while ((line = reader.readLine()) != null) {
                              sb.append(line + "\n");
                        }
                        is.close();

                        return sb.toString();

                  } catch (ClientProtocolException e) {
                      // writing exception to log
                      e.printStackTrace();
                  } catch (IOException e) {
                      // writing exception to log
                      e.printStackTrace();
                  }

                  return null;
              }

              @Override
               protected void onPostExecute(String result) {
                     tv.setText(result);
               }
         }.execute();
    }
}
 
Back
Top Bottom