-2

EDIT: addition to the answer below

I'm at a dead end. I looked for a lot of examples of a simple http post request, but I just can't get it to work...

My request is actually very simple: "What am I doing wrong?"

When I test the app it says "Unfortunately has stopped".

I'll give you the necessary codes:

All my imports

import android.graphics.Typeface;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.TextView;
import android.widget.Button;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

The necessary mainactivity.java functions

public void sync_btn_click(View v) {
        //Sync button click
        boolean varif = postData("hans");
        Toast.makeText(getApplicationContext(), String.valueOf(varif), Toast.LENGTH_SHORT).show();
    }

public boolean postData(String verif_code) {
    //Make new requesting clients
    HttpClient sync_client = new DefaultHttpClient();
    HttpPost get_verif = new HttpPost("http://www.google.nl");

    // Building post parameters, key and value pair
    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
    nameValuePair.add(new BasicNameValuePair("email", "user@gmail.com"));
    nameValuePair.add(new BasicNameValuePair("password", "encrypted_password"));

    //Encode post values
    try{
        get_verif.setEntity(new UrlEncodedFormEntity(nameValuePair));
    }catch (UnsupportedEncodingException e) {
        // writing error to Log
        e.printStackTrace();
    }

    //Make http request
    try {
        HttpResponse response = sync_client.execute(get_verif);

        // writing response to log
        Log.d("Http Response:", response.toString());

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

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

        return false;
    }
}

My AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.scridge.scridge" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.scridge.scridge.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>

</manifest>

The error logs

01-17 11:03:37.578    2977-2977/com.scridge.scridge E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.IllegalStateException: Could not execute method of the activity
            at android.view.View$1.onClick(View.java:3633)
            at android.view.View.performClick(View.java:4240)
            at android.view.View$PerformClick.run(View.java:17721)
            at android.os.Handler.handleCallback(Handler.java:730)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5103)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.reflect.InvocationTargetException
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at android.view.View$1.onClick(View.java:3628)
            at android.view.View.performClick(View.java:4240)
            at android.view.View$PerformClick.run(View.java:17721)
            at android.os.Handler.handleCallback(Handler.java:730)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5103)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: android.os.NetworkOnMainThreadException
            at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
            at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
            at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
            at java.net.InetAddress.getAllByName(InetAddress.java:214)
            at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
            at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
            at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
            at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
            at com.scridge.scridge.MainActivity.postData(MainActivity.java:88)
            at com.scridge.scridge.MainActivity.sync_btn_click(MainActivity.java:64)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at android.view.View$1.onClick(View.java:3628)
            at android.view.View.performClick(View.java:4240)
            at android.view.View$PerformClick.run(View.java:17721)
            at android.os.Handler.handleCallback(Handler.java:730)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5103)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)

I have the feeling it's not the request but something else. But I really don't know what.

Thanks in advance,

Luud

Addition to the answer Thanks to Jitesh Upadhyay I found the answer. I was not using AsyncTask to perform the request.

I found this site which exactly represents what I wanted to do.

Hope this also helps you!

Luud Janssen
  • 306
  • 1
  • 3
  • 12

1 Answers1

0

You're attempting to make a network connection on the main (UI) thread. This is not allowed in Android since it will halt the entire UI until you get a response from the server.

Try using AsyncTask, or performing the connection on a separate thread.

Hope this helps.

NetworkOnMainThreadException: The exception that is thrown when an application attempts to perform a networking operation on its main thread.

You should call method on asynctask then only code will work. To avoid it you should call it on another thread. Hence asynctask is better.

http://android-developers.blogspot.in/2009/05/painless-threading.html

http://android-er.blogspot.in/2012/04/androidosnetworkonmainthreadexception.html

here is link that illustrates how to use asynctask

Jitesh Upadhyay
  • 6,557
  • 1
  • 27
  • 44
  • Thanks for your quick reply! I get the problem now. Then there is the solution... I'm experimenting with AsyncTask now. I hope it will all work soon, so that I can make this question 'solved'. Thanks so far! – Luud Janssen Jan 17 '14 at 11:41
  • Update: I found this website: http://mobiledevtuts.com/android/android-http-with-asynctask-example/ It does exactly what I want. So I'm now going to try it out! – Luud Janssen Jan 17 '14 at 11:53
  • You sir, you just made my day! It worked! Many Thanks! – Luud Janssen Jan 17 '14 at 12:03
  • please raise the answer that it will be good for others!! – Jitesh Upadhyay Jan 17 '14 at 15:24