簡體   English   中英

Android使用PHP在MySQL上進行連接

[英]Android connecting on MySQL using PHP

我試圖做我的第一個與MySQL上的連接的android應用程序,我谷歌很多,找到一些教程和類似的東西。 基於它們,我有以下代碼:

package com.example.helloworld;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    String name;
    String id;
    InputStream is=null;
    String result=null;
    String line=null;
    int code;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText e_id=(EditText) findViewById(R.id.editText1);
        final EditText e_name=(EditText) findViewById(R.id.editText2);
        Button insert=(Button) findViewById(R.id.button1);

        insert.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            id = e_id.getText().toString();
            name = e_name.getText().toString();

            insert();
        }
    });
    }

    public void insert()
    {
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

    nameValuePairs.add(new BasicNameValuePair("id",id));
    nameValuePairs.add(new BasicNameValuePair("name",name));

        try
        {
        HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://localhost/xampp/android_connect/index.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost); 
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            Log.e("pass 1", "connection success ");
    }
        catch(Exception e)
    {
            Log.e("Fail 1", e.toString());
            Toast.makeText(getApplicationContext(), "Invalid IP Address",
            Toast.LENGTH_LONG).show();
    }     

        try
        {
            BufferedReader reader = new BufferedReader
            (new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null)
        {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        Log.e("pass 2", "connection success ");
    }
        catch(Exception e)
    {
            Log.e("Fail 2", e.toString());
    }     

    try
    {
            JSONObject json_data = new JSONObject(result);
            code=(json_data.getInt("code"));

            if(code==1)
            {
        Toast.makeText(getBaseContext(), "Inserted Successfully",
            Toast.LENGTH_SHORT).show();
            }
            else
            {
         Toast.makeText(getBaseContext(), "Sorry, Try Again",
            Toast.LENGTH_LONG).show();
            }
    }
    catch(Exception e)
    {
            Log.e("Fail 3", e.toString());
    }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }    
}

我看不到任何錯誤或任何東西,但是當我嘗試加載它時,它說:“無效的IP地址”(這是catch {}的錯誤消息)。 我嘗試研究哪里可能有問題,在LogCat中我發現此錯誤:

11-16 10:39:10.036: I/ActivityManager(150): Start proc com.example.helloworld for activity com.example.helloworld/.MainActivity: pid=612 uid=10045 gids={3003, 1028}
11-16 10:39:10.386: E/Trace(612): error opening trace file: No such file or directory (2)
11-16 10:39:10.966: D/gralloc_goldfish(612): Emulator without GPU emulation detected.
11-16 10:39:11.016: I/ActivityManager(150): Displayed com.example.helloworld/.MainActivity: +1s32ms
11-16 10:39:11.066: I/Choreographer(150): Skipped 34 frames!  The application may be doing too much work on its main thread.
11-16 10:39:18.945: E/Fail 1(612): android.os.NetworkOnMainThreadException
11-16 10:39:18.975: E/Fail 2(612): java.lang.NullPointerException
11-16 10:39:18.975: E/Fail 3(612): java.lang.NullPointerException
11-16 10:39:19.195: D/dalvikvm(612): GC_CONCURRENT freed 191K, 4% free 6229K/6471K, paused 17ms+65ms, total 206ms
11-16 10:39:20.065: E/Fail 1(612): android.os.NetworkOnMainThreadException
11-16 10:39:20.075: E/Fail 2(612): java.lang.NullPointerException
11-16 10:39:20.075: E/Fail 3(612): java.lang.NullPointerException
11-16 10:39:20.645: E/Fail 1(612): android.os.NetworkOnMainThreadException
11-16 10:39:20.645: E/Fail 2(612): java.lang.NullPointerException
11-16 10:39:20.645: E/Fail 3(612): java.lang.NullPointerException
11-16 10:39:21.055: E/Fail 1(612): android.os.NetworkOnMainThreadException
11-16 10:39:21.065: E/Fail 2(612): java.lang.NullPointerException
11-16 10:39:21.065: E/Fail 3(612): java.lang.NullPointerException
11-16 10:39:21.535: E/Fail 1(612): android.os.NetworkOnMainThreadException
11-16 10:39:21.545: E/Fail 2(612): java.lang.NullPointerException
11-16 10:39:21.545: E/Fail 3(612): java.lang.NullPointerException
11-16 10:39:21.728: E/Fail 1(612): android.os.NetworkOnMainThreadException
11-16 10:39:21.735: E/Fail 2(612): java.lang.NullPointerException
11-16 10:39:21.735: E/Fail 3(612): java.lang.NullPointerException
11-16 10:39:21.925: E/Fail 1(612): android.os.NetworkOnMainThreadException
11-16 10:39:21.925: E/Fail 2(612): java.lang.NullPointerException
11-16 10:39:21.925: E/Fail 3(612): java.lang.NullPointerException
11-16 10:39:22.535: I/Choreographer(612): Skipped 37 frames!  The application may be doing too much work on its main thread.
: E/(): Device disconnected: 1
: E/(): Device disconnected

尤其是我看找不到目錄,我嘗試在瀏覽器中打開相同的地址,並且我沒有問題地打開它。 有人可以告訴我我在做什么錯嗎?

謝謝

localhost指向設備本身; 因此,您可以嘗試以下操作:

  • 如果出於測試目的在自己的網絡上運行此程序,請嘗試鍵入本地ip而不是localhost例如 http://192.168.0.123

  • 嘗試使用http://10.0.2.2而不是localhost ,在設備上的瀏覽器中鍵入它,然后查看其是否正確連接。

還要檢查這個問題

10.0.2.2的參考


關於NetworkOnMainThreadException

您正在嘗試應用程序的主線程上進行網絡操作,這可能會導致嚴重的延遲不可預測的結果

您應該始終使用AsyncTask進行網絡操作。 請參閱android docs中的這篇文章

這是一個示例用法;

您的AsyncTask應該如下所示:

 private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

        // params comes from the execute() call: params[0] is the url.
        try {

            // Initialize your parameters
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("id",urls[1]));
            nameValuePairs.add(new BasicNameValuePair("name",urls[2]));         

            // Make your HTTP Request
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(urls[0]);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost); 
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

            // Read the response
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null) {
             sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();

            // Return the response.
            return result;
        } catch (IOException e) {
            return "Unable to retrieve web page. URL may be invalid.";
        }
    }

    // onPostExecute gets the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {

        // Read your response into a JSONObject and do stuff...
        JSONObject json_data = new JSONObject(result);
        code=(json_data.getInt("code"));
        if(code==1)
        {
            Toast.makeText(getBaseContext(), "Inserted Successfully", Toast.LENGTH_SHORT).show();
        }
        else
        {
            Toast.makeText(getBaseContext(), "Sorry, Try Again", Toast.LENGTH_LONG).show();
        }
   }
}

您可以像這樣使用它:

// Params : url, id, name
new DownloadWebpageTask().execute("http://10.0.2.2/xampp/android_connect/index.php", "12345", "Foo Bar");

這是一個完整的示例,您的代碼應如下所示:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    String name;
    String id;
    InputStream is=null;
    String result=null;
    String line=null;
    int code;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText e_id=(EditText) findViewById(R.id.editText1);
        final EditText e_name=(EditText) findViewById(R.id.editText2);
        Button insert=(Button) findViewById(R.id.button1);

        insert.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                id = e_id.getText().toString();
                name = e_name.getText().toString();

                insert();
            }
        });
    }

    public void insert()
    {
        new DownloadWebpageTask().execute("http://10.0.2.2/xampp/android_connect/index.php", id, name);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

        // params comes from the execute() call: params[0] is the url.
        try {
            // Initialize your parameters
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("id",urls[1]));
            nameValuePairs.add(new BasicNameValuePair("name",urls[2]));         

            // Make your HTTP Request
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(urls[0]);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost); 
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

            // Read the response
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null) {
             sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();

            // Return the response.
            return result;
        } catch (IOException e) {
            return "Unable to retrieve web page. URL may be invalid.";
        }
    }

    // onPostExecute gets the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {

        // Read your response into a JSONObject and do stuff...
        JSONObject json_data = new JSONObject(result);
        code=(json_data.getInt("code"));
        if(code==1)
        {
            Toast.makeText(getBaseContext(), "Inserted Successfully", Toast.LENGTH_SHORT).show();
        }
        else
        {
            Toast.makeText(getBaseContext(), "Sorry, Try Again", Toast.LENGTH_LONG).show();
        }
   }
}
}

我認為您有兩個問題:

  1. localhost更改為計算機的IP地址
  2. 您正在UI線程上進行網絡調用,這對性能不利。 您可以改用AsyncTask或使用像Retrofit這樣的庫! ;)

你做錯了。 嘗試10.0.2.2/android_connect/index.php。 10.0.2.2重定向到您的xampp / htdoc /文件夾。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM