Victor Dolganiuc
Victor Dolganiuc

Reputation: 55

Android Java Http Request Post

I had created a simplest app, a default one and I want to try to post and retrive something from a php page MyActivty.Java looks like:

package com.dolganiuc.victor.myapplication;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class MainActivity extends ActionBarActivity {

    private static final String TAG = "victorMessage";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.i(TAG, "onCreate");
        postData();


    }

    public void postData() {

        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://93.117.158.187/");

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("id", "12345"));
            nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

            Log.i(TAG, response.toString());
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }

    }

}

And when Android Studio debugs that All Works fine, and i ran these app on 2 devecies Android 4.4.2 KitKat and Android 5.0 Lollipop and on both devices the application is closing retriving error Unfortunely MyApplication has closed.

What is the problem?

System.err

06-11 13:18:02.042    1142-1161/? W/System.err﹕ java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
06-11 13:18:02.042    1142-1161/? W/System.err﹕ at com.android.internal.telephony.PhoneBase.privatizeCellInfoList(PhoneBase.java:1252)
06-11 13:18:02.042    1142-1161/? W/System.err﹕ at com.android.internal.telephony.PhoneBase.getAllCellInfo(PhoneBase.java:1240)
06-11 13:18:02.042    1142-1161/? W/System.err﹕ at com.android.internal.telephony.PhoneProxy.getAllCellInfo(PhoneProxy.java:337)
06-11 13:18:02.042    1142-1161/? W/System.err﹕ at com.android.phone.PhoneInterfaceManager.getAllCellInfo(PhoneInterfaceManager.java:1486)
06-11 13:18:02.042    1142-1161/? W/System.err﹕ at com.android.internal.telephony.ITelephony$Stub.onTransact(ITelephony.java:691)
06-11 13:18:02.042    1142-1161/? W/System.err﹕ at android.os.Binder.execTransact(Binder.java:446)

Upvotes: 2

Views: 1641

Answers (1)

romtsn
romtsn

Reputation: 11982

The first problem may be that you didn't add the INTERNET permission in your AndroidManifest.xml. To resolve this just add this line <uses-permission android:name="android.permission.INTERNET" /> in your manifest.

The other problem is that you're trying to execute a post request on main thread. It causes NetworkOnMainThreadException. You should use AsyncTask or Handler to execute network requests, like this:

public class MainActivity extends ActionBarActivity {

    private static final String TAG = "victorMessage";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.i(TAG, "onCreate");
        new HttpPostTask().execute();
    }

    private class HttpPostTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://93.117.158.187/");

            try {
                // Add your data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("id", "12345"));
                nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // Execute HTTP Post Request
                HttpResponse response = httpclient.execute(httppost);

                Log.i(TAG, response.toString());
                return response.toString();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
            } catch (IOException e) {
                // TODO Auto-generated catch block
            }

            return null;
        }

        @Override
        protected void onPostExecute(String response) {
            super.onPostExecute(response);

            //do something with you response, connected with UI thread.
        }
    }
}

Upvotes: 2

Related Questions