android 工作室:将数据库与 php 链接

android studio: linking database with php

当我尝试使用 php 连接数据库时发生了一些错误。 这是我的代码。

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();
    }

}

这是我的日志

 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.access0(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.access0(ActivityThread.java:143)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1221)

只需复制以下代码并将其替换为您的代码。但从下一次开始,请记住将网络请求部分保留在 AsyncTask 中。繁重的任务总是需要在单独的线程中。

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();
            }
        }

    }

}

了解 Asynctask here