gpt4 book ai didi

php - 如何将Android与PHP和MySQL连接?

转载 作者:行者123 更新时间:2023-11-29 13:15:28 25 4
gpt4 key购买 nike

我正在尝试使用 PHP 和 MySQL 连接 Android 系统来创建一个简单的登录 Activity 。我正在使用在 4.2 Android 版本上运行的 genymotion 模拟器。

我在代码中使用线程使其在后台运行,并使用 JSON 顺利地取回数据。

但问题是系统崩溃并强行关闭。如果有人可以帮助我,我将不胜感激。

日志猫

02-02 21:29:46.260: E/AndroidRuntime(1363): FATAL EXCEPTION: main
02-02 21:29:46.260: E/AndroidRuntime(1363): android.os.NetworkOnMainThreadException
02-02 21:29:46.260: E/AndroidRuntime(1363): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
02-02 21:29:46.260: E/AndroidRuntime(1363): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
02-02 21:29:46.260: E/AndroidRuntime(1363): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
02-02 21:29:46.260: E/AndroidRuntime(1363): at libcore.io.IoBridge.connect(IoBridge.java:112)
02-02 21:29:46.260: E/AndroidRuntime(1363): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
02-02 21:29:46.260: E/AndroidRuntime(1363): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
02-02 21:29:46.260: E/AndroidRuntime(1363): at java.net.Socket.connect(Socket.java:842)
02-02 21:29:46.260: E/AndroidRuntime(1363): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
02-02 21:29:46.260: E/AndroidRuntime(1363): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
02-02 21:29:46.260: E/AndroidRuntime(1363): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
02-02 21:29:46.260: E/AndroidRuntime(1363): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
02-02 21:29:46.260: E/AndroidRuntime(1363): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
02-02 21:29:46.260: E/AndroidRuntime(1363): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
02-02 21:29:46.260: E/AndroidRuntime(1363): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
02-02 21:29:46.260: E/AndroidRuntime(1363): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
02-02 21:29:46.260: E/AndroidRuntime(1363): at pack.coderzheaven.JSONParser.makeHttpRequest(JSONParser.java:65)
02-02 21:29:46.260: E/AndroidRuntime(1363): at pack.coderzheaven.AndroidPHPConnectionDemo$CheckLogin$1.run(AndroidPHPConnectionDemo.java:118)
02-02 21:29:46.260: E/AndroidRuntime(1363): at android.os.Handler.handleCallback(Handler.java:730)
02-02 21:29:46.260: E/AndroidRuntime(1363): at android.os.Handler.dispatchMessage(Handler.java:92)
02-02 21:29:46.260: E/AndroidRuntime(1363): at android.os.Looper.loop(Looper.java:137)
02-02 21:29:46.260: E/AndroidRuntime(1363): at android.app.ActivityThread.main(ActivityThread.java:5103)
02-02 21:29:46.260: E/AndroidRuntime(1363): at java.lang.reflect.Method.invokeNative(Native Method)
02-02 21:29:46.260: E/AndroidRuntime(1363): at java.lang.reflect.Method.invoke(Method.java:525)
02-02 21:29:46.260: E/AndroidRuntime(1363): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
02-02 21:29:46.260: E/AndroidRuntime(1363): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-02 21:29:46.260: E/AndroidRuntime(1363): at dalvik.system.NativeStart.main(Native Method)

JSONParser.java

package pack.coderzheaven;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {

// Making HTTP request
try {

// check for request method
/*
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

}
*/
if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);

HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}


} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} 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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;

}
}

AndroidPHPConnection演示

package pack.coderzheaven;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AndroidPHPConnectionDemo extends Activity {
Button b;
EditText et, pass;
String Username, Password;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;

String pid;

// Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();


private static final String url_check_login = "http://10.0.3.2/check.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PERSON = "person";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "username";
private static final String TAG_pass = "password";

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

b = (Button) findViewById(R.id.Button01);
et = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
tv = (TextView) findViewById(R.id.tv);

b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// login();

// Getting complete person details in background thread
new CheckLogin().execute();

}
});
}

/**
* Background Async Task to Get complete person details
* */
class CheckLogin extends AsyncTask<String, String, String> {

/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AndroidPHPConnectionDemo.this);
pDialog.setMessage("Loading person details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

/**
* Getting person details in background thread
* */

@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));

// getting person details by making HTTP request
// Note that person details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_check_login, "GET", params);

// check your log for json response
Log.d("Single person Details", json.toString());

// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received person details
JSONArray productObj = json
.getJSONArray(TAG_PERSON); // JSON Array

// get first product object from JSON Array
JSONObject person = productObj.getJSONObject(0);

et.setText(person.getString(TAG_NAME));
pass.setText(person.getString(TAG_pass));

Log.e("success in login", "SUCCESS IN LOGIN");

}

else {
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});

return null;
}

/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}

检查.php

<?php

require_once('db_config.php');


// array for JSON response
$response = array();


//if(isset($_GET['Username'])and isset($_POST['Password'])){

if(isset($_GET['pid'])){
// $username = $_POST['Username'];
// $password = $_POST['Password'];

$pid = $_GET['pid'];

// $query_search = "select username, password from members where username = '".$username."' AND password = '".$password. "'";

$query_search = "select from members where pid = '".$pid."'";

$query_exec = mysql_query($query_search) or die(mysql_error());

if (mysql_num_rows($query_exec) > 0)
{
$result = mysql_fetch_array($query_exec);

$person = array();
$person['username']=$result[username];
$person['password']=$result['password'];

// success
$response["success"] = 1;

// user node
$response["person"] = array();

array_push($response["person"], $person);

// echoing JSON response
echo json_encode($response);

}
else
{
// no user found
$response["success"] = 0;
$response["message"] = "No User found";

// echo no users JSON
echo json_encode($response);
}
}
else
{
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
}
?>

最佳答案

问题出在 AsyncTask 内的 runOnUiThread 上。您收到异常是因为您占用 UI 线程的时间太长。使用 AsyncTask 是正确的做法,但是您从其中调用 runOnUiThread,这是没有意义的,因为这样它就不再是异步的。

  1. 从其中删除 runOnUiThread 部分doInBackground()。
  2. 保留您想要在屏幕上显示的值作为异步任务的成员或作为结果模板参数。
  3. 将 setText 调用放在 postExecute 中,因为它是在 UI 上运行的线程。

类似这样的事情:

/**
* Background Async Task to Get complete person details
* */
class CheckLogin extends AsyncTask<String, String, String> {

JSONArray productObj;

/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AndroidPHPConnectionDemo.this);
pDialog.setMessage("Loading person details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

/**
* Getting person details in background thread
* */

@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub

int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));

// getting person details by making HTTP request
// Note that person details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_check_login, "GET", params);

// check your log for json response
Log.d("Single person Details", json.toString());

// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received person details
productObj = json
.getJSONArray(TAG_PERSON); // JSON Array

}

else {
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}

return null;
}

/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details


if ( productObj != null ) {
// get first product object from JSON Array
JSONObject person = productObj.getJSONObject(0);

et.setText(person.getString(TAG_NAME));
pass.setText(person.getString(TAG_pass));

Log.e("success in login", "SUCCESS IN LOGIN");
}

pDialog.dismiss();
}
}

关于php - 如何将Android与PHP和MySQL连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21516693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com