0

some error occur when i try to connect database with php. here is my code.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);
    String result = null;
    InputStream is = null;

    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://127.0.0.1:80/webservice/index.php");
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

        Log.e("log_tag", "connection success");
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    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 (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try{
        JSONArray jArray = new JSONArray(result);
        JSONObject json_data = jArray.getJSONObject(1);

    } catch (JSONException e) {
        e.printStackTrace();
    }

}

HERE IS MY LOG

 01-01 18:25:52.724  22488-22488/com.example.lean.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.lean.myapplication, PID: 22488
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lean.myapplication/com.example.lean.myapplication.MyActivity}: android.os.NetworkOnMainThreadException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2276)
            at android.app.ActivityThread.access$800(ActivityThread.java:143)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1221)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5094)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: android.os.NetworkOnMainThreadException
            at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
            at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
            at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
            at libcore.io.IoBridge.connect(IoBridge.java:112)
            at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
            at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:460)
            at java.net.Socket.connect(Socket.java:833)
            at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
            at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
            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.example.lean.myapplication.MyActivity.onCreate(MyActivity.java:39)
            at android.app.Activity.performCreate(Activity.java:5249)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1096)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2190)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2276)
            at android.app.ActivityThread.access$800(ActivityThread.java:143)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1221)
Utkarsh Dixit
  • 4,267
  • 3
  • 15
  • 38
  • 1
    possible duplicate of [android.os.NetworkOnMainThreadException](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception) – laalto Jan 01 '15 at 10:35

1 Answers1

0

Just Copy the below code and replace it with your code. But from the next time please remember to keep the network request part in an AsyncTask. Heavy task is always need be in separate thread.

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;

import com.example.database.Database_adapter;
import com.example.dataset.ProductDataset;
import com.example.point_of_sale.R;
import com.example.point_of_sale.asyncs.GetProductLisTask;
import com.example.point_of_sale.asyncs.GetProductLisTask.OnGettingAllProductListener;

public class TestActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

        new TestAsyncTask(TestActivity.this).execute();
    }

    public class TestAsyncTask extends AsyncTask<String, Integer, String> {


        Context ctx;

        public TestAsyncTask(Context _ctx) {
            this.ctx = _ctx;
        }

        protected String doInBackground(String... urls) {

            String result = null;
            InputStream is = null;

            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(
                        "http://127.0.0.1:80/webservice/index.php");
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

                Log.e("log_tag", "connection success");
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            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();

                return result;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }

        protected void onPostExecute(String result) {

            try {
                JSONArray jArray = new JSONArray(result);
                JSONObject json_data = jArray.getJSONObject(1);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }

}

Read About Asynctask here

techierishi
  • 413
  • 3
  • 14
  • ArrayList obj_item_name = new ArrayList(); what is the purpose with this??? however i still get some error when replacing your code. please help. thanks so much –  Jan 01 '15 at 12:56
  • I have removed that unused code. About the new error message : I provided you the solution for getting rid of "NetworkOnMainThreadException" and the new error message does not seem to be related with the new one. You need to do some workaround to solve it. Probably [this](http://stackoverflow.com/questions/19739269/gl-error-from-openglrenderer-0x502) can help you. – techierishi Jan 01 '15 at 16:14