我正在尝试创建一个可以使用 JSON 将数据发送到 PHP 服务器的 android 应用程序。我遵循了本指南:http ://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/这是我的 Android 代码:
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class HelloWorldActivity extends Activity {
JSONParser jsonParser = new JSONParser();
EditText userName;
// url to create new product
private static String url = "http://192.168.1.35/workspace/sosapp/db_connect.php";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Edit Text
userName = (EditText) findViewById(R.id.userName);
// Send button
Button sendButton = (Button) findViewById(R.id.sendButton);
// button click event
sendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = userName.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
// getting JSON Object
JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);
}
});
}
}
至于我的 PHP 代码:
function insert($var1) {
// mysql inserting a new row
$result = mysql_query("INSERT INTO report (name) VALUES ('$var1')");
// check if row inserted or not
if ($result) {
// successfully inserted into database;
$msg = "Message received.";
} else {
$msg = "Not received.";
}
return ($msg);
}
if (isset($_POST['name'])) {
$name = $_POST['name']);
insert($name);
} else {
echo "No input.";
}
我一直没有输入。我运行 android 应用程序(在连接到计算机的手机上),然后刷新 PHP 站点,但一直没有输入。android 应用程序不发送数据。有人可以帮忙吗?非常感谢!